jest.mock和jest.doMock之间的区别 [英] Difference between jest.mock and jest.doMock

查看:353
本文介绍了jest.mock和jest.doMock之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望这是针对单个测试的:

I want this to be specific to a single test:

  it('should mock the module a single time', () => {
    jest.doMock('../../../../../../../components/HighCharts/HighCharts', () => {
      return () => <div id="mock-line-chart" />;
    });
  })

但是它不起作用.这适用于整个文件:

but it doesnt work. This works for the whole file:

jest.mock('../../../../../../../components/HighCharts/HighCharts', () => {
  return () => <div id="my-special-div" />;
});

我不使用此权限吗?doMock和模拟之间的区别在哪里?我适合只对单个测试进行模块模拟吗?

Am I not using this right? Where is the difference between doMock and mock. I it suitable to do a module mock for a single test only?

推荐答案

jest.mock 在最高级别使用时,悬挂在 import 之上,并提升到在块中使用该块(测试功能范围等)时,与 jest.unmock 相同. jest.doMock jest.dontMock 具有相同的目的,但没有被吊起.

jest.mock is hoisted above import when used at top level and hoisted to the the beginning of the block when used in a block (test function scope, etc), same for jest.unmock. jest.doMock and jest.dontMock serve the same purpose but aren't hoisted.

这对于像这样的情况很重要:

This would matter for a case like this one:

  it('should mock the module a single time', () => {
    let originalHighCharts = require('.../HighCharts');
    ...
    jest.doMock('.../HighCharts', ...);
    let mockedHighCharts = require('.../HighCharts');
    ...
  })

doMock 允许特定顺序的做法在实践中很少有用,因为可以使用 jest.requireActual 检索模拟的模块,而相同的顺序可能不会影响依赖于其他模块的其他模块.由于缓存而在模拟模块上运行.

That doMock allows for specific order is rarely useful in practice because mocked module can be retrieved with jest.requireActual, while the same sequence may not affect other modules that depend on mocked module because of caching.

未悬挂 doMock dontMock 允许在特定情况下将它们一起使用以模拟用于单个测试的模块:

That doMock and dontMock aren't hoisted allows to use them together for a specified scenario to mock a module for single test:

let HighCharts;
jest.isolateModules(() => {
  jest.doMock('.../HighCharts', ...);;
  HighCharts = require('.../HighCharts');
  jest.dontMock('.../HighCharts');
});

不利之处在于,如果导入失败,则可能不会执行 dontMock ,因此它可能会影响其他测试,这需要另外进行处理.实施默认的模块状态可能更直接,这对于大多数测试来说是更好的选择:

The downside is that dontMock may not be executed if the import fails, so it can affect other tests, this needs to be additionally handled. It may be more straightforward to enforce default module state that is preferable for most tests:

beforeEach(() => {
  jest.unmock('.../HighCharts');
  jest.resetModules();
});

这篇关于jest.mock和jest.doMock之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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