最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Jest doesn't load environment variables (even with --setupFiles dotenvconfig) - Stack Overflow

programmeradmin7浏览0评论

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 badges
Add a ment  | 

2 Answers 2

Reset to default 2

Fixed 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.

发布评论

评论列表(0)

  1. 暂无评论