vendredi 15 novembre 2019

Testing react-router with Shallow rendering

I have my react-router component such as :

<Switch>
  <Route
    path="/abc"
    render={() => <ComponentTemplateABC component={containerABC} />}
  />
  <Route
    path="/def"
    render={() => <ComponentTemplateDEF component={containerDEF} />}
  />
  ...
  ...
</Switch>

I wish to test the routing to ensure the respective component is rendered for each route. However, I do not wish to use mount for testing the routing, only wish to use shallow rendering.

Below is what my test looks like currently:

  test('abc path should route to containerABC component', () => {
    const wrapper = shallow(
      <Provider store={store}>
        <MemoryRouter initialEntries={['/abc']}>
          <Switch>
            <AppRouter />
          </Switch>
        </MemoryRouter>
      </Provider>,
    );
    jestExpect(wrapper.find(containerABC)).toHaveLength(1);
  });

This test does not work with shallow, because shallow won't render the full child hierarchy. So I tried an alternate approach:

test('abc path should render correct routes and route to containerABC component', () => {
 const wrapper = shallow(<AppRouter />);

 const pathMap = wrapper.find(Route).reduce((pathMap, route) => {
 const routeProps = route.props();
 pathMap[routeProps.path] = routeProps.component;
 return pathMap;
 }, {});

 jestExpect(pathMap['/abc']).toBe(containerABC);
});

This test does not work for me, because I am using render in my routing code instead of Component directly as in below:

<Route path="..." **render**={() => <Component.. component={container..} />}

Hence, I am unable to test my routes. How do I test my routes using shallow rendering or as above or basically, any other approach that does not use mount?

Any help would be much appreciated. Thank you in advance.

Aucun commentaire:

Enregistrer un commentaire