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' }
)を出力することができました。