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?
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
Most helpful comment
You can pass an
initialEntries
array to your<MemoryRouter>
. If an entry has akey
property, that will be used instead of generating a random key.