Sign in
Log inSign up

How to test dynamic router in ReactRouter with jest?

Riderman de Sousa Barbosa's photo
Riderman de Sousa Barbosa
·Jun 2, 2017

How to test a component that use ReactRouter with match.params ...

I have an App.jsx ...

<Router history={history}>
  <div>
    <Route exact path="/list/:code" component={ListPage} />)}
  </div>
</Router>

With ListPage component ..

@withRouter
export default class ListPage = extends Component {
    componentDidMount() {
        const { match } = this.props;
        fetch(match.params.code);
    }

    render() {
        return (<div>Hi</div>);
    }
}

How can I create a test for that?

it('should render', () => {
  const wrapper = renderer.create(
    <Router history={history} location="/classroom/123/robots">
      <ListPage.wrappedComponent {...minProps} />
    </Router>,
  );
  expect(wrapper.toJSON()).toMatchSnapshot();
});

But I received a error:

TypeError: Cannot read property 'params' of undefined