【问题标题】:How to mock module in different ways in different tests in the same test file in Jest?如何在 Jest 的同一个测试文件中以不同的方式在不同的测试中模拟模块?
【发布时间】:2020-11-03 19:12:14
【问题描述】:

目前我有这个:

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 中基于每个测试自定义模块模拟?

【问题讨论】:

    标签: javascript unit-testing jestjs mocking


    【解决方案1】:

    jest.doMock 一个人不能做任何事情,因为一个依赖它的模块之前已经被导入了。之后应该重新导入它,使用jest.resetModulesjest.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
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-11-27
      • 2019-12-19
      • 2021-04-19
      • 2020-05-30
      • 1970-01-01
      • 2011-10-15
      • 2020-12-24
      相关资源
      最近更新 更多