【发布时间】:2021-03-11 08:04:35
【问题描述】:
我遇到了一个问题,我导入的 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 是在函数外部声明的,因此它是未定义的。
我尝试在我的 func 内部和外部对 process.env 执行 console.log() ,外部将具有所有默认值,但内部也将具有默认值 + 我的配置值。真的很困惑如何以及为什么会发生这种情况。当我正常运行我的代码时,这些变量不是未定义的,但在测试期间是未定义的......
这个链接在这里也提到了这个问题 github vue testing issue
【问题讨论】:
标签: javascript node.js unit-testing jestjs