7

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>)

1 Answer 1

14

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.

3
  • I feel so incredibly dumb right now ! Thank you for your help.
    – 3Dos
    Commented Jul 3, 2018 at 14:48
  • Note that your root component will no longer be Vidactic, but MemoryRouter. Apparently this can be circumvented with Enzyme's mount context (the second parameter for mount()), but this hasn't worked for me. However, since accessing the component is usually not necessary, this answer is completely fine. Commented Nov 21, 2019 at 16:14
  • You are awesome, Thank you
    – skyshine
    Commented Apr 27, 2020 at 14:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.