我有一个我想测试的函数,这个函数使用了一个导入的模块:
var a = require('./a');
function add(b) {
return a + b;
}
module.exports = add;
a
模块在此示例中返回一个数字,但在我的实际项目中,我将其用作配置对象,该对象会不时手动更改。
var a = 1;
module.exports = a;
add
函数的测试如下所示:
describe('add', () => {
it('should add the mock number 1 to 2', () => {
jest.setMock('./a', 1);
const add = require('./add');
expect(add(2)).toBe(3);
});
it('should add the mock number 2 to 2', () => {
jest.setMock('./a', 2);
const add = require('./add');
expect(add(2)).toBe(4);
});
});
第一个测试通过,第二个测试失败,因为它继承自第一个模拟。有没有办法多次模拟a
模块?
我想要一个不暗示重构 add
函数的解决方案,而是专注于多次模拟该模块。 (在我的真实项目中是一个配置文件)
您可以使用此处的代码:https://repl.it/@adyz/NocturnalBadComma
最佳答案
添加
beforeEach(() => {
jest.resetModules();
});
最终测试
describe('add', () => {
beforeEach(() => {
jest.resetModules();
});
it('should add the mock number 5 to 2', () => {
jest.setMock('./a', 5);
const add = require('./add');
expect(add(2)).toBe(7);
});
it('should add the mock number 2 to 2', () => {
jest.setMock('./a', 2);
const add = require('./add');
expect(add(2)).toBe(4);
});
});
关于javascript - 多次使用不同的值开 Jest 模拟模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49650323/