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

API Rotalarını Taklit Etme ve Test Etme

Veritabanını, ağ çağrılarını ve harici hizmetleri Jest ve MSW ile taklit ederek Next.js Rota İşleyicilerini ve Sunucu Eylemlerini yalıtılmış biçimde test edin.

API Rotalarını Taklit Etme ve Test Etme, CoddyKit'te ücretsiz bir Next.js 15 Fullstack (App Router + Server Actions) dersidir. Bu, 4 dersinin 4. dersidir. Aşağıdan dersin tamamını ücretsiz okuyabilir, sonra tarayıcıda yerleşik kod editörü ve 7/24 yapay zeka koçu ile uygulamalı olarak pratik yapabilirsin. Bu, Next.js 15 Fullstack (App Router + Server Actions) öğrenme yolunun bir parçasıdır ve ilerlemeniz web ve CoddyKit uygulaması arasında senkronize olur. Next.js 15 Fullstack (App Router + Server Actions) kursu toplamda 4 dersten oluşur.

Bu dersin bazı bölümleri henüz çevrilmemiş olup İngilizce olarak gösterilmektedir.

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.

Sıkça Sorulan Sorular

“API Rotalarını Taklit Etme ve Test Etme” dersi ücretsiz mi?

Evet — “API Rotalarını Taklit Etme ve Test Etme” dersin tüm metni burada web'de ücretsiz olarak okunabilir. Etkileşimli olarak pratik yapmak (yerleşik kod editörü ve 7/24 yapay zeka koçu) ve Next.js 15 Fullstack (App Router + Server Actions) kursunun geri kalanını açmak için CoddyKit PRO'ya yükselt. Next.js 15 Fullstack (App Router + Server Actions) kursu toplamda 4 dersten oluşur.

“API Rotalarını Taklit Etme ve Test Etme” dersinde ne öğreneceğim?

Veritabanını, ağ çağrılarını ve harici hizmetleri Jest ve MSW ile taklit ederek Next.js Rota İşleyicilerini ve Sunucu Eylemlerini yalıtılmış biçimde test edin. Next.js 15 Fullstack (App Router + Server Actions) ile uygulamalı kodu tarayıcıda doğrudan çalıştırarak pratik yaparsın ve 7/24 yapay zeka koçu dersi çalışırken sorularını yanıtlar.

Next.js 15 Fullstack (App Router + Server Actions) öğrenmeye başlamak için deneyim gerekli mi?

Önceden deneyim gerekmez. CoddyKit'te Next.js 15 Fullstack (App Router + Server Actions), başlangıçtan ileri seviyeye kadar yapılandırıldığı için buradan başlayabilir veya başından başlayıp kendi hızında ilerleme yapabilirsin. Bu, 4 dersinin 4. dersidir.

“API Rotalarını Taklit Etme ve Test Etme” dersi ne kadar sürer?

Çoğu CoddyKit dersi yaklaşık 5–10 dakika sürer. Her biri kısa ve etkileşimli olduğu için sabit ilerleme yaparsın ve web ile uygulama arasında tam olarak bıraktığın yerden devam edebilirsin.

Bu Next.js 15 Fullstack (App Router + Server Actions) dersinde kod yazıp çalıştırabilir miyim?

Evet. Her Next.js 15 Fullstack (App Router + Server Actions) dersi yerleşik bir kod editörü içerir, bu sayede tarayıcıda gerçek kod yazıp çalıştırabilir ve anlık yapay zeka geri bildirimi alırsın — yerel kurulum gerekli değildir.

Bu kursun tüm dersleri

  1. Bileşenleri Birim Sınamasından Geçirme
  2. Sayfaları Tümleştirme Sınamasından Geçirme
  3. Playwright/Cypress ile Uçtan Uca Test
  4. API Rotalarını Taklit Etme ve Test Etme
← Next.js 15 Fullstack (App Router + Server Actions) Sayfasına Dön