【问题标题】:All custom defined variables mssing in test from process.envprocess.env 的测试中缺少所有自定义变量
【发布时间】:2020-08-30 03:52:03
【问题描述】:

dotenv 8.2 安装在我的nodejs 12.15 应用程序中。 .env 文件位于app_root/config/ 下,而应用程序的index.js 文件中需要dotenv

require("dotenv").config(path: __dirname+"/config/.env");

应用程序的根子目录中的“node index.js”运行良好。但是,当在应用程序根npm test 下使用jest 25.0 进行测试时,数据库连接会引发错误,因为它调用process.env.DB_PASSWORD 以获得数据库密码并且什么都不返回。当 console.log process.env 在测试环境中时,我注意到自定义定义的变量完全丢失了。如何恢复测试环境中缺少的所有自定义变量?

【问题讨论】:

  • 您的index.js 是否从您的测试代码中导入/需要?
  • 不,这是package.json 中的test 脚本: "scripts": { "test": "cross-env NODE_ENV=test jest --testTimeout=10000 --watchAll --verbose " },

标签: node.js jestjs dotenv


【解决方案1】:

似乎在 Jest 运行时,它不包括您的 index.js,其中需要 dotenv 变量。

使用 .env 变量运行 jest 的选项很少:

// npm run script
{
  "scripts": {
    "test": "jest --setupFiles dotenv/config"
  }
}

// jest.config.js
module.exports = {
  setupFiles: ["dotenv/config"],
}

// jest in package.json
{
  "name": "my-package",
  "jest": {
    "setupFiles": ["dotenv/config"]
  }
}

【讨论】:

    【解决方案2】:

    以下也适用。在应用的根目录下创建一个 jest.config.js:

    require('dotenv').config({path: process.cwd() +'/config/.env'});
    
    module.exports = {
        verbose:true,
        testTimeout:10000
    }
    

    并在 package.json 中添加脚本:

    "test": "cross-env NODE_ENV=test jest --config=./jest.config.js --watchAll"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-03
      • 2019-09-11
      • 2021-07-02
      • 1970-01-01
      • 2023-04-02
      • 2018-04-19
      • 1970-01-01
      • 2021-10-23
      相关资源
      最近更新 更多