using dotenv path with JEST

老子叫甜甜 提交于 2020-03-05 05:36:06

问题


I'm trying to use a different .env file for my Jest tests, but so far I couldn't make it work.

package.json:

{
  "name": "task-manager",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "module": "main.js",
  "scripts": {
    "start": "node -r esm src/index.js",
    "dev": "nodemon -r esm -r dotenv/config src/index.js dotenv_config_path=./config/.env",
    "test": "jest --setupFiles dotenv/config --watch"
  },
  "jest": {
    "testEnvironment": "node"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@sendgrid/mail": "^6.3.1",
    "bcryptjs": "^2.4.3",
    "dotenv": "^6.2.0",
    "esm": "^3.2.10",
    "express": "^4.16.4",
    "jest": "^24.3.1",
    "jsonwebtoken": "^8.5.0",
    "mongodb": "^3.1.13",
    "mongoose": "^5.4.17",
    "multer": "^1.4.1",
    "sharp": "^0.21.3",
    "supertest": "^4.0.0",
    "validator": "^10.11.0"
  },
  "devDependencies": {
    "@babel/core": "^7.3.4",
    "@babel/preset-env": "^7.3.4",
    "babel-jest": "^24.3.1"
  }
}

Every time I ran my npm test, the MONGODB_URL used was the stored in my .env file, instead of my test.env file

I created a config folder to store my .env dev file to avoid this, but now my app doesn't use the env vars when I run the Jest.

I setup a config path in my dev script, but I couldn't do the same with Jest.

Expected behavior: I just want to use a different MONGODB_URL for my tests with Jest.


回答1:


You have to explicitly specify which .env should be used by the dotenv package.

In your dotenv/config.js file which is used as a setup file for jest on the very first line add this:

require('dotenv').config({ path: './test.env' })



来源:https://stackoverflow.com/questions/55092607/using-dotenv-path-with-jest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!