问题描述
我有一个Jest测试文件,如下所示:
I have a Jest test file like the following:
// 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
仍然是模块的模拟版本,而不是模块的实际版本.这是为什么?我怎样才能使它成为实际版本,而不是模拟版本?
Yet as you can see in my comment in the second test, utils
is still the mocked version rather than the actual version of the module. Why is that? How can I get it to be the actual version, rather than the mocked version?
推荐答案
您仍然可以在第二次测试中获得模拟的utils模块,因为您实际上已在手动模拟(__mocks__/utils.js
)中使用了该模块,该模块在Jest的缓存中仍然存在引用为模拟,由于jest.mock()
处于最高级作用域,因此应返回.
You still get the mocked utils module in your second test because you have actually required it inside the manual mock (__mocks__/utils.js
), which in Jest's cache is still referenced as a mock that should be returned due to jest.mock()
being at the top most scope.
解决此问题的一种方法是不使用手动模拟中的模块,或者更新第二个测试以取消模拟并需要新版本的模块.例如:
A way to fix it is either to not use the module in a manual mock, or update your second test to unmock and require a new version of it. For example:
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测试中,使用requireActual不需要模块的实际版本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!