将 dotenv 路径与 JEST 一起使用

Dan*_*l C 4 node.js express jestjs dotenv

我正在尝试使用不同的 .env 文件进行 Jest 测试,但到目前为止我无法使其工作。

包.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"
  }
}
Run Code Online (Sandbox Code Playgroud)

每次我运行 npm 测试时,使用的 MONGODB_URL 存储在我的 .env 文件中,而不是我的 test.env 文件中

我创建了一个 config 文件夹来存储 .env dev 文件以避免这种情况,但现在我的应用程序在运行 Jest 时不使用环境变量。

我在我的开发脚本中设置了一个配置路径,但我无法对 Jest 执行相同的操作。

预期行为:我只想使用不同的 MONGODB_URL 进行 Jest 测试。

van*_*102 7

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

这是我能够使其发挥作用的方法:

我的文件结构

-src/
-tests/
------/dotenv-config.js
-jest.config.js
-.test.env
-.env
Run Code Online (Sandbox Code Playgroud)

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',
};
Run Code Online (Sandbox Code Playgroud)

dotenv-config.js

-src/
-tests/
------/dotenv-config.js
-jest.config.js
-.test.env
-.env
Run Code Online (Sandbox Code Playgroud)

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