Skip to content
Tutorials Center
My learning

Topics

Lesson 39 of 50 ยท Testing

Testing Routes and Components

Test React Router apps with Testing Library: render at any URL with MemoryRouter, createMemoryRouter and createRoutesStub, then check links, loaders, actions and errors.

Routing code is easy to break and easy to forget to test: a renamed path, a missing Outlet, a loader that returns the wrong shape, a link that points at the old URL. None of these produce a build error, and most of them only show up when a user clicks around. The good news is that a router does not need a browser to run. React Router can start at any URL in memory, so a test can say "the user is at /products/2" and then check what appears on screen.

This lesson shows the three tools React Router gives you for that (MemoryRouter, createMemoryRouter and createRoutesStub), how to test links, loaders, actions and error screens with Testing Library, and what to test where. The real test code is read-only because the live editor has no test runner and no npm packages. To make the ideas concrete anyway, the runnable examples contain a tiny stand-in of a memory router and a miniature test runner, written in plain React. If the general testing tools are new to you, read Testing React Components first.

Choosing what to test

Not everything needs a rendered router. A useful split:

flowchart TD
    A["Pure functions<br/>loaders, actions, helpers"] -->|"call them directly with a fake Request"| B["fast unit tests"]
    C["Route modules and layouts"] -->|"render in a memory router"| D["integration tests"]
    E["Whole app in a real browser"] -->|"Playwright or Cypress"| F["a few end-to-end tests"]

Most of your confidence should come from the first two layers, which run in milliseconds.

  • Loaders and actions are plain async functions. Call them with a Request and params and assert on the returned value or the thrown response. No React involved.
  • Components that use router features (Link, useParams, Outlet, forms) need a router around them. Render them in a memory router.
  • The route table itself deserves a few checks: "this URL reaches this page", "unknown URLs reach the 404".
  • Real browser behavior (scroll restoration, the actual History API) belongs to end-to-end tests, see End-to-End and Accessibility Testing.

Rendering at a URL with MemoryRouter

A memory router keeps the history stack in a JavaScript array instead of the browser's address bar. MemoryRouter is the declarative version, with initialEntries listing the starting URLs:

JSX
// Nav.test.jsx - Vitest + Testing Library (read-only)
import { render, screen } from "@testing-library/react";
import { MemoryRouter, Routes, Route } from "react-router";
import { describe, it, expect } from "vitest";
import { Nav } from "./Nav";

describe("Nav", () => {
  it("marks the current page as active", () => {
    render(
      <MemoryRouter initialEntries={["/about"]}>
        <Nav />
      </MemoryRouter>
    );
    expect(screen.getByRole("link", { name: "About" })).toHaveAttribute("aria-current", "page");
    expect(screen.getByRole("link", { name: "Home" })).not.toHaveAttribute("aria-current");
  });

  it("renders a link with the right href", () => {
    render(
      <MemoryRouter>
        <Nav />
      </MemoryRouter>
    );
    expect(screen.getByRole("link", { name: "Products" })).toHaveAttribute("href", "/products");
  });
});

Any component that calls a router hook or renders a Link throws an error outside a router, so tests for such components always wrap them. NavLink sets aria-current="page" on the active link, which is exactly the kind of thing a role-based query can check (see Link and NavLink).

To test a component that reads params, add a Routes tree with the same path pattern as production:

JSX
// ProductPage.test.jsx - Vitest + Testing Library (read-only)
render(
  <MemoryRouter initialEntries={["/products/42"]}>
    <Routes>
      <Route path="/products/:id" element={<ProductPage />} />
    </Routes>
  </MemoryRouter>
);
expect(screen.getByText("Product 42")).toBeInTheDocument();

Data routers: createMemoryRouter

A component tree that uses loaders, actions, useNavigation or useFetcher needs a data router. MemoryRouter does not support those, so use createMemoryRouter with the same route objects as your app and RouterProvider:

JSX
// products.test.jsx - Vitest + Testing Library (read-only)
import { createMemoryRouter } from "react-router";
import { RouterProvider } from "react-router/dom";
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { routes } from "./routes";

