Testing React Router with Noise and Enzyme
My goal is to test my React Router Route
export in my application and check if it is loading the correct component, page, etc.
I have a route.js file that looks like this:
import React from 'react';
import { Route, IndexRoute } from 'react-router';
import { App, Home, Create } from 'pages';
export default (
<Route path="/" component="isAuthenticated(App)">
<IndexRoute component={Home} />
<Route path="create" component={Create} />
{/* ... */}
</Route>
);
Note: isAuthenticated(App)
defined elsewhere and omitted.
And from what I've read and understood, I can test it as such:
import React from 'react';
import { shallow } from 'enzyme';
import { Route } from 'react-router';
import { App, Home } from 'pages';
import Routes from './routes';
describe('Routes', () => {
it('resolves the index route correctly', () => {
const wrapper = shallow(Routes);
const pathMap = wrapper.find(Route).reduce((pathMapp, route) => {
const routeProps = route.props();
pathMapp[routeProps.path] = routeProps.component;
return pathMapp;
}, {});
expect(pathMap['/']).toBe(Home);
});
});
However, running this test results in:
Invariant Violation: <Route> elements are for router configuration only and should not be rendered
I think I understand that the problem might be using the Enzyme method shallow
. I took these solutions from this SO question . I suppose I understand what it is trying to parse wrapper
in search of a call Route
by putting them in a hash table and using that to determine if the correct component is in the table where it should be, but that doesn't work.
I went through a lot of documentation, Q&A posts and blog posts trying to find the "right path" to test my routes, but I don't feel like I'm not going anywhere. Am I on the sidelines of my approach?
React: 15.4.2
React Router: 3.0.2
Enzyme: 2.7.1
Node: 6.11.0
source to share
You cannot directly render Routes
, but a component with Router
that uses routes internally. The answer you pointed to has a complete solution.
You will probably also need to change your test environment browserHistory
to use another history
one that runs on node. Old v3 docs:
https://github.com/ReactTraining/react-router/blob/v3/docs/guides/Histories.md
As a side note, what testing point Route
I'm assuming is already tested in the library itself? Perhaps your test should focus on your route components: do they do what they should use based on route parameters? You can easily mock these parameters in your tests, because they are just props.
I'm telling you this because, in my experience, understanding what was as important to testing as learning how . Hope this helps :)
source to share