简体   繁体   English

使用 Jest 模拟 React 组件

[英]Mocking a React Component using Jest

I'm trying to mock one of my components across all tests.我试图在所有测试中模拟我的一个组件。 The reason is that it is using a copy of an older version of D3 in a local package, and this D3 has references to "this.document", which errors out when running Jest tests.原因是它在本地包中使用了旧版本 D3 的副本,并且此 D3 引用了“this.document”,在运行 Jest 测试时会出错。 This is probably due to the reasons described here: https://github.com/facebook/jest/issues/3970这可能是由于这里描述的原因: https : //github.com/facebook/jest/issues/3970

package.json包.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 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);

However, when I run npm test, I still get:但是,当我运行 npm test 时,我仍然得到:

TypeError: Cannot read property 'document' of undefined

   6 |     return d3_arraySlice.call(list);
   7 |   };
>  8 |   var d3_document = this.document;

coming from the local D3 package.来自本地 D3 包。

My test file:我的测试文件:

import React from 'react';
import { shallow, mount } from 'enzyme';
import App from '../App';

it('renders without crashing - deep', () => {
  mount(<App />);
});

App has a component which uses BarChart.应用程序有一个使用 BarChart 的组件。

Issue问题

import BarChart from './components/d3/BarChart/BarChart'; ends up running code that includes a reference to this.document which causes the error.最终运行的代码包含对导致错误的this.document的引用。


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 :要么提供一个模块工厂函数作为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:或者在./components/d3/BarChart/__mocks__/BarChart为组件创建一个模拟,然后简单地使用组件的路径调用jest.mock

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM