考虑代码-
// utils.js
export const foo = async (a, b) => {
// do something
bar(a)
}
export const bar = async (a) => {
// do something
}
// utils.spec.js
const utils = require('./utils');
const barSpy = jest.spyOn(utils, 'bar');
const result = await utils.foo('a', 'b');
expect(barSpy).toHaveBeenCalledTimes(1);
测试失败-
Error: expect(jest.fn()).toHaveBeenCalledTimes(expected)
Expected number of calls: 1
Received number of calls: 0
我读了https://medium.com/@DavideRama/mock-spy-exported-functions-within-a-single-module-in-jest-cdf2b61af642和 https://github.com/facebook/jest/issues/936但无法通过多个排列解决此问题。
您认为这有什么问题吗?
最佳答案
如 article 中所述在您共享的 utils.js
文件中,您正在导出一个包含 foo
和 bar
的对象。您的 utils.spec.js
实际上导入了 exports.foo
和 exports.bar
。因此,您模拟 exports.bar
通过如下更改 utils.js
,当您模拟 bar 时,您将模拟 foo 使用的实际 bar。
utils.js
const bar = async () => {};
const foo = async () => {
exportFunctions.bar();
};
const exportFunctions = {
foo,
bar
};
module.exports = exportFunctions;
在这个 codesandbox 中查看实际操作.您可以打开一个新终端(右下角)并在浏览器中运行 npm test
关于javascript - Jest 方法调用计数错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57821225/