反应/酶:运行Jest /酶测试时发生恒定违反错误

时间:2018-08-31 04:48:10

标签: reactjs redux jestjs enzyme

我用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();
  });
});

我不确定为什么<Dashboard />在这里会没有定义。

2 个答案:

答案 0 :(得分:4)

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

export class DashboardComponent extends Component { ... }

export default connect(...)(DashboardComponent)

答案 1 :(得分:0)

<块引用>

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

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

<块引用>

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

<块引用>

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

相关问题