jpskill.com
🛠️ 開発・MCP コミュニティ

jest

Jestは、Meta社が開発したJavaScript/TypeScript向けのテストフレームワークで、設定不要でユニットテストからスナップショットテストまで幅広く対応し、コードカバレッジやモック機能も備え、ReactやNode.jsなど様々な環境でテストを効率化するSkill。

📜 元の英語説明(参考)

Jest is a comprehensive JavaScript testing framework built by Meta, designed for zero-configuration testing of JavaScript and TypeScript applications. It provides a complete ecosystem for unit testing, integration testing, and snapshot testing with built-in code coverage, mocking capabilities, and parallel test execution. Jest works seamlessly with React, Node.js, Angular, Vue, and virtually any JavaScript project, making it the most widely adopted testing framework in the ecosystem.

🇯🇵 日本人クリエイター向け解説

一言でいうと

Jestは、Meta社が開発したJavaScript/TypeScript向けのテストフレームワークで、設定不要でユニットテストからスナップショットテストまで幅広く対応し、コードカバレッジやモック機能も備え、ReactやNode.jsなど様々な環境でテストを効率化するSkill。

※ jpskill.com 編集部が日本のビジネス現場向けに補足した解説です。Skill本体の挙動とは独立した参考情報です。

⚡ おすすめ: コマンド1行でインストール(60秒)

下記のコマンドをコピーしてターミナル(Mac/Linux)または PowerShell(Windows)に貼り付けてください。 ダウンロード → 解凍 → 配置まで全自動。

🍎 Mac / 🐧 Linux
mkdir -p ~/.claude/skills && cd ~/.claude/skills && curl -L -o jest.zip https://jpskill.com/download/15022.zip && unzip -o jest.zip && rm jest.zip
🪟 Windows (PowerShell)
$d = "$env:USERPROFILE\.claude\skills"; ni -Force -ItemType Directory $d | Out-Null; iwr https://jpskill.com/download/15022.zip -OutFile "$d\jest.zip"; Expand-Archive "$d\jest.zip" -DestinationPath $d -Force; ri "$d\jest.zip"

完了後、Claude Code を再起動 → 普通に「動画プロンプト作って」のように話しかけるだけで自動発動します。

💾 手動でダウンロードしたい(コマンドが難しい人向け)
  1. 1. 下の青いボタンを押して jest.zip をダウンロード
  2. 2. ZIPファイルをダブルクリックで解凍 → jest フォルダができる
  3. 3. そのフォルダを C:\Users\あなたの名前\.claude\skills\(Win)または ~/.claude/skills/(Mac)へ移動
  4. 4. Claude Code を再起動

⚠️ ダウンロード・利用は自己責任でお願いします。当サイトは内容・動作・安全性について責任を負いません。

🎯 このSkillでできること

下記の説明文を読むと、このSkillがあなたに何をしてくれるかが分かります。Claudeにこの分野の依頼をすると、自動で発動します。

📦 インストール方法 (3ステップ)

  1. 1. 上の「ダウンロード」ボタンを押して .skill ファイルを取得
  2. 2. ファイル名の拡張子を .skill から .zip に変えて展開(macは自動展開可)
  3. 3. 展開してできたフォルダを、ホームフォルダの .claude/skills/ に置く
    • · macOS / Linux: ~/.claude/skills/
    • · Windows: %USERPROFILE%\.claude\skills\

Claude Code を再起動すれば完了。「このSkillを使って…」と話しかけなくても、関連する依頼で自動的に呼び出されます。

詳しい使い方ガイドを見る →
最終更新
2026-05-18
取得日時
2026-05-18
同梱ファイル
1

📖 Skill本文(日本語訳)

※ 原文(英語/中国語)を Gemini で日本語化したものです。Claude 自身は原文を読みます。誤訳がある場合は原文をご確認ください。

Jest — JavaScript テストフレームワーク

Jest は、JavaScript のテストに対する「至れり尽くせり」のアプローチを提供します。他のフレームワークでは、テストランナー、アサーションライブラリ、モックツールを個別に組み立てる必要がありますが、Jest はこれらすべてを単一のパッケージで提供します。インストールして、テストを記述し、実行するだけです。そのシンプルさこそが、Jest が JavaScript のテスト環境を席巻している理由です。

このスキルでは、Jest の基本原則から順を追って説明します。アサーションの記述、依存関係のモック、非同期コードのテスト、カバレッジレポートの生成、そしてすべてを CI パイプラインに統合する方法を学びます。

Jest のインストールと設定

Jest のセットアップは、常にインストールと設定ファイルから始まります。Jest はプレーンな JavaScript ではすぐに動作しますが、ほとんどの実際のプロジェクトでは、TypeScript、JSX、またはモジュール解決のために少し設定が必要です。

