Quantcast
Channel: Node.jsタグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 8691

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

$
0
0

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

手順

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

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

$ npm install serverless jest jest-environment-serverless

プロジェクトの作成

$ npx serverless create --template aws-nodejs

設定

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

serverless.yml
service:sampleprovider:name:awsruntime:nodejs12.xfunctions:hello:handler:handler.helloenvironment:# これを読み込みます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 の読み込みconstenvVars=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' })を出力することができました。


Viewing all articles
Browse latest Browse all 8691

Trending Articles