vitest-3-features について
Vitest 3.x を使う開発者向けのリファレンススキルです。テスト機能や設定、Vitest 2.x からの移行に加え、対象を絞った実行、ブラウザテスト、レポート、プロジェクト構成を扱います。
主な機能
- 01テスト注釈と添付ファイル
- 02行番号によるテスト選択
- 03ウォッチモードとレポートの改善
- 04ワークスペースのプロジェクト設定
- 05ブラウザテストとカバレッジの指針
- 06モックとマッチャーの更新
活用シーン
- 01開発中に単一テストを実行
- 02単体・統合テストのプロジェクト整理
- 03テストレポートへのメタデータ追加
- 04Vitest 2.x からの移行
インストール
コマンドをコピーしてターミナルで実行します。
npx skills add https:/ / github.com/ josiahsiegel/ claude-plugin-marketplace --skill vitest-3-featuresインストール後、Claude Code で/vitest-3-featuresを入力して読み込まれたか確認します。
詳細
🚨 重要なガイドライン
Windows のファイルパス要件
必須:Windows ではファイルパスに常にバックスラッシュを使用してください
Windows で Edit または Write ツールを使用する場合、ファイルパスにはスラッシュ(/)ではなく、バックスラッシュ(\)を必ず使用してください。
例:
- ❌ 誤り:
D:/repos/project/file.tsx - ✅ 正しい:
D:\repos\project\file.tsx
これは次に適用されます。
- Edit ツールの file_path パラメーター
- Write ツールの file_path パラメーター
- Windows システムでのすべてのファイル操作
ドキュメント作成のガイドライン
ユーザーから明示的に依頼されない限り、新しいドキュメントファイルを作成しないでください。
- 優先事項:新しいドキュメントを作成するのではなく、既存の README.md ファイルを更新してください
- リポジトリの整理:ユーザーから別途依頼されない限り、リポジトリのルートには README.md のみを置いてください
- スタイル:ドキュメントは簡潔で率直、かつプロフェッショナルなものにし、AI 生成のような文体は避けてください
- ユーザーの希望:ユーザーからドキュメント作成を明確に依頼された場合に限り、追加の .md ファイルを作成してください
Vitest 3.x の機能とベストプラクティス(2025)
概要
Vitest 3.0 は 2025 年 1 月にリリースされ、レポート機能、ブラウザテスト、ウォッチモード、開発者エクスペリエンスが大幅に改善されました。このスキルでは、Vitest 3.x の機能と最新のテストパターンに関する包括的な知識を提供します。
Vitest 3.0 以降の主な機能
1. アノテーション API(Vitest 3.2 以降)
アノテーション API を使うと、任意のテストにカスタムメタデータ、メッセージ、添付ファイルを追加できます。これらは UI、HTML、JUnit、TAP、GitHub Actions のレポーターに表示されます。
使用方法:
import { test, expect } from 'vitest';
test('user authentication', async ({ task }) => {
// Add custom annotation
task.meta.annotation = {
message: 'Testing OAuth2 flow with external provider',
attachments: [
{ name: 'config', content: JSON.stringify(oauthConfig) }
]
};
const result = await authenticateUser(credentials);
expect(result.token).toBeDefined();
});
使用例:
- 複雑なテストシナリオを文書化する
- デバッグ情報を添付する
- 外部リソース(チケット、ドキュメント)へのリンクを追加する
- パフォーマンス指標を追加する
- レポート用にテストのメタデータを追跡する
2. 行番号によるフィルタリング
ファイル内の行番号を指定して特定のテストを実行できるため、IDE からテストを正確に実行できます。
CLI の使用方法:
# Run test at specific line
vitest run tests/user.test.js:42
# Run multiple tests by line
vitest run tests/user.test.js:42 tests/user.test.js:67
# Works with ranges
vitest run tests/user.test.js:42-67
IDE との統合:
- VS Code:行番号のガターをクリック
- JetBrains IDE:コンテキストメニューから実行
- 「カーソル位置のテストを実行」機能を利用可能
3. 強化されたウォッチモード
変更検出が改善され、よりスマートで応答性の高いウォッチモードを利用できます。
機能:
- 変更をより正確に検出
- 影響を受けるテストのみを再実行
- 再ビルド時間を短縮
- Windows でのファイル監視を改善
- 誤検出を削減
設定:
export default defineConfig({
test: {
watch: true,
watchExclude: ['**/node_modules/**', '**/dist/**'],
// New in 3.0: More intelligent caching
cache: {
dir: '.vitest/cache'
}
}
});
4. テストレポートの改善
テスト実行レポートが全面的に刷新され、画面のちらつきが抑えられ、出力がより明確になりました。
レポーター API の変更点:
// Custom reporter with new lifecycle
export default class CustomReporter {
onInit(ctx) {
// Called once at start
}
onTestStart(test) {
// More reliable test start hook
}
onTestComplete(test) {
// Includes full test metadata
}
onFinished(files, errors) {
// Final results with all context
}
}
メリット:
- テスト実行中のターミナルのちらつきを軽減
- テストステータスの表示を明確化
- エラーのフォーマットを改善
- 進捗状況の追跡を改善
5. ワークスペース設定の簡素化
ワークスペース用の別ファイルは不要です。プロジェクトを設定ファイルに直接定義できます。
従来の方法(Vitest 2.x):
// vitest.workspace.js
export default ['packages/*'];
新しい方法(Vitest 3.0):
// vitest.config.js
export default defineConfig({
test: {
workspace: [
{
test: {
name: 'unit',
include: ['tests/unit/**/*.test.js']
}
},
{
test: {
name: 'integration',
include: ['tests/integration/**/*.test.js']
}
}
]
}
});
6. 強化されたブラウザテスト
パフォーマンスとキャッシュ機能が改善されたブラウザモードを利用できます。
複数のブラウザーインスタンス:
export default defineConfig({
test: {
browser: {
enabled: true,
instances: [
{ browser: 'chromium', name: 'chrome' },
{ browser: 'firefox', name: 'ff' },
{ browser: 'webkit', name: 'safari' }
]
}
}
});
メリット:
- すべてのブラウザーで単一の Vite サーバーを使用
- ファイル処理をキャッシュ
- ブラウザーで並列実行
- 起動時間を短縮
7. カバレッジの改善
テストファイルがカバレッジレポートから自動的に除外されます。
自動除外(Vitest 3.0):
export default defineConfig({
test: {
coverage: {
provider: 'v8',
// Test files automatically excluded
// No need to manually exclude *.test.js
exclude: [
// Only need to specify custom exclusions
'**/node_modules/**',
'**/dist/**'
]
}
}
});
8. モック機能の強化
スパイの再利用機能と強力なマッチャーが追加されました。
スパイの再利用:
const spy = vi.fn();
// Vitest 3.0: Reuse spy on already mocked method
vi.spyOn(obj, 'method').mockImplementation(spy);
vi.spyOn(obj, 'method'); // Reuses existing spy
新しいマッチャー:
// toHaveBeenCalledExactlyOnceWith
expect(mockFn).toHaveBeenCalledExactlyOnceWith(arg1, arg2);
// Ensures called exactly once with exact arguments
// Fails if called 0 times, 2+ times, or with different args
9. プロジェクトの除外パターン
否定パターンを使って、特定のプロジェクトを除外できます。
CLI の使用方法:
# Run all except integration tests
vitest run --project=!integration
# Run all except multiple projects
vitest run --project=!integration --project=!e2e
# Combine inclusion and exclusion
vitest run --project=unit --project=!slow
10. UI の改善
デバッグとナビゲーションが強化され、テスト UI が大幅に改善されました。
新しい UI 機能:
- UI から個別のテストを実行
- 失敗したテストまで自動スクロール
- node_modules の表示を切り替え
- フィルタリングと検索を改善
- テスト管理コントロールを改善
- モジュールグラフを可視化
UI の起動:
vitest --ui
Vitest 3.x のベストプラクティス
1. 複雑なテストにアノテーション API を使用する
test('complex payment flow', async ({ task }) => {
task.meta.annotation = {
message: 'Tests Stripe webhook integration',
attachments: [
{ name: 'webhook-payload', content: JSON.stringify(payload) },
{ name: 'ticket', content: 'https://jira.company.com/TICKET-123' }
]
};
// Test implementation
});
2. 開発中に行番号フィルタリングを活用する
# Quick iteration on single test
vitest run src/auth.test.js:145 --watch
3. ワークスペースプロジェクトで整理する
export default defineConfig({
test: {
workspace: [
{
test: {
name: 'unit-fast',
include: ['tests/unit/**/*.test.js'],
environment: 'node'
}
},
{
test: {
name: 'unit-dom',
include: ['tests/unit/**/*.dom.test.js'],
environment: 'happy-dom'
}
},
{
test: {
name: 'integration',
include: ['tests/integration/**/*.test.js'],
setupFiles: ['tests/setup.js']
}
}
]
}
});
4. 厳密なテストにはtoHaveBeenCalledExactlyOnceWithを使用する
test('should call API exactly once with correct params', () => {
const apiSpy = vi.spyOn(api, 'fetchUser');
renderComponent({ userId: 123 });
// Strict assertion - fails if called 0, 2+ times or wrong args
expect(apiSpy).toHaveBeenCalledExactlyOnceWith(123);
});
5. 大規模プロジェクト向けにウォッチモードを最適化する
export default defineConfig({
test: {
watch: true,
watchExclude: [
'**/node_modules/**',
'**/dist/**',
'**/.git/**',
'**/coverage/**'
],
// Run only related tests
changed: true,
// Faster reruns
isolate: false // Use with caution
}
});
6. CI/CD向けのカスタムレポーター
// reporters/junit-plus.js
export default class JUnitPlusReporter {
onFinished(files, errors) {
const results = files.map(file => ({
name: file.name,
tests: file.tasks.length,
failures: file.tasks.filter(t => t.result?.state === 'fail').length,
// Add annotations from tests
annotations: file.tasks
.map(t => t.meta?.annotation)
.filter(Boolean)
}));
// Export to CI system
exportToCI(results);
}
}
// vitest.config.js
export default defineConfig({
test: {
reporters: ['default', './reporters/junit-plus.js']
}
});
Vitest 2.xから3.xへの移行
破壊的変更
-
ワークスペース設定:
- ワークスペースのプロジェクトをメイン設定に移動します
- プロジェクト参照を更新します
-
レポーターAPI:
- カスタムレポーターを新しいライフサイクルに合わせて更新します
- レポーターのメソッドシグネチャを確認します
-
ブラウザーモード:
- ブラウザーモードを使用している場合は、プロバイダーの構文を更新します
- ブラウザー設定を確認します
移行手順
# Update Vitest
npm install -D vitest@^3.0.0
# Update related packages
npm install -D @vitest/ui@^3.0.0
npm install -D @vitest/coverage-v8@^3.0.0
# Run tests to check for issues
npm test
# Update configs based on deprecation warnings
パフォーマンス最適化のヒント
1. 分離にはワークスペースプロジェクトを使用する
// Separate fast unit tests from slower integration tests
workspace: [
{
test: {
name: 'unit',
include: ['tests/unit/**'],
environment: 'node' // Fastest
}
},
{
test: {
name: 'integration',
include: ['tests/integration/**'],
environment: 'happy-dom',
setupFiles: ['tests/setup.js']
}
}
]
2. テスト実行を並列化する
# Run projects in parallel
vitest run --project=unit --project=integration
# Exclude slow tests during development
vitest run --project=!e2e --project=!slow
3. TDDでは行フィルタリングを使用する
# Rapid iteration on single test
vitest run src/feature.test.js:42 --watch
4. ブラウザーテストを最適化する
export default defineConfig({
test: {
browser: {
enabled: true,
// Reuse context for speed (less isolation)
isolate: false,
// Single instance for development
instances: [{ browser: 'chromium' }]
}
}
});
よく使われるパターン
デバッグ用のテストアノテーション
test('payment processing', async ({ task }) => {
const startTime = Date.now();
try {
const result = await processPayment(data);
task.meta.annotation = {
message: `Completed in ${Date.now() - startTime}ms`,
attachments: [
{ name: 'result', content: JSON.stringify(result) }
]
};
expect(result.success).toBe(true);
} catch (error) {
task.meta.annotation = {
message: 'Payment processing failed',
attachments: [
{ name: 'error', content: error.message },
{ name: 'payload', content: JSON.stringify(data) }
]
};
throw error;
}
});
マルチプロジェクトのテスト戦略
export default defineConfig({
test: {
workspace: [
// Fast feedback loop
{
test: {
name: 'unit-critical',
include: ['tests/unit/critical/**'],
environment: 'node'
}
},
// Standard tests
{
test: {
name: 'unit-standard',
include: ['tests/unit/**'],
exclude: ['tests/unit/critical/**'],
environment: 'happy-dom'
}
},
// Slow integration tests
{
test: {
name: 'integration',
include: ['tests/integration/**'],
testTimeout: 30000
}
}
]
}
});