How to set environment variables for serverless framework on jest tests

Viewed 303

I'm using Jest to make integration tests for my serverless framework service. Currently I have .env files specifying the environment variables and there is where I have my problem.

In my package.json i have :

...
"scripts": {
  ...
  "start": "npx sls offline start --env local --httpPort xxxx --port xxxx --lambdaPort xxxx"
}
...

When I call yarn start the service starts correctly reading from .env.local file. But when I call exec('yarn start') inside the beforeAll function (because I need to run the service to test the endpoints) the service starts with the configuration from the .env file and not .env.local.

I ran out of ideas of how to set the right variables, I have used jest setupFiles and tried to set the variable manually like process.env.ENV1='XX' but it did not work. Until now the only thing that worked out was to change my test script from jest to ENV1=X ENV2=Y ENV3=Z jest but it does not feel right.

1 Answers

There is a nice serverless plugin called "serverless-export-env", it exports all environment variables you set in serverless.yml, so that you can use them in jest, or invoke them locally.

After install the plugin, you need to put it at the first item of the plugins key, like:

plugins:
 - serverless-export-env
 - serverless-plugin-log-retention
 - serverless-offline

also specify the export settings, in custom

custom:
  export-env:
    filename: .env
    overwrite: false
    enableOffline: true

in this example, the environment variable are exported to a .env file in your project root.

Then, you can run serverless export-env to export the environment variable to .env.

In additional, you can automate this process by adding this command to your script in package.json, so that when you run npm test, it also run serverless export-env for you, for more, see this doc.

Hope it helps.

Related