我按照此从 React Router v5 迁移到 v6tutorial https://reactrouter.com/en/main/start/tutorial。我想测试一下反应测试库 https://testing-library.com/,但是我的旧单元测试(使用中的模式this doc https://testing-library.com/docs/example-react-router/) 停止工作。
我的 React Router v6 应用程序是这样的
const router = createBrowserRouter([
{
path: "/",
element: (
<>
<SiteHeader />
<Outlet />
</>
),
errorElement: <NotFound />,
children: [
{ path: "/", element: <Home /> },
{ path: "/posts", element: <Posts /> },
{ path: "/post/:postId", element: <PostPage /> },
],
},
]);
function App() {
return (
<div className="app">
<RouterProvider router={router} />
</div>
);
}
正如你所看到的,它正在使用RouterProvider
代替Switch
/Route
(所以我很困惑这所以问题 https://stackoverflow.com/questions/70654872/how-to-test-react-router-v6-outlet-using-testing-library-react说它正在使用 React Router v6,但看起来很不同。)。
测试库官方文档中的代码 https://testing-library.com/docs/example-react-router/没有使用RouterProvider
either.
我想测试一些路由逻辑,如以下伪代码:
renderWithRouter(<App />, "/posts"); // loads /posts page initially
await user.click(screen.getByText("some post title")); // trigger click
expect(getUrl(location)).toEqual("/post/123"); // checks the URL changed correctly
我怎样才能创建一个renderWithRouter
功能类似于this https://testing-library.com/docs/example-react-router/#reducing-boilerplate with RouterProvider
?注意this renderWithRouter https://testing-library.com/docs/example-react-router/#reducing-boilerplate当我使用 React Router v5 时,它对我有用,但迁移到 v6 后,它停止工作。
我当前的依赖版本:
- “反应”:“^18.2.0”,
- "react-dom": "^18.2.0",
- "react-router-dom": "^6.4.3",
- "@testing-library/jest-dom": "^5.16.5",
- "@testing-library/react": "^13.4.0",
- "@testing-library/user-event": "^14.4.3",
我试过这个
test("click post goes to /post/:postId", async () => {
render(
<MemoryRouter initialEntries={["/posts"]}>
<App />
</MemoryRouter>,
);
// ...
});
但我得到了错误
You cannot render a <Router> inside another <Router>. You should never have more than one in your app.
31 | test("click post goes to /post/:postId", async () => {
> 32 | render(
| ^
34 | <MemoryRouter initialEntries={["/posts"]}>
36 | <App />