0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

TypeScript + Jestですべてのテスト前に共通処理を実行する

0
Posted at

はじめに

TypeScript + Jest 環境で、すべてのテストの前に共通処理を実行する方法をまとめます。

setupFilesAfterEnv は、各テストファイルが実行される前に必ず読み込まれるスクリプトを指定できる Jest の設定項目です。

例えば、モックの共通設定やグローバルな初期化処理をまとめたい場合に便利です。

手順

ここでは例として、nanoid を常にモックし、呼び出されるたびに異なるIDを返す設定を行います。

1. Jestの設定ファイルを編集

jest.config.js に以下を追加します。

module.exports = {
  setupFilesAfterEnv: ["<rootDir>/jest.setup.js"],
};

2. セットアップ用ファイルを作成

jest.setup.js を作成します。

export {};

let counter = 0;

jest.mock("nanoid", () => ({
  nanoid: jest.fn(() => {
    counter++;
    return `test_id_${counter}`;
  }),
}));

これで、すべてのテストファイルが実行される前にこの設定が読み込まれ、共通のモックが適用されます。

動作環境

  • Node.js: 24.13.0
  • TypeScript: 5.9.3
  • Jest: 30.2.0
  • @types/jest: 30.0.0
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?