javascript - 用 enzyme 和 connect() 进行开 Jest 测试,给出 `import connectAdvanced from ' ../components/connectAdvanced';`

标签 javascript reactjs testing jestjs enzyme

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

我希望能够测试用 shallow 而不是这个错误(显然)包裹的组件

控制台失败

 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>
    );
  }
}

组件/共享/按钮/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)
  });
});

包.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",

最佳答案

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

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

通常图书馆作者有他们的图书馆transpiled in commonjs与多个环境的互操作性和provide that as the entry point for their module

虽然您可以更新您的 bundler 配置以也从 node_modules 文件夹导入模块,但我建议改用模块入口点,因为这样更直接。

import { connect } from "react-redux";

关于javascript - 用 enzyme 和 connect() 进行开 Jest 测试,给出 `import connectAdvanced from ' ../components/connectAdvanced';`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53192075/

相关文章:

javascript - react 数据表错误

reactjs - 路由器状态未通过 redux 保留在 React-Native 中

python - 优化 Django 测试的 fixture 加载部分的最佳方法是什么?

javascript - 将子项拆分为第 n 行,每行包含特定数量的子项

javascript - 如何根据其 li 调整水平菜单的大小?

javascript - react redux async action 完成函数后调用下一个函数

ios - AVPlayer 和 Video 的屏幕截图

ruby-on-rails-3 - Rails 测试功能真的重要/有用吗?

javascript - 在 Magento 的后端 block (选项卡编辑表单)中添加额外的 js

javascript - Angular 2 到最新版本 - jsonp 和 URLSearchParams 到 HttpClient 和 HttpParams