【发布时间】:2021-08-22 02:08:37
【问题描述】:
我正在编写一些代码,我有一个我想要实现的虚拟场景,如下所示。我有一个正在测试的函数,它使用来自不同模块的函数。我想模拟导入模块的功能。我该怎么做呢?
我见过this solution,但jest.doMock 函数在commonJS 中不起作用——这是我的理解。这是一个节点后端项目。
任何帮助将不胜感激。谢谢
// helper.js
let add = (a, b) => a + b;
let mult = (a, b) => a * b;
module.exports = { add, sub, mult };
// index.js
const { add, mult } = require('./helper');
const add5thenMultiply2 = (a) => {
const res1 = add(a, 5);
return mult(res1, 2);
};
module.exports = { add5thenMultiply2 };
// index.test.js
const { add5thenMultiply2 } = require('./index');
describe('index', () => {
it('returns right value', () => {
const input = 3;
const expected = 16;
const result = add5thenMultiply2(input);
expect(result).toEqual(expected);
});
it('works with mock', () => {
// mock add() such that it always returns 100, but for this test only
const input = 3;
const expected = 200;
const result = add5thenMultiply2(input);
expect(result).toEqual(expected);
});
});
【问题讨论】:
标签: javascript unit-testing testing jestjs mocking