使用浅渲染测试React-Router

问题描述 投票:0回答:1

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

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

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

下面是我目前的测试结果:

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

此测试对我不起作用,因为我在路由代码中使用渲染而不是直接在下面使用Component:

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

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

任何帮助将不胜感激。预先谢谢你。

reactjs testing react-router jestjs enzyme
1个回答
0
投票

到目前为止,我可能会建议您使用其他方法进行测试:

© www.soinside.com 2019 - 2024. All rights reserved.