0Pricing
Next.js 15 Fullstack (App Router + Server Actions) · Pelajaran

Membuat Mock dan Menguji Rute API

Uji Route Handlers dan Server Actions Next.js secara terisolasi dengan membuat mock untuk basis data, pemanggilan jaringan, dan layanan eksternal menggunakan Jest dan MSW.

Membuat Mock dan Menguji Rute API adalah pelajaran Next.js 15 Fullstack (App Router + Server Actions) gratis di CoddyKit. Ini adalah pelajaran 4 dari 4. Kamu bisa membaca pelajaran lengkapnya di bawah secara gratis — lalu praktikkan langsung di browser dengan editor kode bawaan dan tutor AI 24/7. Ini adalah bagian dari jalur belajar Next.js 15 Fullstack (App Router + Server Actions), dan progresmu tersinkronisasi di web dan aplikasi CoddyKit. Kursus Next.js 15 Fullstack (App Router + Server Actions) mencakup 4 pelajaran total.

Bagian dari pelajaran ini belum diterjemahkan dan ditampilkan dalam bahasa Inggris.

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.mock and mockResolvedValue
  • 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.

Pertanyaan yang Sering Diajukan

Apakah pelajaran “Membuat Mock dan Menguji Rute API” gratis?

Ya — teks lengkap “Membuat Mock dan Menguji Rute API” gratis dibaca di sini di web. Untuk praktiknya secara interaktif (editor kode bawaan dan tutor AI 24/7) dan buka sisa kursus Next.js 15 Fullstack (App Router + Server Actions), upgrade ke CoddyKit PRO. Kursus Next.js 15 Fullstack (App Router + Server Actions) mencakup 4 pelajaran total.

Apa yang akan aku pelajari di “Membuat Mock dan Menguji Rute API”?

Uji Route Handlers dan Server Actions Next.js secara terisolasi dengan membuat mock untuk basis data, pemanggilan jaringan, dan layanan eksternal menggunakan Jest dan MSW. Kamu berlatih Next.js 15 Fullstack (App Router + Server Actions) dengan kode praktik yang langsung kamu jalankan di browser, dan tutor AI 24/7 menjawab pertanyaanmu saat kamu mengerjakan pelajaran ini.

Apakah aku perlu pengalaman untuk memulai Next.js 15 Fullstack (App Router + Server Actions)?

Tidak diperlukan pengalaman sebelumnya. Next.js 15 Fullstack (App Router + Server Actions) di CoddyKit dirancang untuk pemula hingga pelajar tingkat lanjut, jadi kamu bisa memulai di sini atau dari awal dan belajar sesuai kecepatan kamu sendiri. Ini adalah pelajaran 4 dari 4.

Berapa lama pelajaran “Membuat Mock dan Menguji Rute API” memakan waktu?

Sebagian besar pelajaran CoddyKit memakan waktu sekitar 5–10 menit. Setiap pelajaran ringkas dan interaktif, jadi kamu membuat kemajuan stabil dan melanjutkan dari tempat kamu tinggalkan di web dan aplikasi.

Bisakah aku menulis dan menjalankan kode dalam pelajaran Next.js 15 Fullstack (App Router + Server Actions) ini?

Ya. Setiap pelajaran Next.js 15 Fullstack (App Router + Server Actions) menyertakan editor kode bawaan, jadi kamu menulis dan menjalankan kode nyata langsung di browser dan mendapatkan umpan balik AI instan — tidak diperlukan penyiapan lokal.

Semua pelajaran dalam kursus ini

  1. Pengujian Unit Komponen
  2. Pengujian Integrasi Halaman
  3. Pengujian E2E dengan Playwright/Cypress
  4. Membuat Mock dan Menguji Rute API
← Kembali ke Next.js 15 Fullstack (App Router + Server Actions)