我有一个如下所示的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()
位于最顶层的范围,因此仍被引用为应该返回的模拟。
修复它的一种方法是不在手动模拟中使用该模块,或者将第二个测试更新为 unmock 并需要它的新版本。例如:
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')
})