Dylan Parry Dylan Parry - 2 months ago 15
React JSX Question

Unit testing route matching with React Router 2

I’m trying to add unit tests for a React application and would like to test the routes provided by React Router (2.0.1). I’d like to test whether specific paths that I supply will match a route. I am writing my tests using Mocha and expect.

I’ve looked through the documentation on the React Router repository, but the only testing guide I could see was explaining how to test a

<Link />
and how it’s rendered.

Say I have the following code:

// import statements omitted for brevity

export const routes = (
<Route path="/" component={App}>
<IndexRoute component={Index} />
<Route path="/foo">
<IndexRoute component={FooIndex} />
<Route path="add" component={FooAdd} />
<Route path=":fooId" component={FooDetails} />
</Route>
</Route>
)

ReactDOM.render(
<Router history={browserHistory}>{routes}</Router>,
document.getElementById('app')
)


How can I test that the routes created in the
routes
variable would match the following:


  • /

  • /foo

  • /foo/add

  • /foo/25



But not routes like:


  • /foo/bar/12

  • /bar



Essentially I want to check that every expected URL format has a route that will match it and that unexpected URLs don't match any routes.

I’m not interested in the elements that are rendered by the routes, so don't want to base my tests on checking whether a specific thing is rendered, only that a matching route was found and preferably some way of checking that it was in fact the expected route (I'd guess checking what the name of the component is or something?)

Any help is gratefully appreciated.

Thanks

Answer

We test exactly this in our test for matchRoutes: https://github.com/reactjs/react-router/blob/master/modules/__tests__/matchRoutes-test.js

You can follow this pattern. If you can't identify your routes by reference, you can indeed assert on the components that were rendered as well.

As matchRoutes isn't exported, you'll want to use the match helper (otherwise used for for server-side rendering) instead, and check renderProps.routes or renderProps.components.

Comments