在JEST中使用dotenv路径

时间:2019-03-10 21:30:39

标签: node.js express jestjs dotenv

我正在尝试对Jest测试使用其他.env文件,但到目前为止,我无法使其正常工作。

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"
  }
}

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

我创建了一个配置文件夹来存储我的.env开发文件以避免这种情况,但是现在我的应用在运行Jest时不再使用env变量。

我在开发脚本中设置了配置路径,但对Jest无法做到这一点。

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

1 个答案:

答案 0 :(得分:2)

接受的答案让我很困惑,我不能让它工作,必须参考这个问题: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/dotenv 中的 debug 选项查看 .test.env 是否正确加载。