你如何在 Jest 中模拟模块范围的变量?

时间:2021-04-11 12:22:33

标签: javascript testing jestjs mocking

考虑以下函数:

let dictionary = {
  there: "there"
}

function sayHi(word){
  if (dictionary.hasOwnProperty(word)){
    return "hello " + dictionary[word] 
  }
}

如果我想测试 sayHi 函数,我将如何在 Jest 测试中模拟 dictionary 变量?

我尝试从模块中导入所有内容并覆盖字典对象,但没有奏效,同样我也尝试将其模拟为函数,但仍然无法使其工作。

1 个答案:

答案 0 :(得分:0)

您可以使用 rewire 包来覆盖模块内的变量。

例如

index.js

let dictionary = {
  there: 'there',
};

function sayHi(word) {
  if (dictionary.hasOwnProperty(word)) {
    return 'hello ' + dictionary[word];
  }
}

module.exports = { sayHi };

index.test.js

const rewire = require('rewire');

describe('67044925', () => {
  it('should pass', () => {
    const mod = rewire('./');
    mod.__set__('dictionary', { there: 'teresa teng' });
    const actual = mod.sayHi('there');
    expect(actual).toEqual('hello teresa teng');
  });

  it('should pass too', () => {
    const mod = rewire('./');
    mod.__set__('dictionary', { there: 'slideshowp2' });
    const actual = mod.sayHi('there');
    expect(actual).toEqual('hello slideshowp2');
  });
});

单元测试结果:

 PASS  examples/67044925/index.test.js (12.148 s)
  67044925
    ✓ should pass (15 ms)
    ✓ should pass too (4 ms)

Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        14.047 s
相关问题