Jestテスト|テストの初期設定と後処理beforeEach&afterEach

Jestテストの初期設定と後処理で使用される「beforeEach&afterEach」とは?

5/28/2025

「beforeEach&afterEach」とは?

Jestの beforeEach と afterEach は、各テストの前後に毎回実行される処理を定義するための関数。

関数

実行タイミング

よくある使い方

beforeEach

各テストの直前に実行

毎回共通で使う準備処理(変数の初期化・モックのリセットなど)

afterEach

各テストの直後に実行

クリーンアップ処理(DBやファイルの後始末、モックの解除など)

基本の使い方

🔸テスト対象のモジュール|counter.ts

let count = 0;

export const increment = () => {
  count += 1;
};

export const decrement = () => {
  count -= 1;
};

export const reset = () => {
  count = 0;
};

export const getCount = () => {
  return count;
};

🔸テストコード|counter.test.ts

// counter.test.ts
import { increment, decrement, reset, getCount } from './counter';

beforeEach(() => {
  // 各テスト前にカウントをリセットしておく
  reset();
});

afterEach(() => {
  // 各テスト後に現在の値をログに出力
  console.log('現在のカウント:', getCount());
});

test('increment 関数で +1 される', () => {
  increment();
  expect(getCount()).toBe(1);
});

test('decrement 関数で -1 される', () => {
  decrement();
  expect(getCount()).toBe(-1);
});

test('reset 関数で 0 に戻る', () => {
  increment();
  increment();
  reset();
  expect(getCount()).toBe(0);
});

✅テスト通過時

 PASS  counter.test.ts
  ✓ increment 関数で +1 される
  ✓ decrement 関数で -1 される
  ✓ reset 関数で 0 に戻る

  console.log
    現在のカウント: 1
  console.log
    現在のカウント: -1
  console.log
    現在のカウント: 0

よくある使い方

🔸モックの初期化

let mockFn: jest.Mock;

beforeEach(() => {
  mockFn = jest.fn(); // テストごとに新しいモック関数を準備
});

test('関数が1回呼ばれる', () => {
  mockFn();
  expect(mockFn).toHaveBeenCalledTimes(1);
});

🔸DOMやタイマーのクリーンアップ(ReactやsetTimeoutなど)

beforeEach(() => {
  jest.useFakeTimers(); // タイマーをモックに置き換え
});

afterEach(() => {
  jest.runOnlyPendingTimers(); // 残ったタイマー処理を実行
  jest.useRealTimers();        // タイマーを元に戻す
});