0Pricing
Next.js 15 Fullstack Web Apps · レッスン

Server Componentsのモックとテスト

データ層とネットワーク呼び出しをモックし、非同期Server Components、Server Actions、ルートハンドラーをテストします。フルスタックNext.jsテストを高速かつ信頼性の高いものにします。

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

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

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.

よくある質問

「Server Componentsのモックとテスト」レッスンは無料ですか?

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

「Server Componentsのモックとテスト」で何を学びますか?

データ層とネットワーク呼び出しをモックし、非同期Server Components、Server Actions、ルートハンドラーをテストします。フルスタックNext.jsテストを高速かつ信頼性の高いものにします。 ブラウザで直接実行するハンズオンコードでNext.js 15 Fullstack Web Appsを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。

Next.js 15 Fullstack Web Appsを始めるのに経験は必要ですか?

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

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

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

このNext.js 15 Fullstack Web Appsレッスンでコードを書いて実行できますか?

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

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

  1. ユニットテストと統合テスト
  2. PlaywrightによるE2Eテスト
  3. モノレポとマイクロフロントエンド
  4. Server Componentsのモックとテスト
← Next.js 15 Fullstack Web Appsに戻る