Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing React Router with Jest and Enzyme

Tags:

My goal is to test my React Router Route exports in my app and test if it is loading the correct component, page, etc.

I have a routes.js file that looks like:

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) is 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 issue might be my use of Enzyme's shallow method. I took this solutions from this SO question. I believe I understand that it is attempting to parse through the wrapper in search of a Route call, putting each into a hashtable and using that to determine if the correct component is in the table where it should be, but this is not working.

I've looked through a lot of documentation, Q&A, and blog posts trying to find "the right way" to test my routes, but I don't feel I'm getting anywhere. Am I way off base in my approach?

React: 15.4.2

React Router: 3.0.2

Enzyme: 2.7.1

Node: 6.11.0

like image 676
Matt Walther Avatar asked Jun 22 '17 19:06

Matt Walther


1 Answers

You can't directly render Routes, but a component with Router that uses routes inside. The answer you pointed to has the complete solution.

You will probably also need to change the browserHistory under test environment to use a different history that works on node. Old v3 docs: https://github.com/ReactTraining/react-router/blob/v3/docs/guides/Histories.md

As a side note, what's the point of testing Route which I assume is already tested in the library itself? Perhaps your test should focus on your route components: do they render what they should based on route params? Those params you can easily mock in your tests because they're just props.

I'm telling you this because in my experience understanding what to test was as important as learning how to test. Hope it helps :)

like image 116
CharlieBrown Avatar answered Oct 11 '22 12:10

CharlieBrown