Jestでテスト用の環境変数を設定する際にハマったこと

2021.11.14

この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので、ご注意ください。

こんにちは、CX事業本部 IoT事業部の若槻です。

Jestは、JavaScriptのテスティングフレームワークです。Facebookが開発しています。

今回は、Jestでテスト用の環境変数を設定する際にハマったことについてです。

環境

$ npx jest --version
26.6.3

$ node -v
v14.5.0

$ npx tsc -v
Version 3.9.10

テスト用の環境変数が設定されない

下記のような環境変数を使用したコードがテスト対象です。

src/lambda/sampleHandler.ts

const envVal = process.env.SAMPLE_ENV as string;

export const handler = async () => {
  return `Hello, ${envVal}.`;
};

上記プロダクトコードに対する下記のテストコードを作成しました。テスト用の環境変数の設定処理はテストコード内で記載しています。

test/handler.test.ts

import { handler } from '../src/lambda/sampleHandler';

process.env.SAMPLE_ENV = 'Jest';

test('test', async () => {
  const response = await handler();

  expect(response).toEqual('Hello, Jest.');
});

しかしこのテストを実行すると、process.env.SAMPLE_ENVから取得される値がundefinedとなりテストが失敗してしまいます。

$ npx jest
 FAIL  test/handler.test.ts
  ✕ test (5 ms)

  ● test

    expect(received).toEqual(expected) // deep equality

    Expected: "Hello, Jest."
    Received: "Hello, undefined."

       6 |   const response = await handler();
       7 |
    >  8 |   expect(response).toEqual('Hello, Jest.');
         |                    ^
       9 | });
      10 |

      at Object.<anonymous> (test/handler.test.ts:8:20)

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 total
Snapshots:   0 total
Time:        0.845 s, estimated 1 s
Ran all test suites.

解決

環境変数の設定処理はでプロダクトコードをimportする手前で記載する必要がありました。なぜならimportにより読み込まれるモジュール内での他のモジュールや環境変数の解決はimport時に行われるからです。よってimport時に環境変数が未設定であればundefindとなっていまいます。

そこで下記のようにテスト対象のプロダクトコード(モジュール)のimportの手前で環境変数を設定する処理を記載します。

test/handler.test.ts

process.env.SAMPLE_ENV = 'Jest';

import { handler } from '../src/lambda/sampleHandler';

test('test', async () => {
  const response = await handler();

  expect(response).toEqual('Hello, Jest.');
});

テストを実行すると成功しました。テスト用環境変数が指定できていますね。

$ npx jest 
 PASS  test/handler.test.ts
  ✓ test (1 ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        0.85 s, estimated 1 s
Ran all test suites.

おわりに

Jestでdotenvを使わずにテスト用の環境変数を設定する方法を確認してみました。

タネが分かれば単純なのですが、最初は分からずに結構ハマりました。よく考えたら以前投稿した下記エントリと同じことにハマっていますね。

以上