【问题标题】:Testing react-router with Shallow rendering使用浅渲染测试 react-router
【发布时间】:2020-03-12 04:49:27
【问题描述】:

我有我的 react-router 组件,例如:

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

我希望测试路由以确保为每个路由呈现相应的组件。但是,我不希望使用 mount 来测试路由,只希望使用浅渲染。

下面是我的测试目前的样子:

  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);
  });

此测试不适用于浅层,因为浅层不会呈现完整的子层次结构。所以我尝试了另一种方法:

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);
});

这个测试对我不起作用,因为我在路由代码中使用渲染而不是直接使用组件,如下所示:

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

因此,我无法测试我的路线。如何使用浅渲染或如上所述或基本上任何其他不使用 mount 的方法来测试我的路线?

任何帮助将不胜感激。 提前谢谢你。

【问题讨论】:

  • 这是 react-router@4 还是 @5?我遇到了@5 的问题,但我认为@4 有解决方案。

标签: reactjs testing react-router jestjs enzyme


【解决方案1】:

到目前为止,我可能会建议您使用不同的方法来测试:

  1. 嘲笑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);

【讨论】:

  • 使用玩笑是很糟糕的。不要仅仅为了让东西工作而使用模拟框架魔法
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-14
  • 1970-01-01
  • 2015-12-01
  • 2020-08-26
  • 2018-12-17
  • 2018-04-03
相关资源
最近更新 更多