我希望这是特定于一个测试的:
it('should mock the module a single time', () => {
jest.doMock('../../../../../../../components/HighCharts/HighCharts', () => {
return () => <div id="mock-line-chart" />;
});
})但是它不起作用。这适用于整个文件:
jest.mock('../../../../../../../components/HighCharts/HighCharts', () => {
return () => <div id="my-special-div" />;
});我是不是用错了?doMock和mock之间的区别在哪里?是否适合只为一次测试做一个模块模拟?
发布于 2020-10-07 23:23:18
当在顶层使用时,jest.mock被提升到import之上,当在块中使用时,它被提升到块的开头(测试功能范围等),jest.unmock也是如此。jest.doMock和jest.dontMock的作用相同,但没有被提升。
这对于像这样的情况很重要:
it('should mock the module a single time', () => {
let originalHighCharts = require('.../HighCharts');
...
jest.doMock('.../HighCharts', ...);
let mockedHighCharts = require('.../HighCharts');
...
})doMock允许特定顺序在实践中很少有用,因为可以使用jest.requireActual检索模拟模块,而相同的序列可能不会因为缓存而影响依赖于模拟模块的其他模块。
doMock和dontMock没有被提升,这允许在特定的场景中一起使用它们来模拟单个测试的模块:
let HighCharts;
jest.isolateModules(() => {
jest.doMock('.../HighCharts', ...);;
HighCharts = require('.../HighCharts');
jest.dontMock('.../HighCharts');
});缺点是,如果导入失败,dontMock可能无法执行,因此可能会影响其他测试,这需要额外处理。强制执行默认模块状态可能更直接,这对于大多数测试是可取的:
beforeEach(() => {
jest.unmock('.../HighCharts');
jest.resetModules();
});https://stackoverflow.com/questions/64245013
复制相似问题