嘲笑模拟模块多次具有不同的值 [英] Jest mock module multiple times with different values
问题描述
我有一个要测试的功能,该功能使用导入的模块:
I have a function that I want to test and this function uses an imported module:
var a = require('./a');
function add(b) {
return a + b;
}
module.exports = add;
该a
模块在此示例中返回一个数字,但在我的真实项目中,我将其用作配置对象,该对象会不时手动更改.
That a
module returns a number in this sample, but in my real project I use that as a config object that is changed from time to time manually.
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
模块?
First test passes, The second test fails because it inherits from the first mock. Is there any way to mock the a
module multiple times?
我想要一个不暗示重构add
函数,而是专注于多次模拟该模块的解决方案. (在我的实际项目中是配置文件)
I would like a solution that doesn't imply refactoring the add
function and instead focus on mocking that module multiple times. (in my real project that is a config file)
您可以在此处使用以下代码: https://repl.it/@adyz/NocturnalBadComma
You can play around with the code here: 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);
});
});
演示: https://repl.it/repls/TrustingBelatedProprietarysoftware
这篇关于嘲笑模拟模块多次具有不同的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!