【问题标题】:React.js unit testing with d3-npm使用 d3-npm 进行 React.js 单元测试
【发布时间】:2017-10-24 17:55:04
【问题描述】:

我正在使用 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()
  })
})

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

【问题讨论】:

    标签: node.js reactjs unit-testing d3.js d3-force-directed


    【解决方案1】:

    创建一个文件,例如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';
    

    【讨论】:

      猜你喜欢
      • 2014-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-05
      • 2023-03-11
      • 2011-11-16
      • 2015-05-28
      相关资源
      最近更新 更多