如何在Jest的同一测试文件中的不同测试中以不同的方式模拟模块? [英] How to mock module in different ways in different tests in the same test file in Jest?

查看:69
本文介绍了如何在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.resetModulesjest.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
})

这篇关于如何在Jest的同一测试文件中的不同测试中以不同的方式模拟模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