我遇到了一个问题,我导入的env变量在函数范围之外不可用,我想知道这是有意的设计还是我做错了什么例如我的设置如下所示/src/index.test.js//require configconst 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.jsconst myVar = process.env.myVarconsole.log(process.env.myVar) //<= will be undefinedasync 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测试问题
1 回答

jeck猫
TA贡献1909条经验 获得超7个赞
我想我明白了。显然我的jest.config.js
文件从未被读取。因此, 或 都没有setupFiles
运行setupFilesAfterEnv
。
这是因为我有我jest.config.js
的<rootDir>/jest
,因为我在嵌套文件夹中调用jest
它从未运行。将其移出根目录解决了我的问题。我的所有文件都根据需要运行
添加回答
举报
0/150
提交
取消