MeWrite Docs

Jest: Test failed

Jestテストが失敗した場合のエラー

概要

Jestでテストケースが期待した結果と一致せず失敗した場合のエラーです。

エラーメッセージ

FAIL src/utils.test.js
  ✕ should add numbers correctly (5 ms)

  ● should add numbers correctly

    expect(received).toBe(expected)

    Expected: 5
    Received: 4

原因

  1. アサーション失敗: 期待値と実際の値が異なる
  2. 非同期処理の問題: Promiseの解決を待っていない
  3. モックの設定ミス: モック関数が正しく設定されていない
  4. タイミング問題: 非同期処理のタイムアウト

解決策

1. 正確なマッチャーを使用

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
// オブジェクトの比較
expect({ a: 1 }).toEqual({ a: 1 });  // toBeではなくtoEqual

// 配列の比較
expect([1, 2, 3]).toContain(2);
expect([1, 2, 3]).toHaveLength(3);

// 近似値の比較
expect(0.1 + 0.2).toBeCloseTo(0.3);

// 例外のテスト
expect(() => { throw new Error('test') }).toThrow('test');

2. 非同期テストの正しい書き方

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
// async/await
test('fetches user data', async () => {
  const data = await fetchUserData(1);
  expect(data.name).toBe('John');
});

// Promiseを返す
test('resolves to data', () => {
  return fetchData().then(data => {
    expect(data).toBeDefined();
  });
});

// done コールバック
test('callback test', done => {
  fetchData(data => {
    expect(data).toBeDefined();
    done();
  });
});

3. モックの設定

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
// モジュールのモック
jest.mock('./api');

import { fetchData } from './api';

test('uses mocked data', async () => {
  fetchData.mockResolvedValue({ id: 1, name: 'John' });

  const result = await fetchData();
  expect(result.name).toBe('John');
  expect(fetchData).toHaveBeenCalledTimes(1);
});

// モックのリセット
beforeEach(() => {
  jest.clearAllMocks();
});

4. タイマーのモック

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
jest.useFakeTimers();

test('debounce works', () => {
  const callback = jest.fn();
  const debounced = debounce(callback, 1000);

  debounced();
  debounced();
  debounced();

  expect(callback).not.toBeCalled();

  jest.advanceTimersByTime(1000);

  expect(callback).toBeCalledTimes(1);
});

5. スナップショットテスト

1
2
3
4
5
6
7
test('renders correctly', () => {
  const tree = renderer.create(<Button label="Click" />).toJSON();
  expect(tree).toMatchSnapshot();
});

// スナップショットを更新
// jest --updateSnapshot

6. テストカバレッジ

1
2
3
4
5
# カバレッジレポートを生成
jest --coverage

# 特定のファイルのみ
jest --coverage --collectCoverageFrom="src/**/*.{js,jsx}"

7. デバッグ

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
test('debug test', () => {
  const result = myFunction(input);

  // 値を確認
  console.log('Result:', result);

  // テストを一時停止(node --inspect-brk)
  debugger;

  expect(result).toBe(expected);
});
1
2
# デバッガーを使用
node --inspect-brk node_modules/.bin/jest --runInBand

8. テストの分離

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
describe('UserService', () => {
  let userService;

  beforeEach(() => {
    userService = new UserService();
  });

  afterEach(() => {
    userService.cleanup();
  });

  test('creates user', () => {
    // 各テストは独立
  });
});

9. カスタムマッチャー

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
expect.extend({
  toBeValidEmail(received) {
    const pass = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(received);
    return {
      pass,
      message: () => `expected ${received} to be a valid email`
    };
  }
});

test('validates email', () => {
  expect('test@example.com').toBeValidEmail();
});

10. 環境変数のモック

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
const originalEnv = process.env;

beforeEach(() => {
  process.env = { ...originalEnv, NODE_ENV: 'test' };
});

afterEach(() => {
  process.env = originalEnv;
});

test('uses test environment', () => {
  expect(process.env.NODE_ENV).toBe('test');
});

よくある間違い

  • toBe() で オブジェクトを比較(toEqual() を使用)
  • async テストで await を忘れる
  • モックのリセットを忘れる(beforeEach で clearAllMocks)
  • テスト間で状態が共有される

Jest の他のエラー

最終更新: 2025-12-09