【问题标题】:Using requireActual isn't requiring the actual version of module, in a Jest test在 Jest 测试中,使用 requireActual 不需要模块的实际版本
【发布时间】:2019-02-08 04:03:29
【问题描述】:

我有一个 Jest 测试文件,如下所示:

// utils.test.js
let utils = require('./utils')

jest.mock('./utils')

test('print items', () => {
  utils.printItems(['a'])
  expect(utils.getImage).toHaveBeenLastCalledWith('a.png')
})

test('get image', () => {
  utils = require.requireActual('./utils')

  // `utils` is still mocked here for some reason.
  expect(utils.getImage('note.png')).toBe('note')
})

还有这样的模拟:

// __mocks__/utils.js
const utils = require.requireActual('../utils');

utils.getImage = jest.fn(() => 'abc');

module.exports = utils;

然而,正如您在我在第二个测试中的评论中看到的那样,utils 仍然是模拟版本,而不是模块的实际版本。这是为什么?我怎样才能让它成为实际版本,而不是模拟版本?

【问题讨论】:

  • jest.isMockFunction 如果函数没有按照您期望的方式模拟,则有助于不运行测试

标签: javascript node.js unit-testing mocking jestjs


【解决方案1】:

您仍然在第二次测试中获得了模拟的 utils 模块,因为您实际上在手动模拟 (__mocks__/utils.js) 中需要它,在 Jest 的缓存中仍然被引用为应该返回的模拟,因为 jest.mock() 是在最顶端。

修复它的一种方法是不在手动模拟中使用该模块,或者更新您的第二个测试以取消模拟并要求它的新版本。例如:

test('get image', () => {
  jest.unmock('./utils')
  const utils = require.requireActual('./utils')

  // `utils` is now the original version of that module
  expect(utils.getImage('note.png')).toBe('note')
})

【讨论】:

  • 我添加了 jest.unmock('./utils') 行(以及我已经拥有的其他代码),但不幸的是,它似乎没有任何改变。
  • 你在哪里添加 jest.unmock() ?您能否发布您认为效果不佳的更新测试代码?
  • 我说的和你说的一模一样;我把它放在测试中,作为第一行,就在 requireActual 之前。
  • @chiyanc22 @Gary 我认为在jest.unmock() 通话之后你还需要做jest.resetModules()
猜你喜欢
  • 2015-02-05
  • 2020-08-30
  • 1970-01-01
  • 2018-09-14
  • 2017-02-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-30
相关资源
最近更新 更多