1

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.

4

2 回答 2

5

接受的答案让我很困惑,我不能让它工作,必须参考这个问题:Using .env files for unit testing with jest

以下是我如何使它工作:

我的文件结构

-src/
-tests/
------/dotenv-config.js
-jest.config.js
-.test.env
-.env

jest.config.js

module.exports = {
  setupFiles: [
    "<rootDir>/tests/dotenv-config.js"
  ],
  roots: ['<rootDir>/src'],
  testEnvironment: 'node',
  testMatch: ['**/*.test.(ts|tsx)'],
  collectCoverageFrom: ['src/**/*.{ts,tsx}'],
  preset: 'ts-jest',
};

dotenv-config.js

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

使用https://www.npmjs.com/package/dotenvdebug中的选项来查看是否正确加载。.test.env

于 2021-05-26T07:46:37.620 回答
2

您必须明确指定包.env应该使用哪个dotenv

dotenv/config.js第一行用作 jest 设置文件的文件中,添加以下内容:

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

于 2019-03-10T21:40:09.257 回答