如何使用 jest.fn() 模拟函数



开玩笑的文档说,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);
});
});

最新更新