如何测试包含调用同一模块中其他函数的函数的模块是有限制的。请参阅这篇文章以获取更多见解 https://medium.com/@DavideRama/mock-spy-exported-functions-within-a-single-module-in-jest-cdf2b61af642。在那篇文章中,解决这个问题的方法很少,因此我建议在深入研究我的粗略实现之前先看一下它,因为它可能无法 100% 适用于您的代码结构。
工作示例:
代码沙盒 https://codesandbox.io/s/async-shape-e2mjc?file=/src/utils.js
Utils
对原始版本稍作修改,因此您可能需要根据需要在 util 模块中模仿这一点。
const isDualScreen = () => {
return window.width > 1000 ? true : false;
};
const autoScreenAdd = element => {
if (utilMethods.isDualScreen()) {
utilMethods.dualScreenAdd(element);
} else {
utilMethods.singleScreenAdd(element);
}
};
const dualScreenAdd = element => {
return element;
};
const singleScreenAdd = element => {
return element;
};
// This is important, it allows you to mock the functions properly in your tests.
// Use this same structure in your singleScreenMethods and dualScreenMethods modules
const utilMethods = {
singleScreenAdd,
dualScreenAdd,
autoScreenAdd,
isDualScreen
};
export default utilMethods;
测试实例
import utilMethods from "./utils";
describe("isSingleScreen", () => {
beforeEach(() => {
jest.clearAllMocks();
jest.spyOn(utilMethods, "isDualScreen").mockReturnValue(true);
});
it("autoScreenAdd", () => {
// Arrange
const singleScreenAddSpy = jest.spyOn(utilMethods, "singleScreenAdd");
const dualScreenAddSpy = jest.spyOn(utilMethods, "dualScreenAdd");
// Act
utilMethods.autoScreenAdd({});
// Assert
expect(singleScreenAddSpy).toHaveBeenCalledTimes(0);
expect(dualScreenAddSpy).toHaveBeenCalledTimes(1);
});
});