Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Router 4 and enzyme

Ive switched to react router v4 and few tests need to be reimplemented. I have following scenario:

  • mounting a component (checking if methodA has been called)
  • changing the props by enzymes wrapper method: setProps
  • checking if method has been called twice

And that was fairly easy with old router.. but it comes very hard with the new one:

If component (or children) contains for example Link, it means that we have to provide proper contxt for rendering the component. Thats why MemoryRouter has been created:

const comp = mount(
      <MemoryRouter>
        <Comp {...someProps} />
      </MemoryRouter>
    );
//here comes assertion about spy getting called

thanks to that we are able to render the component (more info:https://reacttraining.com/react-router/web/guides/testing) But.. if we take a look at setProps method at enzyme library (http://airbnb.io/enzyme/docs/api/ReactWrapper/setProps.html):

A method that sets the props of the root component, and re-renders.

It means that if I call comp.setProps({..newProps}), it actually changes route props (MemoryRouter), but doesnt change my component props, which sucks as hell.

Any insights on such case?

like image 871
MariuszJasinski Avatar asked May 24 '17 07:05

MariuszJasinski


1 Answers

You could write wrapper around MemoryRouter and pass all the props down to node that need's to be tested.

const CompWrappedWithMemoryRouter = (props) => {
    return (
        <MemoryRouter>
            <Comp {...props />
        </MemoryRouter>
    )
}

then use it of course

const comp = mount(
      <CompWrappedWithMemoryRouter {...someProps} />
    );

now comp.setProps should work

like image 73
Grzegorz Motyl Avatar answered Nov 11 '22 14:11

Grzegorz Motyl