使用Jest模拟React组件

时间:2018-11-22 02:00:43

标签: reactjs jestjs enzyme

我正在尝试在所有测试中模拟我的组件之一。原因是它正在本地软件包中使用D3的较旧版本的副本,并且此D3引用了“ this.document”,在运行Jest测试时会出错。这可能是由于此处描述的原因:https://github.com/facebook/jest/issues/3970

package.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的组件。

1 个答案:

答案 0 :(得分:1)

问题

import BarChart from './components/d3/BarChart/BarChart';最终运行的代码包含对引起错误的this.document的引用。


解决方案

无需导入该组件即可对其进行模拟。

要么提供module factory function作为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 */);

或在./components/d3/BarChart/__mocks__/BarChart处创建mock for the component并只需调用jest.mock并指定组件的路径即可:

import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
configure({ adapter: new Adapter() });

jest.mock('./components/d3/BarChart/BarChart');