我遇到了一个问题,我导入的env变量在函数范围之外不可用,我想知道这是有意的设计还是我做错了什么
例如我的设置如下所示
/src/index.test.js
//require config
const config = require('../config.json');
const myFunc = require('./index.js');
beforeEach(async () =>
{
//set env vars
process.env = Object.assign(process.env, config);
})
test('sample', async () =>
{
//call function
await myFunc();
expect(somethingMeaninful).toBeCalledTimes(1);
})
然后我的实际代码如下所示
src/index.js
const myVar = process.env.myVar
console.log(process.env.myVar) //<= will be undefined
async function myFunc()
{
console.log(process.env.myVar) //<= will show my value from config.json file
return somethingMeaninful();
}
exports.myFunc = myFunc();
因此,由于myVar是在函数外部声明的,因此它是未定义的。我尝试在 process.env 上作为一个整体在我的 func 内部和外部执行 console.log() ,并且在它外部将具有所有默认值,但在它内部也将具有默认值 + 我的配置值。真的很困惑如何以及为什么会发生这种情况。当我正常运行代码时,这些变量不是未定义的,但在测试期间是未定义的......
这个链接在这里也提到了这个问题以及 github vue测试问题
jeck猫
相关分类