0

我正在使用 d3 for npm 创建一个强制图。该图是使用以下内容创建的:

https://medium.com/walmartlabs/d3v4-forcesimulation-with-react-8b1d84364721

我正在尝试按如下方式设置测试环境: https ://ericnish.io/blog/how-to-unit-test-react-components-with-enzyme/

问题是当我运行测试时,我不断得到

 Cannot read property 'matches' of undefined
at C:\workspace\project\node_modules\d3-selection\build\d3-selection.js:83:15

我在我的图形组件中导入了 d3,如下所示:

import * as d3 from 'd3';

好像当我在我的测试文件中导入我的反应组件时,它吓坏了。这是我的测试文件:

import React from 'react'
import {shallow, mount, render} from 'enzyme'
import {expect} from 'chai'
import * as d3 from 'd3';
import graph from '.../components/graph ';
describe('graph ', () => {
  it('should have the main svg', (done) => {
    const wrapper = shallow(<graph />);
    expect(wrapper.find('svg')).to.have.length(1);
    done()
  })
})

我怎样才能摆脱这个错误?

4

1 回答 1

0

创建一个文件,例如polyfill.js

global.document.documentElement = {matches: () => false};

并在您导入 DS3 之前导入它(或任何其他可传递导入 D3 的导入):

import React from 'react'
import {shallow, mount, render} from 'enzyme'
import {expect} from 'chai'
import './polyfill';
import * as d3 from 'd3';
于 2018-07-05T12:29:40.417 回答