Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jest: react-router tests returns undefined 'params'

I'm trying to test a component with the MemoryRouter as indicated in the React-router docs with initial entries set so I can have params inside the wrapped component.

Component example :

render () {
  console.log(this.props.match.params.item)
}

In the App (works fine) :

<Router>
  <Switch>
    <Route exact path='/' render={() => (
      <Redirect to={`/${guessLocale()}`} />
    )} />
    <Route exact path='/:lang' component={Home} />
    <Route exact path='/:lang/:itemName' component={Vidactic} />
  </Switch>
</Router>

In the test (mount from Enzyme, match is undefined) :

mount(<MemoryRouter initialEntries={['/fr/pamp']}>
  <Vidactic />
</MemoryRouter>)

So I used this workaround but why initialEntries would not work by itself ?

mount(<MemoryRouter initialEntries={['/fr/pamp']}>
  <Vidactic match={{ params: { item: 'pamp' } }} />
</MemoryRouter>)
like image 567
3Dos Avatar asked Jul 03 '18 14:07

3Dos


1 Answers

There's no Route in your test, so no matching will take place, and this.props.match will be undefined for Vidactic. Adding the route should make it work:

mount(
  <MemoryRouter initialEntries={['/fr/pamp']}>
    <Route exact path="/:lang/:itemName" component={Vidactic} />
  </MemoryRouter>
);

To avoid duplicating the routes, you might want to put the <Switch>..</Switch> part in a separate component and use that in your tests.

like image 147
Oblosys Avatar answered Sep 28 '22 09:09

Oblosys