【发布时间】:2022-01-29 23:33:33
【问题描述】:
我遇到了错误。请告诉如何编写测试用例来测试包装在 withRouter 中的组件和使用 useLocation() 的组件 ● 测试套件无法运行
TypeError: (0 , _reactRouterDom.withRouter) is not a function
【问题讨论】:
标签: reactjs jestjs react-router react-testing-library
我遇到了错误。请告诉如何编写测试用例来测试包装在 withRouter 中的组件和使用 useLocation() 的组件 ● 测试套件无法运行
TypeError: (0 , _reactRouterDom.withRouter) is not a function
【问题讨论】:
标签: reactjs jestjs react-router react-testing-library
出现此错误是因为路由组件树未附加到渲染方法。
我建议创建一个 TestUtils,它从 react-testing-library 和路由器层次结构中抽象出渲染:
这或多或少:
export const renderWithRouter = (
children,
{
path = '/',
initialRoute = '/',
history = createMemoryHistory({ initialEntries: [initialRoute] })
} = {}
) => {
return {
...render(
<Router history={history}>
<Route path={path}>{children}</Route>
</Router>
),
history
};
};
用法:
路由中没有参数:
const wrapper = renderWithRouter(<Component />);
在路由中有参数:
const wrapper = renderWithRouter(<Component />, { path: '/route/:id', initialRoute: '/route/1' });
其中 :id 将被 1 替换
【讨论】: