LoginSignup
1
0

More than 3 years have passed since last update.

Jest実行時にserverless.ymlの環境変数を読み込む

Last updated at Posted at 2020-01-24

jest-environment-serverless を利用してserverless.ymlから環境変数を読み込みます。
.envを読み込む以外の方法を試してみたかった)

手順

パッケージのインストール

必要なパッケージをインストールします。

$ npm install serverless jest jest-environment-serverless

プロジェクトの作成

$ npx serverless create --template aws-nodejs

設定

serverless.ymlに読み込む環境変数の名称と値を記述します。

serverless.yml
service: sample

provider:
  name: aws
  runtime: nodejs12.x

functions:
  hello:
    handler: handler.hello
    environment:

      # これを読み込みます
      SAMPLE_VALUE: Sample

package.jsonにjestの設定を追加します。

package.json
{
  :
  "jest": {
    "testEnvironment": "jest-environment-serverless",
  }
}

テストの作成

環境変数を console.log で出力する処理を記述します。

__test__/handler.spec.js
describe('Sample', () => {
  it('check env', () => {

    // 表示
    console.log(process.env.SAMPLE_VALUE);

    expect('');
  });
});

テストの実行

$ npx jest
 PASS  __test__/handler.spec.js (10.71s)
  Sample
    ✓ check env (67ms)

  console.log __test__/handler.spec.js:5
    Sample

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

環境変数の値(Sample)を読み込むことができました。

おまけ

環境変数の名称と値をAPIから取得することもできます。

__test__/handler.spec.js
describe('Sample', () => {
  it('check env', () => {

    // serverless.yml の functions.hello.environment の読み込み
    const envVars = ServerlessWrapper.getEnv('hello');

    // 出力
    console.log(envVars);

    expect('');
  });
});
$ npx jest
 PASS  __test__/handler.spec.js (8.714s)
  Sample
    ✓ check env (68ms)

  console.log __test__/handler.spec.js:8
    { SAMPLE_VALUE: 'Sample' }

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

環境変数の名称と値({ SAMPLE_VALUE: 'Sample' })を出力することができました。

1
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
1
0