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

web-testing-vitest

Vitestというツールを使って、Webサイトのテストに必要な設定、検証、モック(代役)、時間操作、画面キャプチャ、網羅率などを効率的に行い、品質向上を支援するSkill。

📜 元の英語説明(参考)

Vitest test runner - configuration, assertions, mocking (vi.fn, vi.mock, vi.spyOn), fake timers, snapshot testing, coverage, workspace projects

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

一言でいうと

Vitestというツールを使って、Webサイトのテストに必要な設定、検証、モック(代役)、時間操作、画面キャプチャ、網羅率などを効率的に行い、品質向上を支援するSkill。

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

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

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

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

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

💾 手動でダウンロードしたい(コマンドが難しい人向け)
  1. 1. 下の青いボタンを押して web-testing-vitest.zip をダウンロード
  2. 2. ZIPファイルをダブルクリックで解凍 → web-testing-vitest フォルダができる
  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 自身は原文を読みます。誤訳がある場合は原文をご確認ください。

Vitest テストランナーのパターン

クイックガイド: Vitest は高速な、Vite ネイティブのテストランナーです。テスト構造には describe/it/expect を、モックには vi.fn() を、モジュールモックには vi.mock() を、スパイには vi.spyOn() を使用します。テストはコードと同じ場所に配置します。モジュールレベルのモックよりもネットワークレベルの API モックを使用します。Vitest v4 が現在の安定版です (Vite 6+、Node 20+ が必要です)。


<critical_requirements>

重要: この Skill を使用する前に

すべてのコードは CLAUDE.md のプロジェクト規約に従う必要があります (kebab-case、名前付きエクスポート、インポート順、import type、名前付き定数)

(テストはフィーチャーベースの構造でコードと同じ場所に配置する必要があります - 別のテストディレクトリには配置しないでください)

(可能な限り、モジュールレベルのモックではなく、ネットワークレベルの API モックを使用する必要があります)

(テストデータには名前付き定数を使用する必要があります - テストファイルにマジックストリングや数値を使用しないでください)

(モックには vi.fn() を、スパイには vi.spyOn() を使用する必要があります - 関数を手動で置き換えないでください)

(v3+ のテストオプション構文を使用する必要があります: test("name", { timeout: 10_000 }, () => {}) - 3 番目の引数として渡さないでください)

</critical_requirements>


自動検出: Vitest, vi.fn, vi.mock, vi.spyOn, describe, it, expect, test, beforeEach, afterEach, vi.useFakeTimers, vitest.config, defineConfig, coverage, snapshot, mockResolvedValue, mockRejectedValue

使用する場面:

  • Vitest を使用したテストの設定と実行
  • 純粋関数のユニットテストの作成
  • ネットワークレベルのモックを使用した統合テストの作成
  • モジュール、関数、タイマーのモック
  • スナップショットテスト
  • カバレッジ、ワークスペース、プロジェクトの設定

使用しない場面:

  • E2E ブラウザテスト (E2E テストツールを使用してください)
  • コンポーネントのレンダリングとクエリ (コンポーネントテストライブラリを使用してください)
  • サードパーティライブラリの動作のテスト (ライブラリにはすでにテストがあります)
  • TypeScript のコンパイル時保証のテスト (TypeScript がすでに強制しています)

カバーする主なパターン:

  • テスト構造と構成 (describe, it, expect)
  • モック (vi.fn, vi.mock, vi.spyOn, vi.mockObject)
  • 偽のタイマー (vi.useFakeTimers, vi.advanceTimersByTime)
  • 統合テストのためのネットワークレベルの API モック
  • フィーチャーベースのテスト構成 (コードと同じ場所に配置)
  • 設定 (vitest.config, projects, coverage)
  • Vitest v3/v4 の移行と破壊的変更

詳細なリソース:


<philosophy>

Philosophy

Vitest は、速度と開発者エクスペリエンスのために設計された、Vite ネイティブのテストランナーです。ネイティブ ESM サポート、TypeScript の標準サポート、Vite の変換パイプラインを備えた、Jest 互換の API を提供します。

コア原則:

  1. テストはコードと同じ場所に配置する - テストは、見つけやすさとメンテナンスのために、テスト対象のコードの隣に配置します
  2. モジュールモックよりもネットワークレベルのモック - インポート境界ではなく、HTTP 境界でモックします
  3. すべてのテストデータに名前付き定数を使用する - テストファイルにマジックストリングや数値を使用しないでください
  4. 実装ではなく、動作をテストする - 内部状態ではなく、入力と出力に焦点を当てます
  5. 高速なフィードバックループ - Vitest の HMR ベースのウォッチモードを活用して、即座に再実行します

Vitest を使用する場面:

  • 純粋関数のユニットテスト (ビジネスロジック、ユーティリティ、フォーマッタ)
  • ネットワークレベルの API モックを使用した統合テスト
  • シリアライズ可能な出力のスナップショットテスト
  • 実際のブラウザを必要としないテスト