# Jest とその TypeScript サポートをインストール
npm install --save-dev jest ts-jest @types/jest

インストールしたら、プロジェクトのルートに設定ファイルを作成します。jest.config.ts 形式を使用すると、設定オプションの型チェックが可能です。

// jest.config.ts — TypeScript プロジェクトのルート Jest 設定
import type { Config } from 'jest';

const config: Config = {
  preset: 'ts-jest',
  testEnvironment: 'node',
  roots: ['<rootDir>/src'],
  testMatch: ['**/__tests__/**/*.test.ts', '**/*.spec.ts'],
  collectCoverageFrom: [
    'src/**/*.ts',
    '!src/**/*.d.ts',
    '!src/**/index.ts',
  ],
  coverageThresholds: {
    global: {
      branches: 80,
      functions: 80,
      lines: 80,
      statements: 80,
    },
  },
  moduleNameMapper: {
    '^@/(.*)$': '<rootDir>/src/$1',
  },
};

export default config;

チームが一貫したコマンドを使用できるように、package.json にテストスクリプトを追加します。

// package.json — Jest コマンドの scripts セクション
{
  "scripts": {
    "test": "jest",
    "test:watch": "jest --watch",
    "test:coverage": "jest --coverage",
    "test:ci": "jest --ci --coverage --reporters=default --reporters=jest-junit"
  }
}

アサーションの記述

Jest の expect API は、値をアサートするための Fluent インターフェースを提供します。すべてのテストは同じパターンに従います。データを準備し、それに対してアクションを実行し、結果をアサートします。

// src/__tests__/math.test.ts — Jest マッチャーを使用した基本的なアサーションパターン
describe('arithmetic operations', () => {
  test('adds two numbers correctly', () => {
    const result = add(2, 3);
    expect(result).toBe(5);
  });

  test('returns an object with computed properties', () => {
    const result = createUser('Alice', 30);

    // toEqual は参照をチェックする toBe とは異なり、深い等価性を実行します
    expect(result).toEqual({
      name: 'Alice',
      age: 30,
      id: expect.any(String),
    });
  });

  test('array contains specific items', () => {
    const fruits = getFruits();

    expect(fruits).toContain('apple');
    expect(fruits).toHaveLength(3);
    expect(fruits).toEqual(expect.arrayContaining(['apple', 'banana']));
  });

  test('function throws on invalid input', () => {
    expect(() => divide(10, 0)).toThrow('Cannot divide by zero');
    expect(() => divide(10, 0)).toThrow(ArithmeticError);
  });
});

モック関数とモジュールモック

モックは、Jest が真価を発揮する部分です。任意の関数、モジュール、またはタイマーを制御可能な代替に置き換えることができます。これにより、ユニットを完全に分離してテストできます。

// src/__tests__/userService.test.ts — 外部依存関係のモック
import { UserService } from '../userService';
import { database } from '../database';

// データベースモジュール全体を自動モックバージョンに置き換えます
jest.mock('../database');

const mockedDb = jest.mocked(database);

describe('UserService', () => {
  beforeEach(() => {
    // テスト間で全てのモック状態をクリアします
    jest.clearAllMocks();
  });

  test('fetches a user by ID from the database', async () => {
    const mockUser = { id: '1', name: 'Alice', email: 'alice@example.com' };
    mockedDb.findById.mockResolvedValue(mockUser);

    const service = new UserService();
    const user = await service.getUser('1');

    expect(mockedDb.findById).toHaveBeenCalledWith('1');
    expect(mockedDb.findById).toHaveBeenCalledTimes(1);
    expect(user).toEqual(mockUser);
  });

  test('throws when user is not found', async () => {
    mockedDb.findById.mockResolvedValue(null);

    const service = new UserService();

    await expect(service.getUser('999')).rejects.toThrow('User not found');
  });
});

より細かく制御するには、jest.fn() を使用して、コールバックまたはメソッド実装として渡すことができるスタンドアロンのモック関数を作成します。

// src/__tests__/eventHandler.test.ts — コールバックテストに jest.fn() を使用する
describe('event handler', () => {
  test('calls the callback with processed data', () => {
    const callback = jest.fn();

    processEvents([{ type: 'click', target: 'button' }], callback);

    expect(callback).toHaveBeenCalledTimes(1);
    expect(callback).toHaveBeenCalledWith({
      type: 'click',
      target: 'button',
      timestamp: expect.any(Number),
    });
  });

  test('mock implementation controls return value', () => {
    const getPrice = jest.fn()
      .mockReturnValueOnce(10.99)
      .mockReturnValueOnce(24.99)
      .mockReturnValue(0);

    expect(getPrice()).toBe(10.99);
    expect(getPrice()).toBe(24.99);
    expect(getPrice()).toBe(0);
  });
});

