我在一个文件中有两个功能
// file1.ts
const function1 = () => {
return 123;
};
const function2 = () => {
return function1() + 2;
}
export{
function1,
function2
}
我正在使用功能2的玩笑编写单元测试,但是我无法模拟function1
我只是尝试使用jest.spyOn来模拟function1
import * as helperFunctions from "file1";
describe("test function2 ", () => {
let functionSpy: any;
beforeAll(() => {
functionSpy = jest.spyOn(helperFunctions , "function1 ");
});
afterAll(() => {
functionSpy.mockReset();
});
test("test", () => {
functionSpy.mockReturnValue(1);
expect(helperFunctions.function2()).toEqual(3);
});
});
在我的测试中,function1没有被模拟,它仍然调用实际的实现。 任何帮助表示赞赏。
答案 0 :(得分:0)
这是解决方案:
index.ts
:
const function1 = () => {
return 123;
};
const function2 = () => {
return exports.function1() + 2;
};
exports.function1 = function1;
exports.function2 = function2;
单元测试:
describe('test function2 ', () => {
const helperFunctions = require('./');
helperFunctions.function1 = jest.fn();
test('test', () => {
helperFunctions.function1.mockReturnValueOnce(1);
expect(helperFunctions.function2()).toEqual(3);
});
});
单元测试结果:
PASS src/stackoverflow/56354252/index.spec.ts
test function2
✓ test (8ms)
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 2.696s, estimated 3s
您可以找到此问题的更多详细信息:https://github.com/facebook/jest/issues/936#issuecomment-214939935