React-router: How to test component wrapped by 'withRouter' with snapshot?

Created on 1 Oct 2017  路  3Comments  路  Source: ReactTraining/react-router

I have a component that wrapped by withRouter, in order to do the jest snapshot test.
I do something like this.

import React from 'react';
import { MemoryRouter } from 'react-router-dom';
import toJson from 'enzyme-to-json';
import { mount } from 'enzyme';
import Drawer from '..';

describe('Layout-Footer', () => {
  it('should render the component without errors', () => {
    const wrapper = mount(
      <MemoryRouter>
        <Drawer />
      </MemoryRouter>,
    );
    expect(toJson(wrapper)).toMatchSnapshot();
  });
});

The location injected keep changes in each test.

Object {
                                           "hash": "",
-                                          "key": "szfhuo",
+                                          "key": "6ymi9r",
                                           "pathname": "/",
                                           "search": "",
                                           "state": undefined,
                                         }

I know I could do some workaround like this.

    expect(toJson(wrapper).find(Drawer)).toMatchSnapshot();

But how about if my Drawer also contain components that wrapped by withRouter?

Most helpful comment

You can pass an initialEntries array to your <MemoryRouter>. If an entry has a key property, that will be used instead of generating a random key.

<MemoryRouter
  initialEntries={[ { pathname: '/', key: 'testKey' } ]}
>
  <Drawer />
</MemoryRouter>

All 3 comments

You can pass an initialEntries array to your <MemoryRouter>. If an entry has a key property, that will be used instead of generating a random key.

<MemoryRouter
  initialEntries={[ { pathname: '/', key: 'testKey' } ]}
>
  <Drawer />
</MemoryRouter>

Old issue, but google results leading here -- for some reason I couldn't get initialEntries with keys to work; it continued on generating random keys.

I didn't get to the bottom of it, but workaround was to eliminate keys (which presumably is more or less OK for testing):

    <MemoryRouter keyLength={0}>
      <App/>
    </MemoryRouter>,

@tadasant (and future folks led here by Google!):

I think this might be due to BrowserRouter being used in your App overlapping with MemoryRouter. If so, you'll need to mock BrowserRouter like this:

https://medium.com/@antonybudianto/react-router-testing-with-jest-and-enzyme-17294fefd303

Was this page helpful?
0 / 5 - 0 ratings

Related issues

stnwk picture stnwk  路  3Comments

nicolashery picture nicolashery  路  3Comments

maier-stefan picture maier-stefan  路  3Comments

hgezim picture hgezim  路  3Comments

andrewpillar picture andrewpillar  路  3Comments