CodePark/ questions / Testing Next.js
START PRACTICINGPRACTICE
Frontend question · Testing › Testing Next.js

How do you test async Server Components and Server Actions in the Next.js App Router?

jest.mock("@/lib/db");
jest.mock("next/cache", () => ({ revalidatePath: jest.fn() }));

test("createTodo saves and revalidates", async () => {
  const form = new FormData();
  form.set("title", "Write tests");
  await createTodo(form);
  expect(db.todo.create).toHaveBeenCalledWith({ data: { title: "Write tests" } });
  expect(revalidatePath).toHaveBeenCalledWith("/todos");
});

Test async Server Components with E2E tests, and unit test the logic around them. Test Server Actions by calling them directly.

Async Server Components are not well supported by Jest or Vitest yet. They run on the server, and Next's own pipeline renders them. So the Next.js docs recommend E2E tests for them, such as Playwright against a running app.

You can still unit test the logic around them. Move data fetching and transformation into plain functions, such as getPosts(), and test those directly.

Server Actions are async functions too. To test one:

  • Call it with a FormData or with arguments.
  • Mock the database module.
  • Mock next/cache (for revalidatePath) or next/navigation (for redirect).
  • Assert on the result and on the calls.
  • Test the validation and authorisation checks inside the action, because anyone can call it.

Client Components that the server renders are tested normally with RTL.

  • The Next docs recommend E2E tests for async Server Components.
  • Move data logic into plain functions and unit test them.
  • Server Actions are async functions, so call them directly.
  • Mock the database, next/cache and next/navigation.
  • Test validation and authorisation checks inside actions.