【发布时间】: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