Sub topic 17
Testing routes with a memory router
This chapter assumes you can write React components, you have used createBrowserRouter and RouterProvider, and you know what loaders, actions, and errorElement do. You also need a test runner (Jest or Vitest) and React Testing Library. The examples use Jest-style test, expect, and afterEach, which Vitest also provides.
Why a memory router
createBrowserRouter reads and writes the browser's address bar through the History API. A test environment such as jsdom has a fake window.location that is shared across tests, so URL changes leak from one test into the next.
createMemoryRouter keeps the history stack in an array inside the router object. You choose the starting URL, and nothing touches window. Each test gets its own router, so the tests stay independent.
The memory router is a data router, like the browser router. Loaders, actions, errorElement, and lazy all run in it. You can therefore test the same route objects you ship in production.
A first route test
The smallest useful test starts at a URL, renders the router, and checks the output.
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();
});Two details matter here:
initialEntriesis the starting history stack. It can hold several URLs, andinitialIndexpicks which one is current. Without it, the router starts at/.- The test uses
findByText, which waits, instead ofgetByText. A data router resolves matching and loaders asynchronously, so the first render may not show your route yet.
Test the real routes, not copies
If you copy route definitions into each test, the tests can pass while the app is broken. A better structure exports the routes as an array and builds the router separately.
// routes.jsx
import { Outlet, Link } from "react-router-dom";
function Layout() {
return (
<div>
<nav>
<Link to="/">Home</Link> <Link to="/about">About</Link>
</nav>
<Outlet />
</div>
);
}
export const routes = [
{
path: "/",
element: <Layout />,
children: [
{ index: true, element: <h1>Home</h1> },
{ path: "about</h1> },
{ path: "*", element: <h1>Not found</h1> },
],
},
];// mainBrowserRouter } from "react-router-dom";
import { routes } from "./routes";
export const router = createBrowserRouter(routes);Tests import routes and pass it to createMemoryRouter. A small helper removes repetition:
// test-utils.jsx
import { render } from "@testing-library/react";
import { createMemoryRouter, RouterProvider } from "react-router-dom";
export function renderRoute(routes, url) {
const router = createMemoryRouter(routes, { initialEntries: [url] });
render(<RouterProvider router={router} />);
return router;
}The helper returns the router so a test can inspect router.state.location.pathname.
Testing navigation
Click a link with @testing-library/user-event and assert on what appears. This covers the Link and the matching together.
import { screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { routes } from "./routes";
import { renderRoute } from "./test-utils";
test("clicking About shows the About page", async () => {
const user = userEvent.setup();
const router = renderRoute(routes, "/");
expect(await screen.findByText("Home")).toBeTruthy();
await user.click(screen.getByRole("link", { name: "About" }));
expect(await screen.findByText("About", { selector: "h1" })).toBeTruthy();
expect(router.state.location.pathname).toBe("/about");
});
test("unknown URLs hit the catch-all route", async () => {
renderRoute(routes, "/does/not/exist");
expect(await screen.findByText("Not found")).toBeTruthy();
});The selector: "h1" option is needed because "About" is also the text of the nav link. Querying by role, such as getByRole("heading", { name: "About" }), is often cleaner.
If a test must navigate from code, call router.navigate("/about") inside act from React. Otherwise React warns that a state update happened outside act. Prefer clicking real UI when you can, because that tests what a user does.
Testing loaders and errors
A loader calls fetch, and Node and jsdom cannot resolve a relative URL such as /api/users/1. Replace fetch in the test with a stub, and restore it afterward.
import { screen } from "@testing-library/react";
import { useLoaderData, useRouteError, isRouteErrorResponse } from "react-router-dom";
import { renderRoute } from "./test-utils";
async function userLoader({ params }) {
const res = await fetch(`/api/users/${params.userId}`);
if (!res.ok) {
throw new Response("User not found", { status: res.status });
}
return res.json();
}
function User() {
const user = useLoaderData();
return <h1>{user.name}</h1>;
}
function UserError() {
const error = useRouteError();
if (isRouteErrorResponse(error)) {
return <p>{error.status}: {error.data}</p>;
}
return <p>Something went wrong.</p>;
}
const userRoutes = [
{
path: "/users/:userId",
element: <User />,
loader: userLoader,
errorElement: <UserError />,
},
];
const realFetch = globalThis.fetch;
afterEach(() => {
globalThis.fetch = realFetch;
});
test("shows the loaded user", async () => {
globalThis.fetch = async () => ({
ok: true,
json: async () => ({ name: "Ada" }),
});
renderRoute(userRoutes, "/users/1");
expect(await screen.findByText("Ada")).toBeTruthy();
});
test("shows the errorElement when the loader throws", async () => {
globalThis.fetch = async () => ({ ok: false, status: 404 });
renderRoute(userRoutes, "/users/999");
expect(await screen.findByText("404: User not found")).toBeTruthy();
});In a real project, import userLoader, User, and UserError from your source files instead of defining them in the test. They are defined inline here so the example is complete.
The second test is the valuable one. It proves that a failing loader produces the error UI you intended, which is easy to break and hard to notice by hand.
You can also call a loader directly as a plain function, for example await userLoader({ params: { userId: "1" } }). That is faster for logic-only checks. The memory-router version additionally checks that the loader is wired to the route and that the component reads its data correctly.
Gotchas
- Create a router per test. A router holds navigation state. Sharing one across tests carries over the location and any loader data.
- Wait for async rendering. Use
findBy...orwaitForafter rendering or navigating. A synchronousgetBy...right afterrendercan fail on routes that have loaders orlazy. - Request and Response objects. Tests that run actions use
request.formData(), and redirects useResponse. Older Jest jsdom environments lack these globals. If you seeRequest is not defined, use a newer environment or add a polyfill in your setup file. - Do not wrap
RouterProviderin another router. Components rendered throughRouterProvideralready have router context. A secondMemoryRouteraround it causes an error. - Testing a component alone. A single component that calls
useParamsor renders aLinkneeds router context. Give it one route:createMemoryRouter([{ path: "/users/:userId", element: <User /> }], { initialEntries: ["/users/42"] }).
What to cover
| Behavior | How to test it |
|---|---|
| Path matching and params | Start at a URL with `initialEntries`, assert on the output |
| Links and layouts | Click with `user-event`, assert on content and `router.state.location.pathname` |
| Loaders | Stub `fetch`, render, wait for the data |
| Errors and 404 | Make the loader fail, or visit an unknown URL |
| Redirects and guards | Visit the protected URL, assert the destination |
Exercise
A test renders createMemoryRouter(routes, { initialEntries: ["/users/7"] }) with a loader on that route. It calls screen.getByText("Ada") immediately after render and fails, though the app works in the browser. What is the cause and the fix?
Show answer
The loader runs asynchronously, so the route's component has not rendered when getByText runs, and getByText does not wait. Use await screen.findByText("Ada"), or wrap the assertion in waitFor. Also make sure fetch is stubbed, because a relative URL fails in a Node or jsdom test.
Exercise
Why create a new memory router inside each test instead of one at the top of the test file?
Show answer
A router stores its history stack, current location, and loader data. A shared router carries the previous test's location and data into the next test, so results depend on test order. A new router per test starts from initialEntries every time.