玩笑用酶和connect()进行测试,从“ ../components/connectAdvanced”导入importAdvanced ;;

时间:2018-11-07 15:01:09

标签: javascript reactjs testing jestjs enzyme

在组件上使用connect时,无法运行简单的jest/enzyme测试。我尝试按照此处的建议使用dive()Testing a Redux-connected component using Enzyme。但是错误仍然完全相同。

我希望能够测试用浅层包装的组件,而不是这个错误(显然)

控制台故障

 FAIL  src/containers/Home/index.test.js
  ● Test suite failed to run

    /var/www/cloud/websites/www/node_modules/react-redux/es/connect/connect.js:5
    import connectAdvanced from '../components/connectAdvanced';
           ^^^^^^^^^^^^^^^

    SyntaxError: Unexpected identifier

      at new Script (vm.js:74:7)
      at Object.<anonymous> (src/components/shared/buttons/index.js:3:16)

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        1.482s
Ran all test suites related to changed files.

Watch Usage: Press w to show more.

home.index.js

import React, { PureComponent, Fragment } from 'react';
import ButtonUI from '../../components/shared/buttons';

export default class Home extends PureComponent {
  render() {
    return (
      <ButtonUI galabel="testLabel" gaaction="testAction">
        Fire GA Test
      </ButtonUI>
    );
  }
}

components / shared / buttons / index.js

import React, { PureComponent } from 'react';
import connect from 'react-redux/es/connect/connect';

class ButtonUI extends PureComponent {
  render() {
    return (
      <button>
        {this.props.children}
      </button>
    );
  }
}

export default connect()(ButtonUI);

home / index.test.js

import React, { PureComponent } from 'react';
import Home from './index.js';
import { shallow, mount, render } from 'enzyme';

const wrapper = shallow(<Home />).dive();

describe('Home Page Can Render', () => {
  it('Contains a header', () => {
    expect(wrapper.find('h5')).to.have.lengthOf(1)
  });
});

Package.json

"react-router": "^4.3.1",
"react-router-dom": "^4.3.1",
"connected-react-router": "^4.4.1",
"enzyme": "^3.6.0",
"enzyme-adapter-react-16": "^1.5.0",
"enzyme-to-json": "^3.3.4",
"react-scripts": "^2.1.1",

1 个答案:

答案 0 :(得分:2)

connect作为es6模块导入,而NodeJS运行时不知道如何处理它。

import connect from 'react-redux/es/connect/connect';

通常,库作者拥有自己的库transpiled in commonjs,以实现与多种环境和provide that as the entry point for their module的互操作性

虽然您可以更新捆绑程序配置以也可以从node_modules文件夹中导入模块,但是我建议使用模块入口点,因为这样做更直接。

import { connect } from "react-redux";