This is a walk through of how to use Serverless Framework Pro params with AWS Lambda environment variables utilizing a plugin called serverless-export-env with Jest testing.
- Install -
npm i
If you want to automatically pull in your serverless.yml
environment variables and use those for your Jest unit testing, then you're going to need a few things.
-
Create an Org
-
Create an App called,
sls-jest
-
Create a Profile called,
dev
-
Create a
dev
profile param called,COUNT_CHARS_API_KEY
with a value ofxyz
This is only required to setup the connection to Serverless Framework Pro.
- Deploy -
sls deploy --stage dev --region us-west-2 -v
-
Install -
npm install --save-dev arabold/serverless-export-env
-
Generate the
.env
file -sls export-env
Now that we have the .env
file ready. We need too..
-
Install dotenv -
npm i --save-dev dotenv
We only need a single line here.
require("dotenv").config()
We only need to import the index.js
file, call index.handler({})
,
then check if the body.message
equals API_KEY-${process.env.API_KEY}
which in our case should be API_KEY-xyz
.
const index = require('../index');
test('check string matches with env var', async () => {
const result = await index.handler({});
let body = JSON.parse(result.body);
// we set the environment variable as xyz and are checking
// to see if that comes back correctly
expect(body.message).toBe('API_KEY-xyz');
});
Now that we have everything setup we can run npm run jest
.