How to mock module in different ways in different tests in the same test file in Jest?

喜你入骨 提交于 2021-01-29 21:56:41

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!