Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/35.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 从process.env测试中生成的所有自定义变量_Node.js_Jestjs_Dotenv - Fatal编程技术网

Node.js 从process.env测试中生成的所有自定义变量

Node.js 从process.env测试中生成的所有自定义变量,node.js,jestjs,dotenv,Node.js,Jestjs,Dotenv,dotenv 8.2安装在我的nodejs 12.15应用程序中。.env文件位于app\u root/config/下,而dotenv是app的index.js文件中所必需的: require("dotenv").config(path: __dirname+"/config/.env"); 应用程序在应用程序根目录下的“node index.js”下运行良好。但是,当使用app rootnpm test下的jest 25.0进行测试时,db连接抛出错误,因为它调用db密码的process.

dotenv 8.2
安装在我的
nodejs 12.15
应用程序中。
.env
文件位于
app\u root/config/
下,而
dotenv
是app的
index.js
文件中所必需的:

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

应用程序在应用程序根目录下的“node index.js”下运行良好。但是,当使用app root
npm test
下的
jest 25.0
进行测试时,db连接抛出错误,因为它调用db密码的
process.env.db_PASSWORD
,但不返回任何内容。在测试环境中当console.log
process.env
时,我注意到自定义定义的变量完全丢失了。如何恢复测试环境中缺少的所有自定义变量

似乎当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"]
  }
}

以下内容也适用。在应用程序的根目录中创建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"

您的
index.js是否从测试代码中导入/需要?否,这是
package.json
中的
test
脚本:{“测试”:“跨环境节点_env=test jest--testTimeout=10000--watchAll--verbose”},