Testing react-router with Shallow rendering

橙三吉。 提交于 2020-05-16 05:45:27

问题


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.


回答1:


So far I may suggest you different ways to test that:

  1. Mocking ComponentABC + mount()
import containerABC from '../../containerABC.js';

jest.mock('../../containerABC.js', () => <span id="containerABC" />);
...
  const wrapper = mount(
    <Provider store={store}>
      <MemoryRouter initialEntries={['/abc']}>
        <Switch>
          <AppRouter />
        </Switch>
      </MemoryRouter>
    </Provider>,
  );
  jestExpect(wrapper.find(containerABC)).toHaveLength(1);
  1. shallow() + dive() + renderProp():
   const wrapper = shallow(
      <Provider store={store}>
        <MemoryRouter initialEntries={['/abc']}>
          <Switch>
            <AppRouter />
          </Switch>
        </MemoryRouter>
      </Provider>,
    );
    jestExpect(wrapper.find(AppRouter)
      .dive()
      .find(Route)
      .filter({path: '/abc'})
      .renderProp('render', { history: mockedHistory})
      .find(ContainerABC)
    ).toHaveLength(1);


来源:https://stackoverflow.com/questions/58887090/testing-react-router-with-shallow-rendering

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!