问题
Currently I have this:
jest.mock('my/hook', () => () => false)
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
}
}
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.
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
})
How do I customize module mocks on a per-test basis in Jest?
回答1:
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
})
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
})
来源:https://stackoverflow.com/questions/64669103/how-to-mock-module-in-different-ways-in-different-tests-in-the-same-test-file-in