0Pricing
Next.js 15 Fullstack (App Router + Server Actions) · レッスン

APIルートのモックとテスト

JestとMSWでデータベース、ネットワーク呼び出し、外部サービスをモックし、Next.jsのRoute HandlersとServer Actionsを単体でテストします。

「APIルートのモックとテスト」はCoddyKit上の無料Next.js 15 Fullstack (App Router + Server Actions)レッスンです。 これはレッスン4/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはNext.js 15 Fullstack (App Router + Server Actions)学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 Next.js 15 Fullstack (App Router + Server Actions)コースには全4レッスンが含まれています。

このレッスンの一部はまだ翻訳されておらず、英語で表示されています。

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.

よくある質問

「APIルートのモックとテスト」レッスンは無料ですか?

はい。「APIルートのモックとテスト」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、Next.js 15 Fullstack (App Router + Server Actions)コースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 Next.js 15 Fullstack (App Router + Server Actions)コースには全4レッスンが含まれています。

「APIルートのモックとテスト」で何を学びますか?

JestとMSWでデータベース、ネットワーク呼び出し、外部サービスをモックし、Next.jsのRoute HandlersとServer Actionsを単体でテストします。 ブラウザで直接実行するハンズオンコードでNext.js 15 Fullstack (App Router + Server Actions)を演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。

Next.js 15 Fullstack (App Router + Server Actions)を始めるのに経験は必要ですか?

事前経験は必要ありません。CoddyKitのNext.js 15 Fullstack (App Router + Server Actions)は初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン4/4です。

「APIルートのモックとテスト」レッスンにはどのくらい時間がかかりますか?

ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。

このNext.js 15 Fullstack (App Router + Server Actions)レッスンでコードを書いて実行できますか?

はい。すべてのNext.js 15 Fullstack (App Router + Server Actions)レッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。

このコースのすべてのレッスン

  1. コンポーネントのユニットテスト
  2. ページの統合テスト
  3. Playwright/CypressによるE2Eテスト
  4. APIルートのモックとテスト
← Next.js 15 Fullstack (App Router + Server Actions)に戻る