Next.jsHard
How do you test Server Components?
Synchronous Server Components can be rendered with React Testing Library like any component. Async Server Components are not fully supported by Jest or Vitest renderers, so the recommended approach is to test them end to end, and to unit test their pieces separately: the data functions, and presentational child components rendered with props.
Strategies
- Split data from presentation.
async function Page()fetches and passes data to<ProductList products={...} />. Unit testProductListwith props, and unit testgetProducts()with a mocked database. - Test data access functions directly. They are plain async functions: call them with a test database or mocked client, and assert on results and authorization behavior.
- E2E with Playwright for the real rendering, streaming, caching and Suspense behavior.
- Workaround for simple async components:
render(await Page())calls the component as a function and renders the returned JSX. It only works when no nested async components or server-only APIs are involved, so treat it as a limited trick.
Mocking server APIs
cookies()andheaders()fromnext/headers: mock the module in unit tests."use cache",cacheLifeandcacheTag: mocknext/cacheso they are no-ops outside a Next.js build.server-only: alias it to an empty module in the test config.
What not to test in units
Caching and prerender behavior, Suspense streaming and RSC serialization. These are framework behaviors; verify them with E2E tests and next build validation instead.
Code example
tsx
1// app/products/product-list.tsx - presentational, easy to test2export function ProductList({ products }: { products: { id: string; name: string }[] }) {3 if (products.length === 0) return <p>No products yet</p>;4 return <ul>{products.map((p) => <li key={p.id}>{p.name}</li>)}</ul>;5}67// app/products/page.tsx - thin async wrapper, covered by E2E8// export default async function Page() {9// const products = await getProducts();10// return <ProductList products={products} />;11// }1213// app/products/product-list.test.tsx14import { render, screen } from "@testing-library/react";15import { expect, test, vi } from "vitest";1617vi.mock("server-only", () => ({}));18vi.mock("next/cache", () => ({ cacheLife: () => {}, cacheTag: () => {} }));1920test("renders products", () => {21 render(<ProductList products={[{ id: "1", name: "Shoe" }]} />);22 expect(screen.getByRole("listitem")).toHaveTextContent("Shoe");23});2425test("empty state", () => {26 render(<ProductList products={[]} />);27 expect(screen.getByText("No products yet")).toBeInTheDocument();28});
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the Next.js set.