API-Routen mocken und testen
Testen Sie Next.js Route Handlers und Server Actions isoliert, indem Sie Datenbank, Netzwerkaufrufe und externe Dienste mit Jest und MSW mocken
API-Routen mocken und testen ist eine kostenlose Next.js 15 Fullstack (App Router + Server Actions)-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 (App Router + Server Actions)-Lernpfads, und dein Fortschritt wird über Web und CoddyKit-App synchronisiert. Der Next.js 15 Fullstack (App Router + Server Actions)-Kurs umfasst insgesamt 4 Lektionen.
Teile dieser Lektion wurden noch nicht übersetzt und werden auf Englisch angezeigt.
Why Mock?
Tests should be fast, deterministic, and isolated. Mocking replaces slow or external dependencies — databases, payment APIs, email senders — with controllable stand-ins so a single failure does not break unrelated tests.
What to Mock
Good mock targets in a Next.js app:
- The database client (Prisma)
- External HTTP calls (Stripe, OpenAI)
- Auth/session helpers
Keep the route's own logic real so you actually test it.
A Simple Route Handler
Here is a route we want to test. It reads a query param and returns JSON.
// app/api/user/route.ts
import { prisma } from '@/lib/prisma';
export async function GET(req: Request) {
const users = await prisma.user.findMany();
return Response.json(users);
}Mocking Prisma with Jest
jest.mock replaces a module. Mock the Prisma module so calls return fixed data instead of hitting a real database.
jest.mock('@/lib/prisma', () => ({
prisma: {
user: { findMany: jest.fn() }
}
}));Setting Return Values
In each test, tell the mock what to resolve with using mockResolvedValue. This drives the route down a specific path.
import { prisma } from '@/lib/prisma';
(prisma.user.findMany as jest.Mock).mockResolvedValue([
{ id: 1, name: 'Ada' }
]);Invoking the Handler
Route Handlers are plain functions. Call them directly with a Request and assert on the returned Response.
import { GET } from '@/app/api/user/route';
const res = await GET(new Request('http://test/api/user'));
const data = await res.json();
expect(data[0].name).toBe('Ada');Asserting Call Behavior
Verify the mock was used correctly with matchers like toHaveBeenCalledWith. This confirms your route passes the right arguments.
expect(prisma.user.findMany).toHaveBeenCalledTimes(1);Mocking External HTTP with MSW
For outbound calls, MSW (Mock Service Worker) intercepts requests at the network layer. Define handlers that return canned responses.
import { http, HttpResponse } from 'msw';
export const handlers = [
http.get('https://api.stripe.com/v1/charges', () =>
HttpResponse.json({ amount: 500 })
)
];Starting the Mock Server
Boot the MSW server in your test setup so every test runs against the mocked network. Reset handlers between tests for isolation.
import { setupServer } from 'msw/node';
const server = setupServer(...handlers);
beforeAll(() => server.listen());
afterEach(() => server.resetHandlers());
afterAll(() => server.close());Testing Error Paths
Make mocks reject or return errors to test how your route handles failures, ensuring it returns the right status code.
(prisma.user.findMany as jest.Mock).mockRejectedValue(new Error('db down'));
const res = await GET(new Request('http://test/api/user'));
expect(res.status).toBe(500);Best Practices
Keep mocked tests trustworthy:
- Mock the edges, keep logic real
- Reset mocks between tests
- Cover success and error paths
- Use MSW for realistic network mocking
Quick Check
Test your mocking knowledge.
Recap
You learned to test routes in isolation:
- Mock the Prisma client with
jest.mockandmockResolvedValue - Call Route Handlers directly and assert on the
Response - Intercept outbound HTTP with MSW
- Cover error paths by making mocks reject
Your API tests are now fast and reliable.
Häufig gestellte Fragen
Ist die Lektion „API-Routen mocken und testen“ kostenlos?
Ja — der vollständige Text von „API-Routen mocken und testen“ 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 (App Router + Server Actions)-Kurses freizuschalten, upgrade auf CoddyKit PRO. Der Next.js 15 Fullstack (App Router + Server Actions)-Kurs umfasst insgesamt 4 Lektionen.
Was lerne ich in „API-Routen mocken und testen“?
Testen Sie Next.js Route Handlers und Server Actions isoliert, indem Sie Datenbank, Netzwerkaufrufe und externe Dienste mit Jest und MSW mocken Du übst Next.js 15 Fullstack (App Router + Server Actions) 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 (App Router + Server Actions) zu starten?
Keine Vorkenntnisse erforderlich. Next.js 15 Fullstack (App Router + Server Actions) 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 „API-Routen mocken und testen“?
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 (App Router + Server Actions)-Lektion Code schreiben und ausführen?
Ja. Jede Next.js 15 Fullstack (App Router + Server Actions)-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
- Komponenten mit Unit-Tests testen
- Seiten mit Integrationstests testen
- End-to-End-Tests mit Playwright/Cypress
- API-Routen mocken und testen