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

ユニットテストと統合テスト

JestとReact Testing Libraryを使って、ReactコンポーネントとNext.jsの関数に対する効果的なユニットテストおよび統合テストを作成します。

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

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

Why We Test Our Code

Welcome! In modern web development, especially with complex applications built with Next.js, ensuring your code works as expected is crucial. This is where testing comes in.

  • Reliability: Tests prevent bugs and regressions.
  • Maintainability: Well-tested code is easier to refactor and update.
  • Confidence: You can deploy new features with greater assurance.

We'll focus on Unit Tests (small, isolated parts) and Integration Tests (how parts work together).

Setting Up Jest & RTL

Jest is a popular JavaScript testing framework, and React Testing Library (RTL) is a set of utilities for testing React components. Together, they form a powerful duo for Next.js apps.

First, install the necessary packages:

npm install --save-dev jest @testing-library/react @testing-library/jest-dom jest-environment-jsdom

Your First Unit Test (Function)

A unit test checks a small, isolated piece of code, like a single function. Let's create a simple utility function and then write a test for it.

Here's our utility:

// utils/math.js
function add(a, b) {
  return a + b;
}

// This block makes the file directly runnable via Node.js
if (typeof require !== 'undefined' && require.main === module) {
  console.log("Running add(5, 3):", add(5, 3)); // Expected: 8
  console.log("Running add(10, -2):", add(10, -2)); // Expected: 8
}

Testing the 'add' Function

Now, let's write a test for our add function. Jest uses describe to group tests and test (or it) for individual test cases. expect is used for assertions.

Save this in utils/math.test.js:

// utils/math.test.js
import { add } from './math';

describe('add function', () => {
  test('should correctly add two positive numbers', () => {
    expect(add(1, 2)).toBe(3);
  });

  test('should handle negative numbers', () => {
    expect(add(5, -3)).toBe(2);
  });
});

// To run tests: npx jest

Introducing React Testing Library

React Testing Library (RTL) encourages testing components in a way that mimics how users interact with them. Instead of checking internal state, you query the DOM for elements a user would see or interact with.

  • render: Mounts a React component into a virtual DOM.
  • screen: Provides methods to query the rendered DOM (e.g., getByText, getByRole).
  • @testing-library/jest-dom: Adds custom matchers like toBeInTheDocument.

Testing a Simple React Component

Let's test a basic button component. We'll ensure it renders with the correct text.

First, the component (components/Button.jsx):

// components/Button.jsx
export default function Button({ label, onClick }) {
  return (
    <button onClick={onClick}>
      {label}
    </button>
  );
}

Testing Component Rendering

Now, the test for our Button component. We use render to put it on the screen and screen.getByText to find it, then toBeInTheDocument to confirm its presence.

Save this as components/Button.test.jsx:

// components/Button.test.jsx
import { render, screen } from '@testing-library/react';
import Button from './Button';

describe('Button component', () => {
  test('renders with the correct label', () => {
    render(<Button label="Click Me" />);
    const buttonElement = screen.getByText(/Click Me/i);
    expect(buttonElement).toBeInTheDocument();
  });
});

Simulating User Interactions

Beyond just rendering, we need to test how components respond to user actions. RTL's fireEvent (or userEvent for more realistic interactions) helps simulate clicks, input changes, etc.

We can check if a function passed via props is called.

// components/Button.test.jsx (continued)
import { render, screen, fireEvent } from '@testing-library/react';
import Button from './Button';

describe('Button component interactions', () => {
  test('calls the onClick handler when clicked', () => {
    const handleClick = jest.fn(); // Jest mock function
    render(<Button label="Click Me" onClick={handleClick} />);
    const buttonElement = screen.getByText(/Click Me/i);
    fireEvent.click(buttonElement);
    expect(handleClick).toHaveBeenCalledTimes(1);
  });
});

Integration: Testing Route Handlers

Next.js Route Handlers (API routes in the App Router) are server-side functions. We can test them by directly importing and calling their HTTP methods (like GET, POST) and mocking Next.js's request/response objects.

Here's an example:

// app/api/hello/route.js
import { NextResponse } from 'next/server';

export async function GET() {
  return NextResponse.json({ message: 'Hello from API!' }, { status: 200 });
}

// app/api/hello/route.test.js
import { GET } from './route';

describe('GET /api/hello', () => {
  test('should return a greeting message with status 200', async () => {
    // No need to mock NextRequest/NextResponse directly for simple cases
    // as NextResponse.json returns a standard Response object.
    const response = await GET();
    const json = await response.json();

    expect(response.status).toBe(200);
    expect(json.message).toBe('Hello from API!');
  });
});

Best Practices for Effective Tests

To write useful and maintainable tests:

  • Test user behavior: Focus on what the user sees and does, not internal component state.
  • Keep tests focused: Each test should ideally check one thing.
  • Make tests fast: Slow tests discourage running them often.
  • Readability: Write clear tests that are easy to understand.
  • Mock dependencies: Use jest.mock() or jest.fn() to isolate units and prevent external factors from affecting tests.

Quick Check

Which of the following statements about testing in Next.js with Jest and React Testing Library is TRUE?

Recap: Unit & Integration Testing

Great job! You've learned the fundamentals of unit and integration testing in Next.js:

  • Jest is your testing framework.
  • React Testing Library helps test components like a user would.
  • Unit tests verify small, isolated code units.
  • Integration tests check how different parts (like components and APIs) work together.
  • You can test functions, React components, and Next.js Route Handlers.
  • Best practices include focusing on user behavior and mocking dependencies.

Next up, we'll explore End-to-End testing for full application flows!

よくある質問

「ユニットテストと統合テスト」レッスンは無料ですか?

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

「ユニットテストと統合テスト」で何を学びますか?

JestとReact Testing Libraryを使って、ReactコンポーネントとNext.jsの関数に対する効果的なユニットテストおよび統合テストを作成します。 ブラウザで直接実行するハンズオンコードでNext.js 15 Fullstack Web Appsを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。

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

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

「ユニットテストと統合テスト」レッスンにはどのくらい時間がかかりますか?

ほとんどの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に戻る