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.logprocess.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”},