Sub topic 17
Testing routes with a memory router
This chapter assumes you know how to define routes with createBrowserRouter, how loaders and errorElement work, and how to write a basic test with a runner such as Vitest or Jest and React Testing Library. It covers testing your route configuration without a real browser.
Why a memory router
createBrowserRouter reads and writes the browser's address bar through the History API. In a test environment such as jsdom, that state is shared between tests and hard to control. createMemoryRouter keeps the history in an array in memory instead. You choose where it starts with initialEntries, and each test gets a fresh router.
The rest of the API is the same. You pass the same route objects and render the result with RouterProvider.
A first route test
This test starts at /users/42 and checks that the matching route renders.
import { render, screen } from "@testing-library/react";
import { createMemoryRouter, RouterProvider } from "react-router-dom";
test("renders the user page for /users/42", async () => {
const router = createMemoryRouter(
[{ path: "/users/:userId", element: <h1>User page</h1> }],
{ initialEntries: ["/users/42"] }
);
render(<RouterProvider router={router} />);
expect(await screen.findByText("User page")).toBeTruthy();
});Use findBy queries, which wait for the element. Data routers render asynchronously, so a synchronous getBy can run before the route appears.
Testing the real route config
A test that redefines routes proves little. Export your route array from one module, and use it in both the app and the tests:
// routes.jsx
export const routes = [
{ path: "/", element: <Layout />, children: [/* ... */] },
];
// app: createBrowserRouter(routes)
// test: createMemoryRouter(routes, { initialEntries: ["/missing"] })With this setup you can check a 404 page by starting at a URL that no route matches. You can check a redirect by starting at a protected URL and asserting that the login page appears.
Loaders and errors in tests
Loaders run when the router starts, so the test must supply the data. Stub fetch rather than calling a real API:
import { vi } from "vitest";
beforeEach(() => {
globalThis.fetch = vi.fn().mockResolvedValue({
ok: true,
json: async () => ({ name: "Ada" }),
});
});To test an errorElement, make the stub return { ok: false, status: 404 }. Your loader will throw a Response, and the test can assert that the error message is shown.
Common mistakes
- Forgetting
initialEntries. The router then starts at/, and your test renders the wrong route. - Using
getByfor content that appears after a loader finishes. - Rendering a component that uses
LinkoruseParamswithout any router. It throws an error about missing router context. Wrap it in a memory router, even a single-route one. - Leaving a stubbed
fetchin place between tests. Reset it inbeforeEachorafterEach.
Exercise
Why do tests for route components use createMemoryRouter instead of createBrowserRouter, and how do you make a test start on /users/42?
Show answer
createMemoryRouter keeps navigation history in memory, so each test is isolated and does not depend on the browser's address bar. Pass { initialEntries: ["/users/42"] } as the second argument, then render the router with RouterProvider.
Exercise
A test renders a route with a loader and uses screen.getByText for the loaded data, and it fails even though the app works. What is the likely cause and fix?
Show answer
The loader has not finished when getByText runs, so the content is not on the screen yet. Use an async query such as await screen.findByText, which waits for the element to appear.