【问题标题】:using dotenv path with JEST使用带有 JEST 的 dotenv 路径
【发布时间】:2019-08-01 05:18:24
【问题描述】:

我正在尝试为我的 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 dev 文件以避免这种情况,但现在我的应用在运行 Jest 时不使用 env var。

我在我的开发脚本中设置了一个配置路径,但我不能对 Jest 做同样的事情。

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

【问题讨论】:

    标签: node.js express jestjs dotenv


    【解决方案1】:

    接受的答案让我很困惑,我无法让它工作,必须参考这个问题: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 是否正确加载。

    【讨论】:

      【解决方案2】:

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

      在您的dotenv/config.js 文件中,该文件用作第一行开玩笑的设置文件,添加以下内容:

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

      【讨论】:

      • 我在存储 config.path 的位置创建了一个 file.js,并创建了一个 "jest": { "testEnvironment": "node", "setupFilesAfterEnv": ["/tests/ dotenv-config.js"] },运行这个文件,看起来它正在工作。感谢和快乐的代码!
      • 嘿。我面临同样的问题。想要使用不同的 env 文件进行开玩笑的单元测试。但正如您在回答中提到的在 dotenv/config.js 文件中添加绝对路径。但我没有任何 dotenv/config.js 文件。我的 .env 文件位于根目录中。我在 app.js 文件中调用了 "require("dotenv").config()",这是快速设置,我通过 index.js 文件运行服务器。我的 test.env 文件也在根目录中。你能帮忙吗?
      猜你喜欢
      • 1970-01-01
      • 2021-01-24
      • 1970-01-01
      • 1970-01-01
      • 2020-01-10
      • 2018-12-07
      • 1970-01-01
      • 1970-01-01
      • 2019-11-19
      相关资源
      最近更新 更多