开玩笑的文档说,There are two ways to get your hands on mock functions: Either by require()ing a mocked component (via jest.mock('moduleName')) or by explicitly requesting one from jest.fn() in your test:
所以我正在尝试模拟函数思维,每当测试调用minus
函数时,它都会执行模拟函数并返回10
而不是a*b
但它没有按照我的想法工作。
应用.js:
function add(a, b) {
return multiply(a, b) + b;
}
function multiply(a, b) {
return a * b;
}
module.exports = add;
添加测试.js
const add = require('./add');
describe('add', () => {
it('should add two numbers', () => {
const multiply = jest.fn((a, b) => {10})
expect(add(1, 2)).toBe(12);
});
});
注意:如果我将expect(add(1, 2)).toBe(12);
更改为expect(add(1, 2)).toBe(4);
测试将通过,但我想模拟multiply
并返回 10。因此,当我实际调用 make 到函数multiply
时,它应该调用模拟函数而不是真正的实现。
您必须稍微更改app.js
的结构才能按照您想要的方式进行测试。
您可以将multiply()
提取到其自己的文件中,如下所示:
多样的.js
function multiply(a, b) {
return a * b;
}
应用.js
function add(a, b) {
return multiply(a, b) + b;
}
添加测试.js
const add = require('./add');
const multiply = require('./multiply');
jest.mock('multiply', () => jest.fn(a, b) => 10)
describe('add', () => {
it('adds the numbers', () => {
expect(add(1, 2)).toBe(12);
});
});
或者将实现更改为如下所示:
添加.js
function add(multiply) {
multiply()
}
添加测试.js
const add = require('./add');
describe('add', () => {
it('adds the numbers', () => {
const multiply = jest.fn(a,b) => 10;
expect(add(multiply(1, 2)).toBe(12);
});
});