Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React / Enzyme: Invariant Violation error when running Jest / Enzyme test

I am having some trouble with my test cases written in Jest / Enzyme. I have a React / Redux component and am trying to write a basic test but get the following error:

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

This is my code:

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

I am not sure why <Dashboard /> would be undefined here.

like image 493
Eric P Pereira Avatar asked Aug 31 '18 04:08

Eric P Pereira


1 Answers

You're currently exporting your wrapped component as the default export, but to use the unwrapped component in your tests you also need to export your it as a named export, i.e.

export class DashboardComponent extends Component { ... }

export default connect(...)(DashboardComponent)
like image 125
zkcro Avatar answered Oct 09 '22 22:10

zkcro