Skip to content
Tutorials Center
My learning

Topics

Lesson 33 of 39 ยท Testing and Deployment

Testing Loaders and Actions

Unit test Remix and React Router loaders and actions as plain functions: build Request objects, assert on data, status and redirects, fake the database and cookies, with Vitest examples.

Loaders and actions are the easiest part of a Remix or React Router app to test, because they are plain async functions: they take an object with a standard Request and params, and return data or a Response. There is no browser, no component tree and no server to start. You call the function, then check what came back. This lesson shows how, with Vitest code (read-only, since the site cannot run Vitest) and a runnable stand-in harness using Node's built-in assert.

The shape of a test

TypeScript
// app/routes/notes.$id.test.ts (read-only, Vitest)
import { describe, it, expect, vi } from "vitest";
import { loader, action } from "./notes.$id";

vi.mock("~/db.server", () => ({
  db: { note: { findFirst: vi.fn(), delete: vi.fn() } },
}));

describe("note loader", () => {
  it("returns the note for its owner", async () => {
    db.note.findFirst.mockResolvedValue({ id: "7", title: "Hello" });

    const request = new Request("http://localhost/notes/7", {
      headers: { Cookie: await sessionCookieFor("user-1") },
    });
    const result = await loader({ request, params: { id: "7" }, context: {} } as any);

    expect(result).toEqual({ note: { id: "7", title: "Hello" } });
  });

  it("throws 404 for someone else's note", async () => {
    db.note.findFirst.mockResolvedValue(null);
    const request = new Request("http://localhost/notes/8");

    await expect(
      loader({ request, params: { id: "8" }, context: {} } as any)
    ).rejects.toMatchObject({ status: 404 });
  });
});

Three ideas carry the whole approach:

  1. Build a real Request. Node 18+ and the test runners provide Request, Response, Headers and FormData globally. A POST body is just new FormData().
  2. Throws are rejections. A thrown redirect or data() is a rejected promise, so assert with rejects.
  3. Fake only the edges. Replace the database module and the clock, not your own logic.

Testing an action with form data

TypeScript
it("rejects an empty title", async () => {
  const body = new FormData();
  body.set("title", "");
  const request = new Request("http://localhost/notes", { method: "POST", body });

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

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

Test the important paths: success, each validation failure, not-signed-in, wrong owner, and unexpected failure from a dependency (make the mock throw). Each is a short test.

Node.js Stand-in: test a loader and an action with node:assert

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.

Making routes easy to test

  • Keep the business logic in plain modules (createNote(userId, input)), call them from the action, and test those directly. The action then only translates Request into arguments and results into responses.
  • Keep session helpers behind one module (requireUserId). In a test, mock that module to return a fixed ID instead of crafting cookies in every test.
  • Inject the clock and random values rather than calling Date.now() or Math.random() inside logic.

Testing authentication helpers

A security helper deserves its own tests because mistakes are costly: tampered cookies are rejected, expired sessions return null, return paths that start with // are refused. The logic from Protecting Routes is small and pure, so these tests are fast.

Node.js Stand-in: test the safe-redirect helper

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.

What to test and what to skip

Test behavior that would hurt if it broke: access control, validation, money, redirects, data shaping. Do not test the framework (that a loader's return value reaches the component is React Router's job) and avoid asserting on incidental details such as the exact order of object keys. End-to-end tests (Playwright) cover whole journeys such as sign-up and checkout; unit tests on loaders and actions cover the many edge cases cheaply. The next lesson covers testing components that use routes.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why are loaders and actions easy to unit test?

    You construct a Request, call the function and assert on the result.
  2. 2. How do you assert that a loader threw a redirect?

    throw redirect() rejects the promise, so use rejects and inspect status and the Location header.
  3. 3. What should be faked in loader tests?

    Faking your own logic makes tests prove nothing. Fake external dependencies.
  4. 4. How do you send form data in a test Request?

    new Request(url, { method: 'POST', body: formData }) matches what a browser sends.

Summary

  • Call loaders and actions directly with a real Request, params and a FormData body.
  • Assert returned data, rejects for thrown responses, status codes and Location headers.
  • Mock only the edges; keep business logic and security helpers in small pure modules.
  • Test access control, validation and error paths first.

Next: Testing Routes with Stubs