Skip to content
Tutorials Center
My learning

Topics

Lesson 34 of 39 ยท Testing and Deployment

Testing Routes and Components with Stubs

Test components that use loaders, links and forms with createRoutesStub, Testing Library and Playwright for end-to-end checks, plus when to use each kind of test.

Unit tests on loaders and actions cover the server logic. Components are different: they call useLoaderData, render <Link> and <Form>, and read route context, all of which need a router around them. If you render such a component alone, it throws "useLoaderData must be used within a data router." The fix is a router built for the test. React Router provides createRoutesStub for exactly this: you describe a tiny route tree with fake loaders and actions, render it, and test the component as a user would.

This lesson shows the pattern with Testing Library and Vitest (read-only here), then models what a routes stub does in a runnable block, and ends with end-to-end testing and a testing strategy.

createRoutesStub

TSX
// app/components/profile-card.test.tsx (read-only, Vitest + Testing Library)
import { createRoutesStub } from "react-router";
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, it, expect } from "vitest";
import ProfileRoute from "~/routes/profile";

describe("profile route", () => {
  it("shows the name from the loader", async () => {
    const Stub = createRoutesStub([
      {
        path: "/profile",
        Component: ProfileRoute,
        loader: () => ({ user: { name: "Ada Lovelace" } }),
      },
    ]);

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

    expect(await screen.findByText("Ada Lovelace")).toBeInTheDocument();
  });

  it("shows the action's validation error", async () => {
    const Stub = createRoutesStub([
      {
        path: "/profile",
        Component: ProfileRoute,
        loader: () => ({ user: { name: "Ada" } }),
        action: () => ({ errors: { name: "Name is required" } }),
      },
    ]);

    render(<Stub initialEntries={["/profile"]} />);
    await userEvent.clear(await screen.findByLabelText("Name"));
    await userEvent.click(screen.getByRole("button", { name: "Save" }));

    expect(await screen.findByRole("alert")).toHaveTextContent("Name is required");
  });
});

Points to notice:

  • The stub supplies the data. The real loader (with its database) is never run, so the test is fast and deterministic.
  • Use findBy... queries, which wait: the router renders asynchronously after the loader resolves.
  • Query by role and label, as a user or a screen reader would, not by CSS class. That keeps tests valid when markup changes and nudges you toward accessible forms.
  • Pass initialEntries to start at a URL, and include extra routes in the array to test navigation (a link to / needs a / route to land on).

Why a stub rather than the real thing

A stub isolates the component from your server. You can make a loader return an empty list, a huge list or a slow promise, and make an action fail, to test the empty state, the pagination and the error message. Those cases are painful to create with a real database but trivial with a stub.

Node.js Stand-in: a routes stub in miniature

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Testing hooks and context

Components that read useOutletContext, useParams or useSearchParams work inside a stub too; put the parent route in the array and render the child path. For a pure custom hook with no router, use renderHook from Testing Library. For forms, use userEvent to type and submit, then assert on what appears; do not assert on internal state.

End-to-end tests with Playwright

Stubs prove a component handles data correctly. They cannot prove that the whole system works: the real database, cookies, redirects and the browser. A small set of end-to-end tests covers critical journeys against a running app:

TypeScript
// e2e/login.spec.ts (read-only, Playwright)
import { test, expect } from "@playwright/test";

test("a user can sign in and sees the dashboard", async ({ page }) => {
  await page.goto("/login");
  await page.getByLabel("Email").fill("[email protected]");
  await page.getByLabel("Password").fill("correct horse battery");
  await page.getByRole("button", { name: "Sign in" }).click();

  await expect(page).toHaveURL("/dashboard");
  await expect(page.getByRole("heading", { name: "Dashboard" })).toBeVisible();
});

test("visitors are redirected away from the dashboard", async ({ page }) => {
  await page.goto("/dashboard");
  await expect(page).toHaveURL(/\/login\?return=/);
});

Run these against a test database that is reset before each run, with a seeded user. Keep them few (sign-up, sign-in, the main create-edit-delete journey, checkout) because they are slower and more fragile.

A balanced strategy

flowchart TD
  E["End-to-end (few): full journeys in a real browser"]
  C["Component with routes stub (some): each screen, empty and error states"]
  U["Unit tests of loaders, actions, helpers (many): fast, thorough edge cases"]
  U --> C --> E

Many small fast tests at the bottom, a few broad ones at the top.

Node.js Stand-in: a scenario table for one screen

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does rendering a component that uses useLoaderData alone fail in a test?

    Route hooks read from the router context. A stub creates a small router just for the test.
  2. 2. Which query style does Testing Library recommend?

    Role and label queries survive markup refactors and encourage accessible markup.
  3. 3. Why use findBy queries after rendering a stub?

    findBy returns a promise that retries until the element appears.
  4. 4. What are end-to-end tests best used for?

    They are slower and more brittle, so keep them for sign-up, sign-in and the main journeys.

Summary

  • createRoutesStub gives route-aware components a router with fake loaders and actions.
  • Use stubs to test normal, empty, loading and error states without a database.
  • Query by role and label; use findBy for async rendering.
  • Add a handful of Playwright journeys; keep unit tests of loaders and actions as the foundation.

Next: Deployment Targets