Search code examples
node.jsintegration-testingjestjsserverless-framework

How to get environment variables defined in serverless.yml in tests


I am using the serverless framework for running lambda functions on AWS.

In my serverless.yml there are environment variables that are fetched from SSM.

When I write integration tests for the code, I need the code to have the environment variables and I can't find a good way to do this.

I don't want to duplicate all the variables definitions just for the tests, they are already defined in the serverless.yml. Also, some are secrets and I can't commit them to source conrol, so I would have to also repeat them in the ci environment.

Tried using the serverless-jest-plugin but it is not working and not well maintained.

Ideas I had for solutions:

  1. Make the tests exec sls invoke - this will work but would mean that the code cannot be debugged, I won't know the test coverage, and it will be slow.
  2. Parse the serverless.yml myself and export the env variables - possible but rewriting the logic of pulling the SSM variables just for tests seems wrong.

Any ideas?


Solution

  • The solution we ended up using is a serverless plugin called serverless-export-env.

    After adding this plugin you can run serverless export-env to export all the resolved environment variables to an .env file. This resolves ssm parameters correctly and made integration testing much simpler for us.

    BTW, to get the environment variables set from the .env file use the the dotenv npm package.

    Credit to grishezz for finding the solution