Vitest: Test failed
Vitestでテストが失敗した場合の原因調査と解決策
概要
Vitestでテストが失敗した場合の原因特定とデバッグ方法です。
エラーメッセージ
``` FAIL src/utils.test.ts > sum > adds 1 + 2 to equal 3 AssertionError: expected 4 to equal 3 ```
原因
- アサーションの不一致: 期待値と実際の値が異なる
- 非同期処理の問題: awaitの欠落
- モックの設定ミス: モックが正しく機能していない
- 環境変数の欠落: テスト環境での設定漏れ
解決策
1. 基本的なテストの書き方
```typescript // src/utils.test.ts import { describe, it, expect } from ‘vitest’; import { sum } from ‘./utils’;
describe(‘sum’, () => { it(‘adds 1 + 2 to equal 3’, () => { expect(sum(1, 2)).toBe(3); });
it(‘handles negative numbers’, () => { expect(sum(-1, 1)).toBe(0); }); }); ```
2. 非同期テスト
```typescript import { describe, it, expect } from ‘vitest’; import { fetchUser } from ‘./api’;
describe(‘fetchUser’, () => { it(‘fetches user data’, async () => { const user = await fetchUser(‘1’); expect(user).toMatchObject({ id: ‘1’, name: expect.any(String), }); }); }); ```
3. モックの設定
```typescript import { vi, describe, it, expect, beforeEach } from ‘vitest’; import { sendEmail } from ‘./email’;
// モジュールをモック vi.mock(’./email’, () => ({ sendEmail: vi.fn(), }));
describe(’notification’, () => { beforeEach(() => { vi.clearAllMocks(); });
it(‘sends email on signup’, async () => { await signup({ email: ’test@example.com’ });
expect(sendEmail).toHaveBeenCalledWith(
expect.objectContaining({ to: 'test@example.com' })
);
}); }); ```
4. vitest.config.tsの設定
```typescript // vitest.config.ts import { defineConfig } from ‘vitest/config’;
export default defineConfig({ test: { globals: true, environment: ‘jsdom’, setupFiles: [’./test/setup.ts’], coverage: { reporter: [’text’, ‘html’], }, }, }); ```
5. デバッグモードで実行
```bash
特定のテストのみ実行
npx vitest run src/utils.test.ts
ウォッチモード
npx vitest
UIモード
npx vitest –ui
デバッグ
npx vitest –inspect-brk ```
よくある間違い
- toBeとtoEqualの使い分け
- モックのリセット忘れ
- 非同期テストでのawait忘れ
関連エラー
関連エラー
Testing の他のエラー
この記事は役に立ちましたか?