vitest-testing
TypeScript/JavaScriptプロジェクト向けのVitestを活用したモダンなテスト環境を提供します。高速なユニット・統合テスト、ネイティブESMサポート、Vite駆動のHMR、充実したモック機能を備えており、TS/JSプロジェクトのテスト作成・実行に使用します。
description の原文を見る
Modern TypeScript/JavaScript testing with Vitest. Fast unit and integration tests, native ESM support, Vite-powered HMR, and comprehensive mocking. Use for testing TS/JS projects.
SKILL.md 本文
Vitest テスティング
Vite によって駆動された高速テストフレームワーク Vitest を使用した JavaScript/TypeScript プロジェクトのテストに関するエキスパート知識です。
クイックスタート
インストール
# Bun を使用(推奨)
bun add -d vitest
# npm を使用
npm install -D vitest
設定
// vitest.config.ts
import { defineConfig } from 'vitest/config'
export default defineConfig({
test: {
globals: true,
environment: 'node', // or 'jsdom'
coverage: {
provider: 'v8',
reporter: ['text', 'json', 'html'],
thresholds: { lines: 80, functions: 80, branches: 80 },
},
include: ['**/*.{test,spec}.{js,ts,jsx,tsx}'],
},
})
テストの実行
# すべてのテストを実行(Bun を推奨)
bun test
# ウォッチモード(デフォルト)
bun test --watch
# 1 回実行(CI モード)
bun test --run
# カバレッジ付き
bun test --coverage
# 特定のファイル
bun test src/utils/math.test.ts
# パターンマッチング
bun test --grep="calculates sum"
# UI モード(対話的)
bun test --ui
# 詳細な出力
bun test --reporter=verbose
テストの記述
基本的な構造
import { describe, it, expect, beforeEach, afterEach } from 'vitest'
import { add, subtract } from './math'
describe('Math utilities', () => {
beforeEach(() => {
// Setup before each test
})
it('adds two numbers correctly', () => {
expect(add(2, 3)).toBe(5)
})
it('subtracts two numbers correctly', () => {
expect(subtract(5, 3)).toBe(2)
})
})
パラメータ化されたテスト
describe.each([
{ input: 2, expected: 4 },
{ input: 3, expected: 9 },
])('square function', ({ input, expected }) => {
it(`squares ${input} to ${expected}`, () => {
expect(square(input)).toBe(expected)
})
})
アサーション
// 等値性
expect(value).toBe(expected)
expect(value).toEqual(expected)
// 真偽値
expect(value).toBeTruthy()
expect(value).toBeNull()
expect(value).toBeDefined()
// 数値
expect(number).toBeGreaterThan(3)
expect(number).toBeCloseTo(0.3, 1)
// 文字列と配列
expect(string).toMatch(/pattern/)
expect(array).toContain(item)
// オブジェクト
expect(object).toHaveProperty('key')
expect(object).toMatchObject({ a: 1 })
// 例外
expect(() => throwError()).toThrow('message')
// Promise
await expect(promise).resolves.toBe(value)
await expect(promise).rejects.toThrow()
モッキング
関数のモック
import { vi } from 'vitest'
const mockFn = vi.fn()
mockFn.mockReturnValue(42)
mockFn.mockResolvedValue('async result')
mockFn.mockImplementation((x) => x * 2)
expect(mockFn).toHaveBeenCalled()
expect(mockFn).toHaveBeenCalledWith('arg')
モジュールのモック
vi.mock('./api', () => ({
fetchUser: vi.fn(() => ({ id: 1, name: 'Test User' })),
}))
import { fetchUser } from './api'
beforeEach(() => {
vi.clearAllMocks()
})
タイマー
beforeEach(() => vi.useFakeTimers())
afterEach(() => vi.restoreAllMocks())
it('advances timers', () => {
const callback = vi.fn()
setTimeout(callback, 1000)
vi.advanceTimersByTime(1000)
expect(callback).toHaveBeenCalledOnce()
})
it('mocks dates', () => {
const date = new Date('2024-01-01')
vi.setSystemTime(date)
expect(Date.now()).toBe(date.getTime())
})
カバレッジ
# カバレッジレポートを生成
bun test --coverage
# HTML レポート
bun test --coverage --coverage.reporter=html
open coverage/index.html
# 閾値に対してチェック
bun test --coverage --coverage.thresholds.lines=90
インテグレーションテスト
import request from 'supertest'
import { app } from './app'
describe('API endpoints', () => {
it('creates a user', async () => {
const response = await request(app)
.post('/api/users')
.send({ name: 'John' })
.expect(201)
expect(response.body).toMatchObject({
id: expect.any(Number),
name: 'John',
})
})
})
ベストプラクティス
- ソースファイルごとに 1 つのテストファイル:
math.ts→math.test.ts describe()ブロックで関連するテストをグループ化- 説明的なテスト名を使用
- 外部依存関係のみをモック
- 独立した非同期テストには
concurrentテストを使用 - 高価なフィクスチャは
beforeAll()で共有 - 80%以上のカバレッジを目指しますが、100%を追い求めない
参照
test-quality-analysis- テストの問題検出playwright-testing- E2E テストmutation-testing- テスト効果の検証
ライセンス: MIT(寛容ライセンスのため全文を引用しています) · 原本リポジトリ
詳細情報
- 作者
- secondsky
- ライセンス
- MIT
- 最終更新
- 不明
Source: https://github.com/secondsky/claude-skills / ライセンス: MIT
関連スキル
doubt-driven-development
重要な判断はすべて、本番環境への展開前に新しい視点から対抗的レビューを実施します。速度より正確性が重要な場合、不慣れなコードを扱う場合、本番環境・セキュリティに関わるロジック・取り消し不可の操作など影響度が高い場合、または後でバグを修正するよりも今検証する方が効率的な場合に活用してください。
apprun-skills
TypeScriptを使用したAppRunアプリケーションのMVU設計に関する総合的なガイダンスが得られます。コンポーネントパターン、イベントハンドリング、状態管理(非同期ジェネレータを含む)、パラメータと保護機能を備えたルーティング・ナビゲーション、vistestを使用したテストに対応しています。AppRunコンポーネントの設計・レビュー、ルートの配線、状態フローの管理、AppRunテストの作成時に活用してください。
desloppify
コードベースのヘルスチェックと技術負債の追跡ツールです。コード品質、技術負債、デッドコード、大規模ファイル、ゴッドクラス、重複関数、コードスメル、命名規則の問題、インポートサイクル、結合度の問題についてユーザーが質問した場合に使用してください。また、ヘルススコアの確認、次の改善項目の提案、クリーンアップ計画の作成をリクエストされた際にも対応します。29言語に対応しています。
debugging-and-error-recovery
テストが失敗したり、ビルドが壊れたり、動作が期待と異なったり、予期しないエラーが発生したりした場合に、体系的な根本原因デバッグをガイドします。推測ではなく、根本原因を見つけて修正するための体系的なアプローチが必要な場合に使用してください。
test-driven-development
テスト駆動開発により実装を進めます。ロジックの実装、バグの修正、動作の変更など、あらゆる場面で活用できます。コードが正常に動作することを証明する必要がある場合、バグ報告を受けた場合、既存機能を修正する予定がある場合に使用してください。
incremental-implementation
変更を段階的に実施します。複数のファイルに影響する機能や変更を実装する場合に使用してください。大量のコードを一度に書こうとしている場合や、タスクが一度では完結できないほど大きい場合に活用します。