I have a simple component that uses react-router (I'm aware this is the alpha build):
{props.app && props.app.health &&
<Match exactly pattern="/" component={HomeLogin} />
}
The docs recommending wrapping in <MemoryRouter />
to provide context to components while testing.
However, with Jest/Enzyme I'm not able to shallow()
render - I have to use Enzyme's mount()
or render()
, which causes problems because HomeLogin
is a connected component - I want to be able to test that my component renders the right thing, but not test the component rendered within it.
My test:
it('Renders based upon matched route', () => {
let props = {
app: { health: true },
};
const component = render(
<Provider store={store}>
<MemoryRouter location="/">
<Jumbotron {...props} />
</MemoryRouter>
</Provider>
);
expect(toJson(component)).toMatchSnapshot();
});
How can I test the output of this component based upon the route without having to provide the redux store or using shallow render?
Update: If I try to use shallow()
the snapshot renders no output.
You can use .find(Jumbotron)
and use that for matching as snapshot, for example:
const wrapped = component.find(Jumbotron);
expect(toJson(wrapped)).toMatchSnapshot();
I had a more complex example involving withRouter()
and I was restoring to removing all keys from the output before matching as snapshot. Well, until testing for React-Router v4 gets more solid with Jest and snapshot testing. Example:
export function removeKeys(object) {
if (object === undefined || object === null) {
return object;
}
Object.keys(object).forEach((key) => {
if (typeof object[key] === 'object') {
removeKeys(object[key]);
} else if (key === 'key') {
delete object[key];
}
});
return object;
}
...
expect(removeKeys(toJson(component))).toMatchSnapshot();
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