0Pricing
Next.js 15 Fullstack Web Apps · Lesson

Mocking and Testing Server Components

Test async Server Components, Server Actions, and route handlers by mocking data layers and network calls so your fullstack Next.js tests stay fast and reliable.

Mocking and Testing Server Components is a free Next.js 15 Fullstack Web Apps lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Next.js 15 Fullstack Web Apps learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

The Server Component Challenge

Server Components are async and run on the server, so classic client-render test tools do not fit perfectly. The key is to test their data dependencies in isolation and test the rendered output separately.

Separate Logic from Rendering

Extract data-fetching and business logic into plain functions. Pure functions are trivial to unit test without rendering anything.

export function formatPrice(cents) {
  return '$' + (cents / 100).toFixed(2);
}

Testing a Pure Helper

A pure helper is testable anywhere with no mocks at all.

function formatPrice(cents) {
  return '$' + (cents / 100).toFixed(2);
}
console.log(formatPrice(1999) === '$19.99');
console.log(formatPrice(500) === '$5.00');

Mocking the Data Layer

Server Components usually call a repository or ORM. Mock that module so tests do not hit a real database.

import { vi } from 'vitest';
import * as db from '@/lib/db';

vi.spyOn(db, 'getUser').mockResolvedValue({ id: 1, name: 'Ada' });

Rendering an Async Server Component

Because the component is async, you can await it to get its element tree, then assert on it with your render utility.

import { render, screen } from '@testing-library/react';
import Profile from '@/app/profile/page';

it('shows the name', async () => {
  render(await Profile());
  expect(screen.getByText('Ada')).toBeInTheDocument();
});

Mocking fetch with MSW

When a component fetches from an external API, intercept the request with Mock Service Worker (MSW) instead of stubbing fetch by hand.

import { http, HttpResponse } from 'msw';

export const handlers = [
  http.get('https://api.example.com/user', () =>
    HttpResponse.json({ name: 'Ada' })
  ),
];

Testing Server Actions

Server Actions are async functions. Call them directly with mocked dependencies and assert on side effects and return values.

import { createTodo } from '@/app/actions';
import * as db from '@/lib/db';

it('creates a todo', async () => {
  const spy = vi.spyOn(db, 'insertTodo').mockResolvedValue({ id: 1 });
  await createTodo('Write tests');
  expect(spy).toHaveBeenCalledWith('Write tests');
});

Mocking revalidatePath

Actions often call revalidatePath. Mock next/cache so the call does not throw outside a request scope, and assert it was invoked.

vi.mock('next/cache', () => ({
  revalidatePath: vi.fn(),
}));

Testing Route Handlers

Route handlers take a Request and return a Response. Build a request, call the handler, and inspect the response.

import { POST } from '@/app/api/todos/route';

it('returns 400 on empty body', async () => {
  const req = new Request('http://t/api/todos', { method: 'POST', body: '{}' });
  const res = await POST(req);
  expect(res.status).toBe(400);
});

Keep Tests Deterministic

Avoid flaky tests:

  • Reset mocks between tests (vi.clearAllMocks()).
  • Freeze time when testing dates.
  • Never call real networks or databases.

The Testing Pyramid

Balance your suite: many fast unit tests for logic, fewer integration tests for components plus data, and a small set of E2E tests (Playwright) for critical flows.

Quick Check

What is the recommended way to test an async Server Component that calls your ORM?

Recap

You learned to test fullstack Next.js code:

  • Separate pure logic for easy unit tests.
  • Mock the data layer and use MSW for network calls.
  • Await async Server Components; call Server Actions and route handlers directly.
  • Keep tests deterministic and follow the testing pyramid.

Frequently asked questions

Is the “Mocking and Testing Server Components” lesson free?

Yes — the full text of “Mocking and Testing Server Components” is free to read here on the web, and the Next.js 15 Fullstack Web Apps course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Next.js 15 Fullstack Web Apps course, upgrade to CoddyKit PRO.

What will I learn in “Mocking and Testing Server Components”?

Test async Server Components, Server Actions, and route handlers by mocking data layers and network calls so your fullstack Next.js tests stay fast and reliable. You practise Next.js 15 Fullstack Web Apps with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Next.js 15 Fullstack Web Apps?

No prior experience is required. Next.js 15 Fullstack Web Apps on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Mocking and Testing Server Components” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Next.js 15 Fullstack Web Apps lesson?

Yes. Every Next.js 15 Fullstack Web Apps lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Unit and Integration Testing
  2. End-to-End Testing with Playwright
  3. Monorepos and Micro-frontends
  4. Mocking and Testing Server Components
← Back to Next.js 15 Fullstack Web Apps