0Pricing
Next.js 15 Fullstack Web Apps · Lektion

Mocking und Testen von Server Components

Testen Sie asynchrone Server Components, Server Actions und Route Handlers, indem Sie Datenschichten und Netzwerkaufrufe mocken, damit Ihre Fullstack-Next.js-Tests schnell und zuverlässig bleiben.

Mocking und Testen von Server Components ist eine kostenlose Next.js 15 Fullstack Web Apps-Lektion auf CoddyKit. Dies ist Lektion 4 von 4. Du kannst die komplette Lektion unten kostenlos lesen – dann übst du sie direkt im Browser mit einem integrierten Code-Editor und einem KI-Tutor rund um die Uhr. Sie ist Teil des Next.js 15 Fullstack Web Apps-Lernpfads, und dein Fortschritt wird über Web und CoddyKit-App synchronisiert. Der Next.js 15 Fullstack Web Apps-Kurs umfasst insgesamt 4 Lektionen.

Teile dieser Lektion wurden noch nicht übersetzt und werden auf Englisch angezeigt.

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.

Häufig gestellte Fragen

Ist die Lektion „Mocking und Testen von Server Components“ kostenlos?

Ja — der vollständige Text von „Mocking und Testen von Server Components“ ist hier im Web kostenlos zu lesen. Um sie interaktiv zu üben (integrierter Code-Editor und 24/7 KI-Tutor) und den Rest des Next.js 15 Fullstack Web Apps-Kurses freizuschalten, upgrade auf CoddyKit PRO. Der Next.js 15 Fullstack Web Apps-Kurs umfasst insgesamt 4 Lektionen.

Was lerne ich in „Mocking und Testen von Server Components“?

Testen Sie asynchrone Server Components, Server Actions und Route Handlers, indem Sie Datenschichten und Netzwerkaufrufe mocken, damit Ihre Fullstack-Next.js-Tests schnell und zuverlässig bleiben. Du übst Next.js 15 Fullstack Web Apps mit praktischem Code, den du direkt im Browser ausführst, und ein 24/7 KI-Tutor beantwortet deine Fragen während du die Lektion bearbeitest.

Brauche ich Erfahrung, um Next.js 15 Fullstack Web Apps zu starten?

Keine Vorkenntnisse erforderlich. Next.js 15 Fullstack Web Apps auf CoddyKit ist für Anfänger bis fortgeschrittene Lernende strukturiert, sodass du hier starten oder von Anfang an beginnen und in deinem eigenen Tempo voranschreiten kannst. Dies ist Lektion 4 von 4.

Wie lange dauert die Lektion „Mocking und Testen von Server Components“?

Die meisten CoddyKit-Lektionen dauern etwa 5–10 Minuten. Jede ist kompakt und interaktiv, sodass du stetig Fortschritte machst und genau dort weitermachst, wo du aufgehört hast – im Web und in der App.

Kann ich in dieser Next.js 15 Fullstack Web Apps-Lektion Code schreiben und ausführen?

Ja. Jede Next.js 15 Fullstack Web Apps-Lektion enthält einen integrierten Code-Editor, sodass du echten Code direkt in deinem Browser schreibst und ausführst und sofort KI-Feedback erhältst — ohne lokale Einrichtung erforderlich.

Alle Lektionen in diesem Kurs

  1. Unit- und Integrationstests
  2. End-to-End-Tests mit Playwright
  3. Monorepos und Micro-frontends
  4. Mocking und Testen von Server Components
← Zurück zu Next.js 15 Fullstack Web Apps