我有以下文件要测试
functions.js
function funcOne() {
return funcTwo()
}
function funcTwo() {
return "func two"
}
module.exports = {
funcOne,
funcTwo
}
我想模拟funcTwo,以便在通过functions.funcOne
调用时返回不同的字符串
functions.test.js
function mockFunctions() {
const original = require.requireActual("./functions")
return {
...original, //Pass down all the exported objects
funcTwo: jest.fn(() => {
return "my test func"
})
}
}
jest.mock("./functions", () => mockFunctions())
const functions = require.requireMock("./functions")
it("renders without crashing", () => {
console.log(functions.funcOne())
})
它仍然显示“ func two”而不是“我的测试功能”。
有没有办法让模块保持完整并仅模拟一个特定方法?
答案 0 :(得分:0)
这是一个解决方案:
functions.js
:
function funcOne() {
return exports.funcTwo();
}
function funcTwo() {
return 'func two';
}
exports.funcOne = funcOne;
exports.funcTwo = funcTwo;
单元测试:
functions.spec.js
const functions = require('./functions');
describe('functions test suites', () => {
it('funcOne', () => {
const funcTwoSpyOn = jest.spyOn(functions, 'funcTwo').mockReturnValueOnce('my test func');
const actualValue = functions.funcOne();
expect(actualValue).toBe('my test func');
expect(funcTwoSpyOn).toBeCalledTimes(1);
funcTwoSpyOn.mockRestore();
});
it('funcTwo', () => {
const actualValue = functions.funcTwo();
expect(actualValue).toBe('func two');
});
});
覆盖率100%的单元测试结果:
PASS src/stackoverflow/53889291/functions.spec.js
functions test suites
✓ funcOne (5ms)
✓ funcTwo
--------------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
--------------|----------|----------|----------|----------|-------------------|
All files | 100 | 100 | 100 | 100 | |
functions.js | 100 | 100 | 100 | 100 | |
--------------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests: 2 passed, 2 total
Snapshots: 0 total
Time: 3.199s
以下是完整的演示:https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/53889291