Use .env variables in Jest & NodeJS testing
If you want to test a a NodeJS application with Jest, you often need to set local environment variables. Usually these variables are set on the server when deploying your application, but they’re not available locally for testing.
A common pattern is to use a .env
file with all variables for local development and testing. However, to load these variables before you run your test can be tricky.
The magic line is:
Here is the core again for you to copy/paste:
node -r dotenv/config $(which jest) --watchAll
To be more precise, these are the three magic steps:
- Add the
dotenv
module (e.g.yarn add -D dotenv
), if you haven’t already. - Set your variables in a file named
.env
- Add a test script to your
package.json
:"test": "node -r dotenv/config $(which jest) --watchAll"
Of course you can skip the --watchAll
or add any other params for jest
if you like. The tricky part is to load the dotenv config first and then call jest in a way that it finds it on your system (hence the $(which jest)
).
I hope this helps for your NodeJS/Jest testing with env variables.