Test Component with Reactive Router v4, Jest, and Enzyme

I have a simple component that uses response-router (I know this is an alpha assembly):

{props.app && props.app.health && <Match exactly pattern="/" component={HomeLogin} /> } 

Documents recommending wrapping in <MemoryRouter /> to provide context to components during testing.

However, with Jest / Enzyme I cannot execute shallow() render - I need to use Enzyme mount() or render() , which causes problems because HomeLogin is a connected component - I want to be able to verify that my component is doing the right thing thing, but does not check the component rendered inside 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 check the output of this component based on a route without having to provide a reduction repository or use small rendering?

Update: if I try to use shallow() , the snapshot does not output the result.

+7
javascript reactjs react-router jestjs
source share
1 answer

You can use .find(Jumbotron) and use it for matching as a snapshot, for example:

 const wrapped = component.find(Jumbotron); expect(toJson(wrapped)).toMatchSnapshot(); 

I had a more complex example involving withRouter() , and I was restoring the removal of all keys from the output before matching as a snapshot. Well, until testing for React-Router v4 becomes more reliable with testing Jest and snapshots. 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(); 
+1
source share

All Articles