Vitest を使用しない場面:

  • ブラウザベースの E2E テスト (E2E テストツールを使用してください)
  • ビジュアルリグレッションテスト (ビジュアルテストツールを使用してください)

</philosophy>


<patterns>

コアパターン

パターン 1: 純粋関数のユニットテスト

副作用のない純粋関数のユニットテストを作成します。明確な入力/出力の動作に焦点を当てます。

テスト対象:

  • 明確な入力 -> 出力を持つ純粋関数
  • ビジネスロジックの計算 (価格設定、税金、割引)
  • データ変換とフォーマッタ
  • エッジケースと境界条件

純粋関数のテスト例については、examples/core.md を参照してください。


パターン 2: ネットワークレベルのモックを使用した統合テスト

Vitest とネットワークレベルの API モックを使用して、API 統合レイヤーを持つコンポーネントをテストします。

統合テストが理にかなっている場合:

  • 分離されたコンポーネントの動作 (フォームの検証、UI の状態)
  • E2E で再現するのが難しいエッジケースのテスト
  • 開発ワークフロー (フルスタックを起動するよりも高速)

キーパターン:

  • コードと同じ場所にある __tests__/ ディレクトリ内のテスト
  • ネットワークレベルの API モック (HTTP リクエストをインターセプトします)
  • 共有パッケージ内の中央化されたモックデータ
  • すべての状態をテストします: ローディング、空、エラー、成功

統合テストの例については、examples/integration.md を参照してください。


パターン 3: フィーチャーベースのテスト構成

フィーチャーベースの構造で、テストをコードと同じ場所に配置します。テストは、テスト対象のものの隣に配置されます。

直接的な同じ場所への配置 (推奨):

src/
  features/
    auth/
      components/
        login-form.tsx
        login-form.test.tsx        # コンポーネントの隣にテスト
      hooks/
        use-auth.ts
        use-auth.test.ts           # フックの隣にテスト

代替案: __tests__/ サブディレクトリ:

src/features/auth/
  components/
    login-form.tsx
    __tests__/
      login-form.test.tsx

E2E テストの構成:

tests/
  e2e/
    auth/
      login-flow.spec.ts
      register-flow.spec.ts
    checkout/
      checkout-flow.spec.ts

ファイル命名規則:

  • ユニットテストおよび統合テストの場合は *.test.tsx / *.test.ts

1 つのパターンを選択し、コードベース全体で一貫性を保ちます。

</patterns>


<red_flags>

RED FLAGS

優先度の高い問題:

  • ネットワークレベルではなくモジュールレベルのモック (vi.mock) - インポート構造が変更されると壊れ、シリアライゼーションをテストしません
  • ハッピーパスのみのテスト - エラー状態
📜 原文 SKILL.md(Claudeが読む英語/中国語)を展開

Vitest Test Runner Patterns

Quick Guide: Vitest is a fast, Vite-native test runner. Use describe/it/expect for test structure, vi.fn() for mocks, vi.mock() for module mocking, vi.spyOn() for spying. Co-locate tests with code. Use network-level API mocking over module-level mocks. Vitest v4 is current stable (requires Vite 6+, Node 20+).


<critical_requirements>

CRITICAL: Before Using This Skill

All code must follow project conventions in CLAUDE.md (kebab-case, named exports, import ordering, import type, named constants)

(You MUST co-locate tests with code in feature-based structure - NOT in separate test directories)

(You MUST use network-level API mocking - NOT module-level mocks where possible)

(You MUST use named constants for test data - no magic strings or numbers in test files)

(You MUST use vi.fn() for mocks and vi.spyOn() for spying - NEVER manually replace functions)

(You MUST use the v3+ test options syntax: test("name", { timeout: 10_000 }, () => {}) - NOT as third argument)

</critical_requirements>


Auto-detection: Vitest, vi.fn, vi.mock, vi.spyOn, describe, it, expect, test, beforeEach, afterEach, vi.useFakeTimers, vitest.config, defineConfig, coverage, snapshot, mockResolvedValue, mockRejectedValue

When to use:

  • Configuring and running tests with Vitest
  • Writing unit tests for pure functions
  • Writing integration tests with network-level mocking
  • Mocking modules, functions, and timers
  • Snapshot testing
  • Configuring coverage, workspaces, and projects

When NOT to use:

  • E2E browser testing (use your E2E testing tool)
  • Component rendering and querying (use your component testing library)
  • Testing third-party library behavior (library already has tests)
  • Testing TypeScript compile-time guarantees (TypeScript already enforces)

