React test with Enzyme, cannot read property 'route' of undefined

Viewed 2137

In my React App (No flux / redux), I'm trying to do unit testing to a component using enzyme, the shallow rendering works well, I am able to retrieve it's state etc, but mount rendering throw me an error of cannot read property 'route' of undefined.

my App.js looks like this

class App extends Component {
  render() {
    return (
      <BrowserRouter>
        <Switch>
          <MyCustomLayout>
            <Route path="/mypath" component={myComponent} />
          </MyCustomLayout>
        </Switch>
      </BrowserRouter>
    )
  }

Here is the code for myComponent

import React, { Component } from 'react';
import './index.css';
import { getList } from './apiService.js';
 
class myComponent extends Component {
  constructor(props) {
      super(props);
      this.state = {
        myList: [],
      };
  }
  
  componentDidMount() {
  // get list ajax call
    getList().then(response => {
      this.setState({
        myList: response.data
      })
    });
  }
  
  handleClick = () => {
    this.props.history.push('/home');
  }
  
  renderMyList() {
    /*
      Code for rendering list of items from myList state
    */
  }
  
  render() {
    return (
      <div>
        <h1>Hello World</h1>
        <button onClick={this.handleClick}>Click me</button>
        {this.renderMyList()}
      </div>
    )
  }
}

export default myComponent

Here is the code for my test

import React from 'react';
import myComponent from './myComponent';
import renderer from 'react-test-renderer';
import { shallow, mount } from 'enzyme';
import sinon from 'sinon';

test('Initial state of myList should be empty array ', () => {
  const component = shallow(<myComponent/>);
  expect(component.state().myList).toEqual([]);
});

test('Make sure the componentDidMount being called after mount', () => {
  sinon.spy(myComponent.prototype, 'componentDidMount');
  const component = mount(<myComponent/>);
  expect(myComponent.prototype.componentDidMount.calledOnce).toEqual(true);
});

What does the error ?

1 Answers
Related