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>)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With