如何在Jest的同一测试文件中的不同测试中以不同的方式模拟模块?
目前我有这个:
jest.mock('my/hook', () => () => false)
我希望我的自定义React钩子模块默认在每个测试中返回false
,但是在一些测试中,我希望它返回true.
I want my custom React hook module to return false
in every test by default, but in a few tests I want it to return true.
该钩子基本上是这样实现的:
The hook is implemented essentially like this:
function useMyHook(key) {
switch (key) {
case 'foo':
case 'bar':
return true
default:
return false
}
}
我在组件中多次使用了钩子,一次用于foo
键,一次用于bar
键.我希望它默认为两个键都返回false.
I am using the hook several times in my component, once for the foo
key and once for the bar
key. I want it to return false for both keys by default.
但是对于一些测试,我希望foo
键返回true,对于其他测试,我希望bar
键返回true.
But for a few tests I want the foo
key to return true, and for other tests I want the bar
key to return true.
我通过在特定测试中执行此操作来尝试了此操作,但是它什么也没做:
I tried that by doing this in the specific test, but it didn't do anything:
it('should do x', () => {
jest.doMock('my/hook', () => (key) => {
if (key == 'foo') {
return true
}
})
// ... rest of test
})
如何在Jest中按测试自定义模块模拟?
How do I customize module mocks on a per-test basis in Jest?
jest.doMock
本身不能做任何事情,因为依赖它的模块已在前面导入.此后应重新导入,并使用jest.resetModules
或jest.isolateModules
丢弃模块缓存:
jest.doMock
alone can't do anything because a module that depends on it has been already imported earlier. It should be re-imported after that, with module cache discarded with either jest.resetModules
or jest.isolateModules
:
beforeEach(() => {
jest.resetModules();
});
it('should do x', () => {
jest.doMock('my/hook', ...)
require('module that depends on hook');
// ... rest of test
})
由于需要对函数进行不同的模拟,因此更好的方法是使用Jest间谍而不是普通函数模拟实现:
Since it's a function that needs to be mocked differently, a better way is to mock the implementation with Jest spies instead of plain functions:
jest.mock('my/hook', () => jest.fn(() => false))
...
it('should do x', () => {
hook.mockReturnValueOnce(true);
// ... rest of test
})