reactjs - react / enzyme : Invariant Violation error when running Jest/Enzyme test

标签 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 />此处未定义。

最佳答案

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

export class DashboardComponent extends Component { ... }

export default connect(...)(DashboardComponent)

关于reactjs - react / enzyme : Invariant Violation error when running Jest/Enzyme test,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52108597/

相关文章:

reactjs - 如何在 React 启动时仅初始化一次上下文

node.js - 何时将 React 与 npm 结合使用?

reactjs - 如何在 React 组件中使用 @types/redux-form 定义的类型与 Field 和 FieldArray?

javascript - 如何在 React TDD 中使用 jest 和 Enzyme 测试组件的状态是否被函数更改

javascript - 开 Jest : Error in async method: ReferenceError: regeneratorRuntime is not defined

reactjs - 如何解决testing-library-react中的 “update was not wrapped in act()”警告?

reactjs - 使用 reactjs 上传多个文件

reactjs - 构建安全 JWT 身份验证流程的指南?

javascript - 为什么 React App 的 redux 情况下 IndexOf(Object) 可以工作?

reactjs - Jest 测试仅在覆盖范围内失败