9

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:

project's folder structure: a source folder with several folders inside it, including a test folder. Outside src are app.js, routes.js, .env, package.json and some other files

2 Answers 2

2

Fixed it by moving .env file from the src/ folder to the root folder.

Sign up to request clarification or add additional context in comments.

3 Comments

I already have it in my root folder. What should be done for this case?
@Allan Juan, This works perfectly fine, is there any solution for dotenv to pickup .env file anywhere in the project structure, like in my case it is present in src/
You can use the path argument, like this: require('dotenv').config({ path: 'src/.env' }). Docs
0

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.

2 Comments

Isn't crossenv intended to fix platform compatibility problems? Correct me if I'm wrong, I'm just not seeing how this could help. The env variables are being loaded when I run the server, they are not loaded only when I run tests.
This entry (from the scripts section of package.json): "test": "cross-env NODE_ENV=test jest" will load env variable(s) only when you run tests by executing yarn test.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.