【问题标题】:Jest test not reading environment variables with dotenv玩笑测试不使用 dotenv 读取环境变量
【发布时间】:2020-08-30 00:44:33
【问题描述】:

我正在对一个调用环境变量的函数进行测试,但结果未定义。 我尝试过但无效的解决方案:

1/ 在我的测试文件中添加require('dotenv').config({path:'../.env'})

2/ 在 package.json 中传递全局变量

"jest": {
    "globals": {
      "USER_ENDPOINT":"xxx",
      "USER_KEY":"xxx"
  }
}

3/ 在 package.json 中的 test 命令中传递我的变量

"test": "USER_ENDPOINT:xxx USER_KEY:xxx jest --watchAll --detectOpenHandles"

4/ 在我的测试文件的 beforeEach() 中添加了一个 Object.assign

beforeEach(() => {
        process.env = Object.assign(process.env, {USER_ENDPOINT:"xxx", USER_KEY:"xxx" });
});

并收到错误“Jest 遇到了意外的令牌”

5/ 我在根目录下创建了一个 jest.config.js 文件

require('dotenv').config({path:'./.env'});
module.exports = {
    globals: {
        USER_ENDPOINT:"xxx", 
        USER_KEY:"xxx"
    }
};

这里建议了大部分解决方案: https://github.com/vuejs/vue-test-utils/issues/193 但都没有成功

【问题讨论】:

    标签: node.js jestjs dotenv


    【解决方案1】:

    它使用dotenv包加载环境变量按预期工作。

    例如

    index.test.js:

    const path = require('path');
    
    require('dotenv').config({ path: path.resolve(__dirname, './.env') });
    
    describe('61781150', () => {
      it('should pass', () => {
        expect(process.env.USER_ENDPOINT).toBe('http://localhost:3000');
        expect(process.env.USER_KEY).toBe('abc123');
      });
    });
    

    .env:

    USER_ENDPOINT=http://localhost:3000
    USER_KEY=abc123
    

    您很可能需要通过path.resolve 方法获取.env 文件的路径。

    单元测试结果:

     PASS  stackoverflow/61781150/index.test.js (8.236s)
      61781150
        ✓ should pass (2ms)
    
    Test Suites: 1 passed, 1 total
    Tests:       1 passed, 1 total
    Snapshots:   0 total
    Time:        9.264s, estimated 11s
    

    【讨论】:

    • require("dotenv").config("./.env") 也可以。
    猜你喜欢
    • 2022-09-07
    • 1970-01-01
    • 1970-01-01
    • 2021-01-24
    • 2020-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-20
    相关资源
    最近更新 更多