目前我有这个:
jest.mock('my/hook', () => () => false)
我希望我的自定义React挂钩模块false
默认情况下在每个测试中都返回,但是在一些测试中,我希望它返回true。
挂钩基本上是这样实现的:
function useMyHook(key) {
switch (key) {
case 'foo':
case 'bar':
return true
default:
return false
}
}
我在组件中多次使用了钩子,一次用于foo
密钥,一次用于bar
密钥。我希望它默认为两个键返回false。
但是对于一些测试,我希望foo
键返回true,对于其他测试,我希望bar
键返回true。
我通过在特定测试中执行此操作来尝试了此操作,但它没有执行任何操作:
it('should do x', () => {
jest.doMock('my/hook', () => (key) => {
if (key == 'foo') {
return true
}
})
// ... rest of test
})
如何在Jest中按测试自定义模块模拟?
jest.doMock
一个人不能做任何事情,因为依赖它的模块早已导入。之后应重新导入,并使用jest.resetModules
或丢弃模块缓存jest.isolateModules
:
beforeEach(() => {
jest.resetModules();
});
it('should do x', () => {
jest.doMock('my/hook', ...)
require('module that depends on hook');
// ... rest of test
})
因为它是一个需要不同模拟的函数,所以更好的方法是使用Jest间谍而不是普通函数模拟实现:
jest.mock('my/hook', () => jest.fn(() => false))
...
it('should do x', () => {
hook.mockReturnValueOnce(true);
// ... rest of test
})
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句