Search code examples
node.jsexpressjestjsdotenv

using dotenv path with JEST


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.


Solution

  • 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' })