it("loads the product and navigates between products", async () => {
  const router = createMemoryRouter(routes, { initialEntries: ["/products/2"] });
  render(<RouterProvider router={router} />);

  // loaders are asynchronous: wait for the result with findBy
  expect(await screen.findByRole("heading", { name: "Desk" })).toBeInTheDocument();

  await userEvent.click(screen.getByRole("link", { name: "Lamp" }));
  expect(await screen.findByRole("heading", { name: "Lamp" })).toBeInTheDocument();
  expect(router.state.location.pathname).toBe("/products/1");
});

Three habits matter here:

  1. Export your route objects (routes) from a module the app and the tests both import. Then the tests exercise the real tree, nesting and loaders. This is the strongest reason to keep a route config separate from main.jsx (Routes as Objects).
  2. Use findBy queries (or waitFor) after navigation. A loader makes the screen change asynchronously. getBy fails if it runs before the data arrives.
  3. Create a new router in every test. A router holds state (the history stack, loader data). Sharing one between tests makes them depend on each other.

You can also read router.state.location, router.state.loaderData and call router.navigate("/somewhere") directly when you want to assert on navigation rather than on text.

createRoutesStub: testing one component in isolation

Component tests rarely want the full route tree. In framework mode, route modules are not even plain objects you can import into a tree. createRoutesStub builds a small fake route tree around one component, with fake loaders and actions you control:

JSX
// ProductPage.test.jsx - Vitest + Testing Library (read-only)
import { createRoutesStub } from "react-router";

it("shows the product returned by the loader", async () => {
  const Stub = createRoutesStub([
    {
      path: "/products/:id",
      Component: ProductPage,
      loader: () => ({ id: 2, name: "Desk", price: 180 }),
    },
  ]);

  render(<Stub initialEntries={["/products/2"]} />);

  expect(await screen.findByRole("heading", { name: "Desk" })).toBeInTheDocument();
});

Notice Component (capital C) rather than element: that is the data-router way of passing a component. The stub accepts the usual route fields (loader, action, ErrorBoundary, children) and an initialEntries prop. Because you write the loader, the test needs no database, no network and no server, and you can feed the component any shape of data, including the unhappy ones.

flowchart LR
    A["test"] --> B["createRoutesStub<br/>fake loader and action"]
    B --> C["router in memory"]
    C --> D["your real component"]
    D --> E["assertions on the screen"]
    D -->|"submits a form"| B

The component under test is real. Everything around it, the URL, the data and the submission handler, is controlled by the test.

Testing actions and forms

For an action, check two things: that submitting the form produces the right request, and that the page reacts to the result. With a stub, write the action as a spy:

JSX
// NewNote.test.jsx - Vitest + Testing Library (read-only)
import { vi } from "vitest";

it("submits the title to the action", async () => {
  const action = vi.fn(async ({ request }) => {
    const form = await request.formData();
    return { saved: form.get("title") };
  });
  const Stub = createRoutesStub([{ path: "/notes/new", Component: NewNote, action }]);

  render(<Stub initialEntries={["/notes/new"]} />);
  await userEvent.type(screen.getByLabelText("Title"), "Buy milk");
  await userEvent.click(screen.getByRole("button", { name: "Save" }));

  expect(await screen.findByText("Saved: Buy milk")).toBeInTheDocument();
  expect(action).toHaveBeenCalledTimes(1);
});

Your real action is tested separately, as a plain function, because it does not need React at all:

JavaScript
// notes.action.test.js - Vitest (read-only)
it("rejects an empty title", async () => {
  const body = new FormData();
  body.set("title", "");
  const request = new Request("http://localhost/notes/new", { method: "POST", body });

  const result = await action({ request, params: {}, context: {} });

  expect(result).toEqual({ errors: { title: "Title is required" } });
});

Loaders work the same way: build new Request("http://localhost/products?page=2"), call the loader, and await expect(loader(...)).rejects for thrown responses. The Fetch API classes (Request, Response, FormData) are available in current Node and in Vitest; some older Jest and jsdom setups need a polyfill.

