我正在为一个函数编写单元测试,该函数调用同一模块内的另一个函数。
例如。
export function add(a, b) {
return a + b
}
export function showMessage(a, b) {
let sum = add(a, b)
return `The sum is ${sum}`
}
测试:
import * as Logics from './logics;
describe('showMessage', () => {
it('should return message with sum', () => {
let addSpy = jest.spyOn(Logics, 'add')
let showMessageResponse = Logics.showMessage(2, 2)
expect(addSpy).toHaveBeenCalledTimes(1)
});
});
我想测试执行showMessage时是否调用了add函数。上面的错误如下:
预计来电次数:1 接听电话数量:0
我找到了一个解决方案,但需要更改函数导出的方式:
function add(a, b) {
return a + b
}
function showMessage(a, b) {
const sum = Logics.add(a, b)
return `The sum is ${sum}`
}
const Logics = {
showMessage,
add
}
export default Logics
我不想改变导出函数的方式。
理想情况下,您应该独立测试功能。一项测试不负责另一项功能测试的功能。
不是最好的方法,但你可以这样做:
util.js
export function add(a, b) {
return a + b;
}
export function showMessage(a, b, addNew = add) {
let sum = addNew(a, b);
return `The sum is ${sum}`;
}
在你的测试中你可以这样做:
util.test.js
import * as Logics from "./util";
describe("showMessage", () => {
it("should return message with sum", () => {
let addSpy = jest.spyOn(Logics, "add");
addSpy.mockReturnValue(123);
let showMessageResponse = Logics.showMessage(2, 2, addSpy);
expect(addSpy).toHaveBeenCalledTimes(1);
expect(showMessageResponse).toBe(`The sum is 123`);
});
});
这是您可以使用的沙箱:https://codesandbox.io/s/jest-test-forked-9zk1s4?file=/util.test.js:0-366
总而言之,如果不改变出口,你就无法真正实现这一目标。您可以阅读原因(也许还有其他选项)此答案以及此答案。
更好的选择在我看来是这样的(在你的logics.js文件中):
import * as Logics from './logics;
并在
showMessage
函数中像第二个示例中那样使用它:
const sum = Logics.add(a, b)
基本上只需导入logics.js中的所有内容并使用该值即可获取对相同
add
函数的引用。
附加说明:虽然您正确地模拟了
add
,但这与 showMessage 中调用的函数不同,您基本上无法模拟该函数(您也可以检查此代码以获取证明
describe("showMessage", () => {
it("should return the mocked sum (PASSES)", () => {
jest.spyOn(Logics, "add").mockReturnValue(123);
const showMessageResponse = Logics.add(2, 2);
expect(showMessageResponse).toBe(123);
});
it("should return message with sum (FAILS)", () => {
let addSpy = jest.spyOn(Logics, "add").mockReturnValue(123);
const showMessageResponse = Logics.showMessage(2, 2);
expect(addSpy).toHaveBeenCalledTimes(0);
expect(showMessageResponse).toBe(`The sum is 123`);
});
});
) 还发布了在此沙箱中