非同期コードのテスト

現代の JavaScript は非常に非同期です。Jest は、promises、async/await、およびコールバックを同じように簡単に処理します。重要なのは、常に非同期操作を返すか、await することです。そうすることで、Jest はテストがいつ完了したかを知ることができます。

// src/__tests__/api.test.ts — 非同期操作をテストするためのパターン
describe('API client', () => {
  test('fetches data with async/await', async () => {
    const data = await fetchUserProfile('alice');

    expect(data.username).toBe('alice');
    expect(data.posts).toBeInstanceOf(Array);
  });

  test('handles API errors gracefully', async () => {
    // Mock fetch t
📜 原文 SKILL.md(Claudeが読む英語/中国語)を展開

Jest — JavaScript Testing Framework

Jest brings a batteries-included approach to JavaScript testing. Where other frameworks require you to assemble a test runner, assertion library, and mocking tool separately, Jest ships all three in a single package. You install it, write a test, and run it. That simplicity is why it dominates the JavaScript testing landscape.

This skill walks you through Jest from first principles — writing assertions, mocking dependencies, testing asynchronous code, generating coverage reports, and integrating everything into a CI pipeline.

Installing and Configuring Jest

Every Jest setup begins with installation and a configuration file. Jest works out of the box for plain JavaScript, but most real projects need a bit of configuration for TypeScript, JSX, or module resolution.

# Install Jest and its TypeScript support
npm install --save-dev jest ts-jest @types/jest

Once installed, create a configuration file at the root of your project. The jest.config.ts format gives you type checking on your configuration options.

// jest.config.ts — Root Jest configuration for a TypeScript project
import type { Config } from 'jest';

const config: Config = {
  preset: 'ts-jest',
  testEnvironment: 'node',
  roots: ['<rootDir>/src'],
  testMatch: ['**/__tests__/**/*.test.ts', '**/*.spec.ts'],
  collectCoverageFrom: [
    'src/**/*.ts',
    '!src/**/*.d.ts',
    '!src/**/index.ts',
  ],
  coverageThresholds: {
    global: {
      branches: 80,
      functions: 80,
      lines: 80,
      statements: 80,
    },
  },
  moduleNameMapper: {
    '^@/(.*)$': '<rootDir>/src/$1',
  },
};

export default config;

Add test scripts to your package.json so your team has consistent commands.

// package.json — Scripts section for Jest commands
{
  "scripts": {
    "test": "jest",
    "test:watch": "jest --watch",
    "test:coverage": "jest --coverage",
    "test:ci": "jest --ci --coverage --reporters=default --reporters=jest-junit"
  }
}

Writing Assertions

Jest's expect API gives you a fluent interface for asserting values. Every test follows the same pattern: arrange your data, act on it, then assert the result.

// src/__tests__/math.test.ts — Basic assertion patterns with Jest matchers
describe('arithmetic operations', () => {
  test('adds two numbers correctly', () => {
    const result = add(2, 3);
    expect(result).toBe(5);
  });

  test('returns an object with computed properties', () => {
    const result = createUser('Alice', 30);

    // toEqual performs deep equality, unlike toBe which checks reference
    expect(result).toEqual({
      name: 'Alice',
      age: 30,
      id: expect.any(String),
    });
  });

  test('array contains specific items', () => {
    const fruits = getFruits();

    expect(fruits).toContain('apple');
    expect(fruits).toHaveLength(3);
    expect(fruits).toEqual(expect.arrayContaining(['apple', 'banana']));
  });

  test('function throws on invalid input', () => {
    expect(() => divide(10, 0)).toThrow('Cannot divide by zero');
    expect(() => divide(10, 0)).toThrow(ArithmeticError);
  });
});

Mock Functions and Module Mocking

Mocking is where Jest truly shines. You can replace any function, module, or timer with a controllable substitute. This lets you test units in complete isolation.

// src/__tests__/userService.test.ts — Mocking external dependencies
import { UserService } from '../userService';
import { database } from '../database';

// Replace the entire database module with auto-mocked version
jest.mock('../database');

const mockedDb = jest.mocked(database);

describe('UserService', () => {
  beforeEach(() => {
    // Clear all mock state between tests
    jest.clearAllMocks();
  });

  test('fetches a user by ID from the database', async () => {
    const mockUser = { id: '1', name: 'Alice', email: 'alice@example.com' };
    mockedDb.findById.mockResolvedValue(mockUser);

    const service = new UserService();
    const user = await service.getUser('1');

    expect(mockedDb.findById).toHaveBeenCalledWith('1');
    expect(mockedDb.findById).toHaveBeenCalledTimes(1);
    expect(user).toEqual(mockUser);
  });

  test('throws when user is not found', async () => {
    mockedDb.findById.mockResolvedValue(null);

    const service = new UserService();

    await expect(service.getUser('999')).rejects.toThrow('User not found');
  });
});

For more granular control, jest.fn() creates standalone mock functions you can pass as callbacks or method implementations.

// src/__tests__/eventHandler.test.ts — Using jest.fn() for callback testing
describe('event handler', () => {
  test('calls the callback with processed data', () => {
    const callback = jest.fn();

    processEvents([{ type: 'click', target: 'button' }], callback);

    expect(callback).toHaveBeenCalledTimes(1);
    expect(callback).toHaveBeenCalledWith({
      type: 'click',
      target: 'button',
      timestamp: expect.any(Number),
    });
  });

  test('mock implementation controls return value', () => {
    const getPrice = jest.fn()
      .mockReturnValueOnce(10.99)
      .mockReturnValueOnce(24.99)
      .mockReturnValue(0);

    expect(getPrice()).toBe(10.99);
    expect(getPrice()).toBe(24.99);
    expect(getPrice()).toBe(0);
  });
});

Testing Asynchronous Code

Modern JavaScript is heavily asynchronous. Jest handles promises, async/await, and callbacks with equal ease. The key is always returning or awaiting the asynchronous operation so Jest knows when the test is done.

// src/__tests__/api.test.ts — Patterns for testing async operations
describe('API client', () => {
  test('fetches data with async/await', async () => {
    const data = await fetchUserProfile('alice');

    expect(data.username).toBe('alice');
    expect(data.posts).toBeInstanceOf(Array);
  });

  test('handles API errors gracefully', async () => {
    // Mock fetch to simulate a network failure
    global.fetch = jest.fn().mockRejectedValue(new Error('Network error'));

    const result = await fetchWithRetry('/api/data', { retries: 3 });

    expect(result.error).toBe('Network error');
    expect(global.fetch).toHaveBeenCalledTimes(4); // initial + 3 retries
  });

  test('resolves multiple concurrent requests', async () => {
    const [users, posts] = await Promise.all([
      fetchUsers(),
      fetchPosts(),
    ]);

    expect(users).toHaveLength(10);
    expect(posts).toHaveLength(25);
  });
});

Snapshot Testing

Snapshots capture the output of a component or function and compare it against a saved reference. They are invaluable for catching unintended changes in UI components or serialized data structures.

// src/__tests__/components.test.tsx — Snapshot testing for React components
import { render } from '@testing-library/react';
import { UserCard } from '../components/UserCard';

describe('UserCard', () => {
  test('renders correctly with user data', () => {
    const { container } = render(
      <UserCard
        name="Alice Johnson"
        email="alice@example.com"
        role="admin"
      />
    );

    expect(container).toMatchSnapshot();
  });

  test('inline snapshot for small outputs', () => {
    const formatted = formatAddress({
      street: '123 Main St',
      city: 'Springfield',
      state: 'IL',
    });

    expect(formatted).toMatchInlineSnapshot(`"123 Main St, Springfield, IL"`);
  });
});

When a snapshot test fails because you intentionally changed the output, update the snapshots with jest --updateSnapshot.

Coverage Reports and Watch Mode

Jest's built-in coverage tool uses Istanbul under the hood. It generates reports showing which lines, branches, functions, and statements your tests exercise.

# Generate a coverage report in multiple formats
npx jest --coverage --coverageReporters='text' --coverageReporters='lcov'

Watch mode is where Jest becomes a development companion. It watches for file changes and re-runs only the tests affected by those changes.

# Start watch mode — press 'p' to filter by filename, 't' to filter by test name
npx jest --watch

Watch mode supports interactive filtering. Press p to filter tests by a filename regex, t to filter by test name, or a to run all tests. This tight feedback loop makes TDD practical even in large codebases.

CI Integration

In continuous integration, Jest should run with specific flags that optimize for non-interactive environments and produce machine-readable output.

# .github/workflows/test.yml — GitHub Actions workflow running Jest
name: Tests
on: [push, pull_request]

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: 20
          cache: npm

      - run: npm ci
      - run: npx jest --ci --coverage --maxWorkers=2

      - uses: actions/upload-artifact@v4
        if: always()
        with:
          name: coverage-report
          path: coverage/lcov-report/

The --ci flag changes snapshot behavior to fail instead of writing new snapshots, preventing accidental snapshot updates in CI. The --maxWorkers flag controls parallelism to match your CI runner's CPU count and avoid out-of-memory failures.