React Server Components 26 🧬 Testing RSC — Strategies for server and client trees
Testing an RSC application is not one problem. It is three problems, and each has a different solution. A synchronous Server Component can be tested with a unit test that calls the function and inspects the returned JSX. An asynchronous Server Component cannot be tested that way—the React Testing Library’s render() function receives a Promise, not a component, and the test fails before any assertion runs . A Client Component can be tested with the same tools as any other React component, but the test environment must be configured to handle the "use client" boundary and the framework-specific imports. And the integration of the two—the serialization boundary, the streaming, the Server Actions—can only be tested end-to-end, because the integration depends on the framework’s server and bundler, not on React alone.
The official Next.js documentation states the limitation plainly: “Since async Server Components are new to the React ecosystem, Vitest currently does not support them. While you can still run unit tests for synchronous Server and Client Components, we recommend using E2E tests for async components” . This is not a configuration gap. It is a boundary of the unit-testing model. The async component returns a Promise, and the test renderer has no way to await it within the synchronous render() call. The workaround is not to mock the Promise and force the component through a synchronous renderer. The workaround is to test the component’s output through Playwright, where the framework’s server is running and the component actually executes .
Key point: Synchronous Server and Client Components are unit-testable with Vitest and React Testing Library. Asynchronous Server Components are not; they must be tested end-to-end with Playwright. The boundary is the async keyword, not the "use server" directive.
Why the testing strategy splits
The async rendering problem. A synchronous Server Component returns JSX directly. The test can call the component as a function, receive the JSX, and render it with React Testing Library. An asynchronous Server Component returns a Promise that resolves to JSX. The test would need to await the Promise before rendering, but React Testing Library’s render() is synchronous. The result is a Promise passed to a function that expects a React element, and the test fails with a type error that does not mention the real cause .
The framework dependency problem. An async Server Component typically fetches data. The fetch may use the framework’s caching layer, the framework’s request context, or the framework’s environment variables. A unit test can mock the fetch function, but the mock does not exercise the framework’s integration. The test verifies that the component renders the mocked data; it does not verify that the component works in the framework. The E2E test exercises the integration, because the framework’s server is running and the fetch is real (or mocked at the network level, not the module level) .
The serialization boundary problem. The Server-to-Client boundary is a serialization point. A unit test of a Client Component receives its props directly, without serialization. The test does not verify that the props are serializable, that the Server Component passes the correct props, or that the Client Component renders correctly after deserialization. The E2E test exercises the full path: the Server Component renders, the props are serialized, the client receives them, the Client Component hydrates, and the UI updates . The serialization failure is invisible to the unit test.
The Server Action problem. A Server Action is an HTTP endpoint. A unit test that calls the action function directly does not exercise the HTTP layer, the serialization of the arguments, the redirect, or the cookie mutation. The E2E test submits the form, the action executes on the server, and the UI reflects the result . The unit test can verify the action’s logic, but the integration is verified only by the E2E test.
a. Unit testing synchronous components
The unit test for a synchronous component—whether Server or Client—follows the standard React Testing Library pattern. The component is imported, rendered, and queried.
// __tests__/greeting.test.tsx — a synchronous Server Component
import { expect, test } from "vitest";
import { render, screen } from "@testing-library/react";
import { Greeting } from "@/components/greeting";
test("Greeting renders the name", () => {
// The component is synchronous.
// It returns JSX directly, not a Promise.
// The render function receives the JSX and returns a result.
render(<Greeting name="Alice" />);
// The query finds the heading by role and name.
expect(screen.getByRole("heading", { name: "Hello, Alice" })).toBeDefined();
});
The configuration for Vitest requires the jsdom environment and the @vitejs/plugin-react plugin. The vite-tsconfig-paths plugin resolves the @/ aliases if the project uses them . The test file can be colocated with the component or placed in a __tests__ directory. The convention is not enforced by Vitest; it is a project decision.
// __tests__/button.test.tsx — a Client Component
"use client";
import { expect, test, vi } from "vitest";
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { Button } from "@/components/button";
test("Button calls onClick", async () => {
const handleClick = vi.fn();
render(<Button onClick={handleClick}>Click me</Button>);
// userEvent simulates a real interaction.
await userEvent.click(screen.getByRole("button"));
expect(handleClick).toHaveBeenCalledTimes(1);
});
The Client Component test is identical to a standard React component test. The "use client" directive is a bundler instruction, not a runtime instruction. In the test environment, the component runs in jsdom, and the directive has no effect. The test verifies the component’s behavior in isolation, without the server, without the serialization boundary, and without the framework .
The limitation of these tests is the limitation of all unit tests. They verify the component’s logic, not the component’s integration. A Button that calls onClick correctly in a unit test may still fail in the application if the onClick handler is a Server Action reference that was not serialized correctly, or if the Button is rendered inside a Server Component that passes a non-serializable prop.
b. End-to-end testing of async components and Server Actions
The E2E test runs against a real server. The framework’s build has produced the client and server bundles, the server is running, and the browser loads the application. The test navigates to a route, waits for the content, and asserts on the rendered output.
// e2e/user-profile.spec.ts — an async Server Component
import { test, expect } from "@playwright/test";
test("user profile renders the fetched data", async ({ page }) => {
// Navigate to the route that renders the async Server Component.
// The framework's server executes the component,
// serializes the result, and streams it to the browser.
await page.goto("/user/123");
// The assertion waits for the content to appear.
// The content is the result of the async fetch,
// not a mocked value.
await expect(page.getByTestId("user-name")).toHaveText("John Doe");
await expect(page.getByTestId("user-email")).toHaveText("john@example.com");
});
The page.goto() call triggers the server render. The expect assertion waits for the element to appear, which means the test implicitly waits for the async component to resolve, the fetch to complete, the serialization to happen, and the client to render. The test does not need to know how the component works; it only needs to know what the user sees .
// e2e/contact-form.spec.ts — a Server Action
import { test, expect } from "@playwright/test";
test("contact form submits via Server Action", async ({ page }) => {
await page.goto("/contact");
// Fill the form fields.
await page.getByLabel("Name").fill("John Doe");
await page.getByLabel("Email").fill("john@example.com");
await page.getByLabel("Message").fill("Hello, this is a test.");
// Submit the form.
// The form's action is a Server Action.
// The click triggers the network request to the Server Action endpoint.
await page.getByRole("button", { name: "Send Message" }).click();
// The success feedback appears after the action completes.
// The test verifies the action executed and the UI updated.
await expect(page.getByText("Message sent successfully")).toBeVisible();
// The form resets after a successful action.
await expect(page.getByLabel("Name")).toHaveValue("");
});
The test verifies the complete flow: the form submission, the Server Action execution, the response, and the UI update. The unit test of the action function would verify the function’s logic, but it would not verify the form submission, the serialization of the FormData, the HTTP endpoint, or the UI update . The E2E test is the only test that covers the integration.
The useFormStatus pending state can also be tested. The test slows down the network request with page.route() and then asserts that the button shows the pending label while the request is in flight . The pending state is a client-side behavior that depends on the action’s lifecycle, and it is verified only when the action actually runs.
Complete Example Session
// ============================================
// PART 1: THE VITEST CONFIGURATION
// ============================================
// vitest.config.mts
import { defineConfig } from "vitest/config";
import react from "@vitejs/plugin-react";
import tsconfigPaths from "vite-tsconfig-paths";
export default defineConfig({
plugins: [tsconfigPaths(), react()],
test: {
// jsdom provides the browser environment.
// The "use client" directive has no effect in this environment;
// the component runs in the test renderer.
environment: "jsdom",
},
});
// ============================================
// PART 2: THE SYNCHRONOUS SERVER COMPONENT TEST
// ============================================
// components/greeting.tsx
export function Greeting({ name }: { name: string }) {
return <h1>Hello, {name}!</h1>;
}
// __tests__/greeting.test.tsx
import { expect, test } from "vitest";
import { render, screen } from "@testing-library/react";
import { Greeting } from "@/components/greeting";
test("Greeting renders the name", () => {
// The component is synchronous.
// It returns JSX, not a Promise.
// The test renders it and asserts on the output.
render(<Greeting name="Alice" />);
expect(screen.getByRole("heading", { name: "Hello, Alice!" })).toBeDefined();
});
// ============================================
// PART 3: THE ASYNC SERVER COMPONENT (NOT UNIT TESTABLE)
// ============================================
// components/user-profile.tsx
export async function UserProfile({ userId }: { userId: string }) {
// The fetch runs on the server during render.
const user = await fetch(`https://api.example.com/users/${userId}`).then(r => r.json());
return <h1>{user.name}</h1>;
}
// __tests__/user-profile.test.tsx — THIS DOES NOT WORK.
// import { render } from "@testing-library/react";
// import { UserProfile } from "@/components/user-profile";
//
// test("renders the user", () => {
// render(<UserProfile userId="123" />); // ❌ receives a Promise
// });
//
// The async function returns a Promise.
// React Testing Library's render() expects a React element.
// The test fails before the assertion runs.
// ============================================
// PART 4: THE E2E TEST FOR THE ASYNC COMPONENT
// ============================================
// e2e/user-profile.spec.ts
import { test, expect } from "@playwright/test";
test("user profile renders the fetched data", async ({ page }) => {
// The framework's server executes the async component.
// The result is serialized and streamed to the browser.
await page.goto("/user/123");
// The assertion waits for the rendered content.
// The content is the result of the real fetch.
await expect(page.getByRole("heading", { name: "John Doe" })).toBeVisible();
});
// ============================================
// PART 5: THE CLIENT COMPONENT TEST
// ============================================
// components/button.tsx
"use client";
export function Button({ onClick, children }: { onClick: () => void; children: React.ReactNode }) {
return <button onClick={onClick}>{children}</button>;
}
// __tests__/button.test.tsx
import { expect, test, vi } from "vitest";
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { Button } from "@/components/button";
test("Button calls onClick", async () => {
const handleClick = vi.fn();
render(<Button onClick={handleClick}>Click me</Button>);
// userEvent simulates a real click.
await userEvent.click(screen.getByRole("button"));
expect(handleClick).toHaveBeenCalledTimes(1);
});
// ============================================
// PART 6: THE SERVER ACTION E2E TEST
// ============================================
// e2e/contact-form.spec.ts
import { test, expect } from "@playwright/test";
test("contact form submits via Server Action", async ({ page }) => {
await page.goto("/contact");
// Fill the form.
await page.getByLabel("Name").fill("John Doe");
await page.getByLabel("Email").fill("john@example.com");
await page.getByLabel("Message").fill("Hello, this is a test.");
// Submit the form.
// The form's action is a Server Action.
await page.getByRole("button", { name: "Send Message" }).click();
// The success feedback appears after the action completes.
await expect(page.getByText("Message sent successfully")).toBeVisible();
// The form resets after a successful action.
await expect(page.getByLabel("Name")).toHaveValue("");
});
// ============================================
// PART 7: THE PENDING STATE TEST
// ============================================
// e2e/pending-state.spec.ts
import { test, expect } from "@playwright/test";
test("shows pending state during Server Action", async ({ page }) => {
// Slow down the Server Action request.
// The route handler intercepts the POST request
// and delays it before continuing.
await page.route("/contact", async (route) => {
if (route.request().method() === "POST") {
await new Promise((resolve) => setTimeout(resolve, 2000));
}
await route.continue();
});
await page.goto("/contact");
await page.getByLabel("Name").fill("Test");
await page.getByLabel("Email").fill("test@example.com");
await page.getByLabel("Message").fill("Test");
await page.getByRole("button", { name: "Send Message" }).click();
// The button shows the pending label while the action is in flight.
// useFormStatus reads the parent form's pending state.
await expect(page.getByRole("button", { name: "Sending..." })).toBeVisible();
});
// ============================================
// PART 8: THE SUSPENSE BOUNDARY TEST
// ============================================
// e2e/suspense.spec.ts
import { test, expect } from "@playwright/test";
test("shows loading state then content", async ({ page }) => {
// Slow down the API that the Server Component fetches.
await page.route("/api/slow-data", async (route) => {
await new Promise((resolve) => setTimeout(resolve, 2000));
await route.fulfill({ body: JSON.stringify({ data: "loaded" }) });
});
await page.goto("/dashboard");
// The Suspense fallback is visible first.
await expect(page.getByTestId("loading-skeleton")).toBeVisible();
// The real content streams in after the fetch completes.
await expect(page.getByTestId("dashboard-content")).toBeVisible();
await expect(page.getByTestId("loading-skeleton")).toBeHidden();
});
// ============================================
// PART 9: THE MOCKING STRATEGY
// ============================================
// Unit tests mock at the module level:
// vi.mock("@/lib/db", () => ({ db: { query: vi.fn() } }));
//
// E2E tests mock at the network level:
// page.route("/api/users/*", (route) => route.fulfill({ body: "..." }));
//
// The module-level mock verifies the component's logic.
// The network-level mock verifies the integration with the framework.
// ============================================
// PART 10: THE VERIFICATION CHECKLIST
// ============================================
// [ ] Synchronous Server Components are unit-tested.
// [ ] Client Components are unit-tested.
// [ ] Async Server Components are E2E-tested.
// [ ] Server Actions are E2E-tested.
// [ ] The pending state is E2E-tested.
// [ ] The Suspense fallback is E2E-tested.
// [ ] The Vitest configuration uses the jsdom environment.
// [ ] The Playwright configuration runs against a production build.
The ten parts covered the Vitest configuration, the synchronous component test, the async limitation, the E2E test for the async component, the Client Component test, the Server Action test, the pending state, the Suspense boundary, the mocking strategy, and the verification checklist. The through-line is that the test tool matches the component type, and the async Server Component is the boundary that forces the E2E approach.
Quick Reference
Test tool by component type
| Component type | Unit test (Vitest) | E2E test (Playwright) |
|---|---|---|
| Synchronous Server Component | Yes | Optional |
| Async Server Component | No | Yes |
| Client Component | Yes | Optional |
| Server Action | No | Yes |
The async limitation
| Symptom | Cause | Fix |
|---|---|---|
render() receives a Promise | The component is async | Test via E2E |
| Type error on the render result | The Promise was not awaited | The test renderer cannot await; use E2E |
The mocking levels
| Test type | Mock level | What it verifies |
|---|---|---|
| Unit | Module (vi.mock) | Component logic |
| E2E | Network (page.route) | Framework integration |
Best Practices
✅ Do This:
// Unit test synchronous components
render(<Greeting name="Alice" />); // ✅
// E2E test async components
await page.goto("/user/123"); // ✅
// Mock at the network level for E2E
await page.route("/api/user/*", (route) => route.fulfill(...)); // ✅
// Test the pending state with a delayed route
await page.route("/contact", async (route) => { /* delay */ }); // ✅
❌ Don’t Do This:
// Unit test an async Server Component
render(<AsyncComponent />); // ❌
// Mock at the module level for E2E
vi.mock("@/lib/db"); // ❌ (in Playwright)
// Test a Server Action without the form
await login(formData); // misses the HTTP layer // ❌
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Vitest test fails on an async component | render() receives a Promise | Move the test to Playwright |
| E2E test is flaky | Waiting for the wrong selector | Use expect(...).toBeVisible() with a role or test ID |
| Server Action test misses the UI update | The action was called directly | Submit the form via Playwright |
| Pending state never appears | The action completes too fast | Slow down the route with page.route() |
| Suspense fallback is not testable | The fetch is too fast | Delay the API with page.route() |
Real-World Examples
1. Synchronous Server Component unit test
render(<Greeting name="Alice" />);
expect(screen.getByRole("heading", { name: "Hello, Alice" })).toBeDefined();
2. Async Server Component E2E test
await page.goto("/user/123");
await expect(page.getByTestId("user-name")).toHaveText("John Doe");
3. Client Component unit test
const handleClick = vi.fn();
await userEvent.click(screen.getByRole("button"));
expect(handleClick).toHaveBeenCalled();
4. Server Action E2E test
await page.getByLabel("Name").fill("John");
await page.getByRole("button").click();
await expect(page.getByText("Success")).toBeVisible();
5. Pending state test
await page.route("/contact", async (route) => { await delay(2000); });
await expect(page.getByRole("button", { name: "Sending..." })).toBeVisible();
6. Suspense fallback test
await expect(page.getByTestId("loading")).toBeVisible();
await expect(page.getByTestId("content")).toBeVisible();
7. Network mocking
await page.route("/api/data", (route) => route.fulfill({ body: JSON.stringify(data) }));
8. Module mocking
vi.mock("@/lib/db", () => ({ db: { query: vi.fn().mockResolvedValue(data) } }));
9. Vitest config
test: { environment: "jsdom" }
10. Playwright config
webServer: { command: "npm run build && npm run start", url: "http://localhost:3000" }
Visual
The Testing Split
┌──────────────────────────────────────────────────────────────┐
│ WHICH TOOL FOR WHICH COMPONENT │
│ │
│ Synchronous Server Component │
│ ┌─────────────────────┐ │
│ │ Vitest + RTL │ render(<Component />) works │
│ │ Unit test │ │
│ └─────────────────────┘ │
│ │
│ Async Server Component │
│ ┌─────────────────────┐ │
│ │ Playwright E2E │ render() receives a Promise │
│ │ │ The test must go through the │
│ │ │ framework's server. │
│ └─────────────────────┘ │
│ │
│ Client Component │
│ ┌─────────────────────┐ │
│ │ Vitest + RTL │ Standard React component test │
│ │ Unit test │ │
│ └─────────────────────┘ │
│ │
│ Server Action │
│ ┌─────────────────────┐ │
│ │ Playwright E2E │ The HTTP layer and UI update │
│ │ │ are part of the test. │
│ └─────────────────────┘ │
└──────────────────────────────────────────────────────────────┘
The Async Boundary
┌──────────────────────────────────────────────────────────────┐
│ WHY ASYNC COMPONENTS CANNOT BE UNIT TESTED │
│ │
│ Synchronous Async │
│ ┌─────────────────────┐ ┌─────────────────────┐ │
│ │ function C() { │ │ async function C() {│ │
│ │ return <div />; │ │ return <div />; │ │
│ │ } │ │ } │ │
│ └──────────┬──────────┘ └──────────┬──────────┘ │
│ │ │ │
│ ▼ ▼ │
│ ┌─────────────────────┐ ┌─────────────────────┐ │
│ │ Returns JSX │ │ Returns Promise<JSX>│ │
│ │ render() works │ │ render() fails │ │
│ └─────────────────────┘ └─────────────────────┘ │
│ │
│ The async keyword changes the return type. │
│ The test renderer is synchronous. │
│ The E2E test is the only option. │
└──────────────────────────────────────────────────────────────┘
The Mocking Levels
┌──────────────────────────────────────────────────────────────┐
│ UNIT VS E2E MOCKING │
│ │
│ Unit test E2E test │
│ ┌─────────────────────┐ ┌─────────────────────┐ │
│ │ vi.mock("@/lib/db") │ │ page.route("/api/*")│ │
│ │ │ │ │ │
│ │ Mocks the module │ │ Mocks the network │ │
│ │ Verifies the logic │ │ Verifies the │ │
│ │ │ │ integration │ │
│ └─────────────────────┘ └─────────────────────┘ │
│ │
│ The unit mock is a module replacement. │
│ The E2E mock is a network interception. │
│ The two verify different things. │
└──────────────────────────────────────────────────────────────┘
Summary
| Item | Value |
|---|---|
| Unit test tool | Vitest + React Testing Library |
| E2E test tool | Playwright |
| Unit-testable | Synchronous Server Components, Client Components |
| Not unit-testable | Async Server Components |
| E2E-testable | Async Server Components, Server Actions, Suspense, pending state |
| Vitest environment | jsdom |
| Unit mock level | Module (vi.mock) |
| E2E mock level | Network (page.route) |
Key takeaways:
- The
asynckeyword is the boundary. A synchronous Server Component can be unit-tested because it returns JSX directly. An async Server Component returns a Promise, and the test renderer cannot await it. The component must be tested through E2E, where the framework’s server executes it . - The official Next.js documentation confirms the limitation. Vitest “currently does not support” async Server Components. The recommendation is E2E tests for async components and unit tests for synchronous components .
- E2E tests exercise the integration. The serialization boundary, the streaming, the Server Action endpoint, and the UI update are invisible to a unit test. The E2E test navigates to the route, waits for the content, and asserts on what the user sees .
- The mocking level distinguishes the test types. A unit test mocks the module (
vi.mock). An E2E test mocks the network (page.route). The module mock verifies the component’s logic; the network mock verifies the framework’s integration with the component . - The pending state and Suspense fallback are E2E-only. Both depend on the lifecycle of an async operation, and both are verified by slowing down the network request and asserting on the intermediate state .
Remember: Testing RSC is not a single strategy. It is a split: unit tests for the synchronous components, E2E tests for the async components and the Server Actions. The split is forced by the async keyword and by the framework’s role in the integration. A unit test of an async Server Component is a test that cannot run, and a E2E test of a synchronous Client Component is a test that runs slower than necessary. The tool must match the component type. The async boundary is the line.
Stop using slow, ad-bloated tool sites! 🤮
🔎 Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)
⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free
🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!