【问题标题】:Making assertions on Jest manual mocks对 Jest 手动模拟进行断言
【发布时间】:2019-05-19 05:14:09
【问题描述】:

我在使用手动 Jest 模拟时遇到了一些问题,需要一些帮助。

我正在测试的文件如下所示:

import withTranslation from '../utils/withTranslation'

withTranslation('test')

我在这样的测试文件中模拟一个模块。

import withTranslation from '../utils/withTranslation'

jest.mock('../utils/withTranslation')

// tests here

我在../utils/__mocks__/withTranslation.js 有手动模拟,代码如下:

const impl = (...args) => {
  console.log('in mock', args)
  return args
}

export default impl

当测试运行时,使用了 mock,我可以看到控制台日志。到目前为止一切顺利。

但是,我希望能够在 withTranslation 被嘲笑时对它的使用做出断言。例如,expect(withTranslation).toHaveBeenCalledWith('test')

因此,我将手动模拟更改为 Jest 模拟函数,其实现与以前相同。

const impl = (...args) => {
  console.log('in mock 1', args)
  return args
}

// only difference is wrapping in jest.fn()
export default jest.fn(impl)

现在运行测试时,使用了一个通用的 Jest 模拟函数,我看不到控制台日志,所以我的假实现永远不会被调用。有什么想法吗?

【问题讨论】:

    标签: node.js unit-testing jestjs


    【解决方案1】:

    我的问题中的代码是正确的。发生这种情况的原因是因为我的测试套件有一个全局的 beforeEach 调用 jest.resetMocks()。希望这可以为某人节省几个小时。

    【讨论】:

    • 不幸的是,这似乎不再起作用了。
    【解决方案2】:

    实际模块中的函数withTranslation 在测试开始之前已经被模拟替换,并且这个替换不是通过引用完成的。因此,当您断言模拟 withTranslation 时,断言失败,因为永远不会调用模拟函数,而是调用实际模块中的 withTranslation 方法。

    您的控制台日志仍然出现,因为正如我上面所说,“真实”模块的功能已被模拟替换。

    所以导入实际的withTranslation 并声明它,它将解决您的问题。

    感谢answer.

    【讨论】:

      猜你喜欢
      • 2017-05-23
      • 2017-10-01
      • 2019-06-09
      • 2020-01-27
      • 2018-09-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多