reactjs - 使用 Jest 模拟 React 组件
问题描述
我试图在所有测试中模拟我的一个组件。原因是它在本地包中使用了旧版本 D3 的副本,并且此 D3 引用了“this.document”,在运行 Jest 测试时会出错。这可能是由于这里描述的原因:https ://github.com/facebook/jest/issues/3970
包.json
"devDependencies": {
"enzyme": "^3.7.0",
"enzyme-adapter-react-16": "^1.7.0",
"eslint": "5.6.0",
"eslint-config-airbnb-base": "13.1.0",
"react-scripts": "^2.0.4",
"react-test-renderer": "^16.6.3",
"redux-devtools": "^3.4.1",
"redux-devtools-dock-monitor": "^1.1.3",
"redux-devtools-log-monitor": "^1.4.0",
"redux-logger": "^3.0.6"
...
"scripts": {
"test": "react-scripts test --env=jsdom --passWithNoTests"
src/setupTests.js
import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
configure({ adapter: new Adapter() });
import jest from 'jest';
import BarChart from './components/d3/BarChart/BarChart';
jest.mock('BarChart');
BarChart.render.mockResolvedValue(null);
但是,当我运行 npm test 时,我仍然得到:
TypeError: Cannot read property 'document' of undefined
6 | return d3_arraySlice.call(list);
7 | };
> 8 | var d3_document = this.document;
来自本地 D3 包。
我的测试文件:
import React from 'react';
import { shallow, mount } from 'enzyme';
import App from '../App';
it('renders without crashing - deep', () => {
mount(<App />);
});
应用程序有一个使用 BarChart 的组件。
解决方案
Issue
import BarChart from './components/d3/BarChart/BarChart';
ends up running code that includes a reference to this.document
which causes the error.
Solution
The component does not need to be imported in order to mock it.
Either provide a module factory function as the second parameter to jest.mock
:
import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
configure({ adapter: new Adapter() });
jest.mock('./components/d3/BarChart/BarChart', /* provide your module factory function here */);
or create a mock for the component at ./components/d3/BarChart/__mocks__/BarChart
and simply call jest.mock
with the path to the component:
import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
configure({ adapter: new Adapter() });
jest.mock('./components/d3/BarChart/BarChart');
推荐阅读
- reactjs - React Native reanimated v2 Scale + Opacity withRepeat
- javascript - 如何将用户选项存储到javascript数组中?
- excel - 是否可以阻止personal.xlsb 中可用的代码?
- python - 根据常用值从另一个数据框中添加列
- swift - 如何将 int 快速转换为二进制字符串?
- python - 没有 `%config Completer.use_jedi = False`,Jupyter Notebook 选项卡完成无法正常工作
- javascript - Cypress 中的链接函数
- flutter - 减小颤振项目文件夹的大小
- javascript - JavaScript 函数中的函数
- python - Python 字典键值名称