【问题标题】:Process.env Variables Not Available Outside of Function During Jest Testing在 Jest 测试期间,Process.env 变量在函数之外不可用
【发布时间】: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


    【解决方案1】:

    我想我明白了。显然我的jest.config.js 文件从未被读取过。因此,setupFilessetupFilesAfterEnv 都没有运行。

    这是因为我在&lt;rootDir&gt;/jest 中有我的jest.config.js,因为我在名为jest 的嵌套文件夹中它从未运行过。将它从那里移到根目录解决了我的问题。我的所有文件都在必要时运行

    【讨论】:

      猜你喜欢
      • 2019-09-11
      • 2018-06-10
      • 2023-04-02
      • 2023-01-26
      • 2019-10-26
      • 1970-01-01
      • 2020-04-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多