I see quite a few similar questions to this, but all seem wildly outdated or incredibly convoluted.
I have a React component which contains a React Router Link
component, like so:
export default class Home extends Component {
render() {
return (
<div className="Home">
<Link to="/mission">Begin</Link>
</div>
);
}
}
Then, I am trying to test very simply that the Home
component contains a Link
component which has a to=/mission
property, using Jest. So, as per the Testing React Router docs, I tried many variations of tests, but this code most succinctly demonstrates what I am trying to achieve (example uses jest-enzyme for brevity):
it('includes link to Mission scene', () => {
const home = shallow(<MemoryRouter><Home /></MemoryRouter>);
expect(home).toContainReact(<Link to="/mission">Begin</Link>)
});
Obviously, that code has several issues, not the least of which is the error:
Warning: Failed context type: The context `router` is marked as required in `Link`, but its value is `undefined`.
But notice the key bits: I want to shallow render (if possible) the Home
component in order to test that component in isolation. At the same time, I am trying to wrap that in a MemoryRouter
or somehow get the context in place so that I can test the Link
components.
Astute potential answerers will notice that this issue is actually going to prevent all isolated tests of that component (not just tests related to React Router), because I can't shallow render the component at all.
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(); });
React Testing Library aims to solve the problem that many developers face when writing tests with Enzyme, which allows (and encourages) developers to test implementation details. Tests which do this ultimately prevent you from modifying and refactoring the component without changing its tests.
You can use Enzyme's find
method:
import { Link } from 'react-router';
it('includes link to Mission scene', () => {
const wrapper = shallow(<MemoryRouter><Home /></MemoryRouter>);
expect(wrapper.find(Link).props().to).toBe('/mission');
});
This is an info from official docs:
If you try to unit test one of your components that renders a
<Link>
or a<Route>
, etc. you’ll get some errors and warnings about context. While you may be tempted to stub out the router context yourself, we recommend you wrap your unit test in a<StaticRouter>
or a<MemoryRouter>
.
This link might be useful for you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With