I'm using jest
to test a component with a <Link>
from react-router v4.
I get a warning that <Link />
requires the context from a react-router <Router />
component.
How can I mock or provide a router context in my test? (Basically how do I resolve this warning?)
Link.test.js
import React from 'react';
import renderer from 'react-test-renderer';
import { Link } from 'react-router-dom';
test('Link matches snapshot', () => {
const component = renderer.create(
<Link to="#" />
);
let tree = component.toJSON();
expect(tree).toMatchSnapshot();
});
The warning when the test is run:
Warning: Failed context type: The context `router` is marked
as required in `Link`, but its value is `undefined`.
Above solutions have a common default defact:
Can't access your component's instance! Because the
MemoryRouter
orStaticRouter
component wrapped your component.So the best to solve this problem is mock a router context, code as follows:
my test like this:
I had the same issue and using
StaticRouter
would still require thecontext
which needed more configuration to have it available in my test, so I ended up using theMemoryRouter
which worked very well and without any issues.You can wrap your component in the test with the StaticRouter to get the router context into your component:
Have a look at the react router docs about testing