【问题标题】:Jest method-invocation count is wrong?Jest 方法调用计数错误?
【发布时间】:2020-01-09 06:50:55
【问题描述】:

考虑代码 -

// 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-cdf2b61af642https://github.com/facebook/jest/issues/936,但无法通过多种排列解决这个问题。

你觉得这有什么问题吗?

【问题讨论】:

  • 您好,尝试在调用 bar(a) 时添加等待。 export const foo = async (a, b) => { // 做一些事情 await bar(a) }
  • 调试器中的调用实际上进入了方法。
  • await 的事情不走运,似乎与分享的中篇文章更相关。
  • 导入方式不起作用 - stackoverflow.com/questions/51269431/jest-mock-inner-function。这是在 node.js 中
  • 这和jest有关,但是export是如何工作的。您是否尝试将 b 移动到不同的文件并导出它?

标签: javascript node.js mocking jestjs


【解决方案1】:

正如您共享的article 中所述,在您的utils.js 文件中,您正在导出一个具有foobar 的对象。您的utils.spec.js 实际上导入了exports.fooexports.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

【讨论】:

  • 谢谢 - 我之前试过这个,但我认为我在导入时犯了错误,这没有用。
【解决方案2】:

正如@bhargav-shah 所说,当您用 jest 监视模块函数时,实际上是在监视其导出的函数值,而不是内部函数本身。

这是因为 commonJS 模块的工作方式。使用 ES 模块环境,您实际上可以在不修改代码的情况下实现您在此处尝试执行的操作,因为导出将是绑定。更深入的解释可以在here找到。

目前 Jest 不支持 ES 模块,因此使代码正常工作的唯一方法是从 foo 函数中调用实际导出的函数:

// utils.js
export const foo = async (a, b) => {
   // do something
   // Call the actual exported function
   exports.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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-29
    • 2015-11-28
    • 1970-01-01
    • 1970-01-01
    • 2017-12-31
    • 2018-05-20
    • 2017-06-07
    相关资源
    最近更新 更多