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
FormDataor with arguments. - Mock the database module.
- Mock
next/cache(forrevalidatePath) ornext/navigation(forredirect). - 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/cacheandnext/navigation. - Test validation and authorisation checks inside actions.