首页 > 解决方案 > 使用 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 的组件。

标签: reactjsjestjsenzyme

解决方案


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');

推荐阅读