8

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

Community
  • 1
  • 1
Allan Juan
  • 2,048
  • 1
  • 18
  • 42

2 Answers2

2

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

Allan Juan
  • 2,048
  • 1
  • 18
  • 42
  • I already have it in my root folder. What should be done for this case? – Tanishq Vyas Apr 13 '22 at 05:46
  • @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/ – ronak patel Jun 15 '22 at 08:26
  • You can use the path argument, like this: `require('dotenv').config({ path: 'src/.env' })`. [Docs](https://www.npmjs.com/package/dotenv) – Allan Juan Jun 16 '22 at 11:41
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.

winwiz1
  • 2,906
  • 11
  • 24
  • 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. – Allan Juan Apr 26 '20 at 12:55
  • 1
    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`. – winwiz1 Apr 26 '20 at 13:37