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

问题描述 投票:0回答:1

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

javascript node.js unit-testing mocking jestjs
1个回答
0
投票

您仍然在第二次测试中获得模拟的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')
})
© www.soinside.com 2019 - 2024. All rights reserved.