I'm writing tests for my Express project, but when I run the test script my environment variables are not loaded.
In other threads people suggested using --setupFiles dotenv/config
, which I did, but unfortunately it didn't work. I tried both adding it to my test script and to a jest.config.js
file, but none worked. Does someone have any hint on how to fix this?
Context
This is how I setup jest on package.json
:
"scripts": {
"test": "jest --watchAll --setupFiles dotenv/config"
},
"jest": {
"testEnvironment": "node"
},
At the top of my app.js
file, I load my environment variables with
require('dotenv').config();
And this is my folder structure:
I'm writing tests for my Express project, but when I run the test script my environment variables are not loaded.
In other threads people suggested using --setupFiles dotenv/config
, which I did, but unfortunately it didn't work. I tried both adding it to my test script and to a jest.config.js
file, but none worked. Does someone have any hint on how to fix this?
Context
This is how I setup jest on package.json
:
"scripts": {
"test": "jest --watchAll --setupFiles dotenv/config"
},
"jest": {
"testEnvironment": "node"
},
At the top of my app.js
file, I load my environment variables with
require('dotenv').config();
And this is my folder structure:
Share Improve this question edited Jun 20, 2020 at 9:12 CommunityBot 11 silver badge asked Apr 25, 2020 at 21:40 Allan JuanAllan Juan 2,6323 gold badges26 silver badges54 bronze badges2 Answers
Reset to default 2Fixed it by moving .env
file from the src/
folder to the root folder.
Have a look at this project. It uses both cross-env and dotenv to pass env variables to Express:
cross-env NODE_ENV=production node -r dotenv/config ./build/srv/main.js
Alternatively the sibling project uses cross-env only.
Disclosure: I'm the author of the above 'crisp' projects.