Key patterns covered:

  • Test structure and organization (describe, it, expect)
  • Mocking (vi.fn, vi.mock, vi.spyOn, vi.mockObject)
  • Fake timers (vi.useFakeTimers, vi.advanceTimersByTime)
  • Network-level API mocking for integration tests
  • Feature-based test organization (co-located with code)
  • Configuration (vitest.config, projects, coverage)
  • Vitest v3/v4 migration and breaking changes

Detailed Resources:


<philosophy>

Philosophy

Vitest is a Vite-native test runner designed for speed and developer experience. It provides Jest-compatible APIs with native ESM support, TypeScript out of the box, and Vite's transform pipeline.

Core Principles:

  1. Co-locate tests with code - Tests live next to the code they test for discoverability and maintenance
  2. Network-level mocking over module mocking - Mock at the HTTP boundary, not at import boundaries
  3. Named constants for all test data - No magic strings or numbers in test files
  4. Test behavior, not implementation - Focus on inputs and outputs, not internal state
  5. Fast feedback loops - Leverage Vitest's HMR-based watch mode for instant re-runs

When to use Vitest:

  • Unit testing pure functions (business logic, utilities, formatters)
  • Integration testing with network-level API mocking
  • Snapshot testing for serializable outputs
  • Any test that doesn't require a real browser

When NOT to use Vitest:

  • Browser-based E2E testing (use your E2E testing tool)
  • Visual regression testing (use your visual testing tool)

</philosophy>


<patterns>

Core Patterns

Pattern 1: Unit Testing Pure Functions

Write unit tests for pure functions with no side effects. Focus on clear input/output behavior.

What to test:

  • Pure functions with clear input -> output
  • Business logic calculations (pricing, taxes, discounts)
  • Data transformations and formatters
  • Edge cases and boundary conditions

See examples/core.md for pure function test examples.


Pattern 2: Integration Testing with Network-Level Mocking

Use Vitest with network-level API mocking to test components with their API integration layer.

When Integration Tests Make Sense:

  • Component behavior in isolation (form validation, UI state)
  • Testing edge cases that are hard to reproduce in E2E
  • Development workflow (faster than spinning up full stack)

Key Pattern:

  • Tests in __tests__/ directories co-located with code
  • Network-level API mocking (intercepts HTTP requests)
  • Centralized mock data in shared package
  • Test all states: loading, empty, error, success

See examples/integration.md for integration test examples.


Pattern 3: Feature-Based Test Organization

Co-locate tests with code in feature-based structure. Tests live next to what they test.

Direct Co-location (Recommended):

src/
  features/
    auth/
      components/
        login-form.tsx
        login-form.test.tsx        # Test next to component
      hooks/
        use-auth.ts
        use-auth.test.ts           # Test next to hook

Alternative: __tests__/ Subdirectories:

src/features/auth/
  components/
    login-form.tsx
    __tests__/
      login-form.test.tsx

E2E Test Organization:

tests/
  e2e/
    auth/
      login-flow.spec.ts
      register-flow.spec.ts
    checkout/
      checkout-flow.spec.ts

File Naming Convention:

  • *.test.tsx / *.test.ts for unit and integration tests

Choose one pattern and be consistent across the codebase.

</patterns>


<red_flags>

RED FLAGS

High Priority Issues:

  • Module-level mocking (vi.mock) instead of network-level - breaks when import structure changes, doesn't test serialization
  • Only testing happy paths - error states go untested until users report them
  • Not using named constants for test data - magic strings and numbers make tests unreadable

Medium Priority Issues:

  • Mocks that don't match real API - tests pass but production fails because mocks drifted
  • Complex mocking setup - simplify or test at a higher level
  • Not resetting mocks between tests - causes cross-test pollution

Gotchas & Edge Cases:

  • Network mock handlers are typically global - reset handlers after each test to prevent pollution
  • Vitest v3+: Test options must be second argument: test("name", { timeout: 10_000 }, () => {}) NOT test("name", () => {}, { timeout: 10_000 })
  • Vitest v4: Multiple mock behavior changes (getMockName, restoreAllMocks, automocked getters) - see reference.md for full v4 migration notes
  • vi.fn().mock.invocationCallOrder starts at 1 in v4 instead of 0
  • vi.restoreAllMocks() only affects manual spies in v4, not automocks - use vi.resetAllMocks() for full reset

</red_flags>


<critical_reminders>

CRITICAL REMINDERS

All code must follow project conventions in CLAUDE.md

(You MUST co-locate tests with code in feature-based structure - NOT in separate test directories)

(You MUST use network-level API mocking - NOT module-level mocks where possible)

(You MUST use named constants for test data - no magic strings or numbers in test files)

(You MUST use vi.fn() for mocks and vi.spyOn() for spying - NEVER manually replace functions)

(You MUST use the v3+ test options syntax: test("name", { timeout: 10_000 }, () => {}) - NOT as third argument)

Failure to follow these rules will result in fragile tests that break on refactoring and false confidence from poorly structured test suites.

</critical_reminders>