Testing errors and redirects

  • Loader errors. Give the stub a loader that throws, and an ErrorBoundary (or use your real one). Assert on the message the user sees. See Error Boundaries and Error Elements.
  • Redirects. Render at the old URL and assert that the new page appeared. You can also check router.state.location.pathname.
  • Guards. Render a protected route with no user and assert that the login page shows up. Remember that this tests the user experience only; real access control happens on the server (Protected Routes).
  • 404s. Render at a URL no route matches and assert that the not-found page shows, inside the layout if that is the design.

A runnable stand-in harness

The real tools need a test runner, so here is a miniature version that runs in the page. It is not React Router: the stand-in createMemoryRouter matches paths, runs loader functions and exposes navigate; RouterProvider, Outlet, Link and useLoaderData mirror the real names. The harness has render, waitFor (polling, like Testing Library's findBy), expect and test. Press the button to run five tests against the route table. One test fails on purpose, so you can see what a failure report looks like.

A miniature router test harness

Four tests pass. The last one fails with expected "Product not found" but got "unknown", because the loader falls back to the word unknown. The test describes the behavior you want. Fix the app (change the ?? 'unknown' fallback in the loader to 'Product not found') or change the expectation, run the tests again and watch it turn green. That loop, describing behavior at a URL and checking what renders, is what a Testing Library test with createMemoryRouter does too.

Table-driven tests for the route config

For the route table itself, a list of [url, expected route] pairs is the fastest test there is. It needs no rendering at all: the stand-in below matches URLs against route patterns, and the table of expectations reports each row. Tick the box to introduce a typo in one route and see which row catches it.

Table-driven route tests

With the typo only the /products/7 row fails: it falls through to the catch-all and reports not-found. A five-line table like this catches renamed paths and shadowed routes before a user does. The same idea works with real React Router through matchRoutes(routes, "/products/7"), which returns the matched route chain and params without rendering anything.

Practical tips

  • Prefer role-based queries (getByRole("link", { name }), getByRole("heading")) over test IDs; they also verify accessibility.
  • Use userEvent rather than fireEvent for clicks and typing, because it fires the full sequence of browser events.
  • Keep tests independent: new router per test, no shared mutable module state in loaders.
  • Mock at the boundary (the fetch call or your API client), not the router. A router you replaced with a mock tests nothing about routing.
  • Do not assert on window.location in a memory router test: the address bar is not used. Read router.state.location instead.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does a component that renders a Link fail in a test unless you wrap it in a router?

    Link and the router hooks read the current location and navigate function from context. Outside a router that context is missing, so React Router throws. MemoryRouter or createMemoryRouter provides it.
  2. 2. Your component uses a loader and useNavigation. Which tool can you NOT use to render it?

    Loaders, actions and navigation state need a data router. MemoryRouter is the declarative router, so those features are unavailable; createMemoryRouter and createRoutesStub create data routers.
  3. 3. After clicking a link whose route has a loader, which query is the right way to check the new heading?

    The screen changes only after the loader finishes. findBy queries retry until the element appears or a timeout passes, so the test is fast and not flaky.
  4. 4. What is createRoutesStub mainly for?

    createRoutesStub builds an in-memory data router around the component under test. You supply fake loaders and actions, so no server or database is needed.
  5. 5. How should you test your real action function?

    Actions and loaders are plain async functions of a Request. Calling them directly is fast and covers validation logic without any React rendering.

Summary

  • A memory router runs the router in memory, so tests can start at any URL with initialEntries.
  • Use MemoryRouter for declarative components, and createMemoryRouter with RouterProvider when loaders, actions or navigation state are involved; export your route objects so tests use the real tree.
  • createRoutesStub wraps one component in a fake route tree with loaders and actions you write, ideal for component tests and framework-mode route modules.
  • Await results with findBy or waitFor, use a fresh router per test and query by role.
  • Test loaders and actions as plain functions with a Request, and test the route table with a table of URLs and expected matches.

Next: Project: A Multi-Page Site with Nested Layouts