javascript - 在 Jest 测试中,使用 requireActual 不需要模块的实际版本

标签 javascript node.js unit-testing mocking jestjs

我有一个 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仍然是模拟版本而不是模块的实际版本。这是为什么?我怎样才能让它成为实际版本,而不是模拟版本?

最佳答案

您仍然在第二次测试中获得了模拟的 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')
})

关于javascript - 在 Jest 测试中,使用 requireActual 不需要模块的实际版本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52143961/

相关文章:

javascript - 是否可以将名为通配符的单行重新导出?

javascript - JS : Is eval really secure?

javascript - Node.js 应用程序中的 SequelizeConnectionError

javascript - Chart js旧图表数据未清除

java - 具有模拟上下文的 Hadoop 单元测试

javascript - 在 Jest 测试中将通用数据放在哪里

javascript - AVA:为每个测试用例设置不同的超时

javascript - WCF Restfull WS post方法和HTML表单

javascript - 如何使用 Python 触发 javascript 事件

javascript - 从更新的项目更新时,在云函数中创建引用的 Firestore 文档