【问题标题】:React / Enzyme: Invariant Violation error when running Jest / Enzyme testReact / Enzyme:运行 Jest / Enzyme 测试时出现 Invariant Violation 错误
【发布时间】:2019-02-06 01:57:33
【问题描述】:

我在使用 Jest / Enzyme 编写的测试用例时遇到了一些问题。我有一个 React / Redux 组件,正在尝试编写一个基本测试,但收到以下错误:

Invariant Violation: ReactShallowRenderer render(): Shallow rendering works only with custom components, but the provided element type was 'undefined'.

这是我的代码:

dashboardComponent.js

import '../stylesheets/dashboardComponent.css';
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import * as dashboardActions from '../actions/dashboardActions';

class DashboardComponent extends Component {
  constructor(props) {
    super();
  }

  componentDidMount() {
    this.props.actions.getDashboardContent();
  }

  render() {
    return (
      < SOME JSX HERE >
    );
  }
}

function mapStateToProps(state) {
  return {
    dashboardContent: state.dashboard.get('dashboardContent')
  }
}

function mapDispatchToProps(dispatch) {
  return {
    actions: bindActionCreators(dashboardActions, dispatch)
  };
}

export default connect(mapStateToProps, mapDispatchToProps)(DashboardComponent);

dashboardComponent.test.js

import React from 'react';
import { shallow } from 'enzyme';
import { DashboardComponent as Dashboard } from '../../components/dashboardComponent';

const wrapper = shallow(<Dashboard />);

describe('Dashboard', () => {
  it('renders the Dashboard component', () => {
    expect(wrapper).toMatchSnapshot();
  });
});

我不确定为什么 &lt;Dashboard /&gt; 会在这里未定义。

【问题讨论】:

    标签: reactjs redux jestjs enzyme


    【解决方案1】:

    您当前正在将包装组件导出为默认导出,但要在测试中使用未包装组件,您还需要将其导出为命名导出,即

    export class DashboardComponent extends Component { ... }
    
    export default connect(...)(DashboardComponent)
    

    【讨论】:

    • 就是这样。谢谢!
    • 如果您没有传递组件渲染所需的道具,也可能导致此错误。
    • 哇,我不敢相信我从来没有想过这个。干得好!
    【解决方案2】:

    错误:ReactShallowRenderer render():浅渲染仅适用于自定义组件,但提供的元素类型为 `object`。

    - 通过更改导出行解决了类似的错误,来自

    export const TestComponent = () => { ...

    导出默认 TestComponent = () => { ...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-01-29
      • 1970-01-01
      • 2017-02-12
      • 2020-08-07
      • 2017-11-26
      • 2019-08-02
      • 2020-06-09
      相关资源
      最近更新 更多