Jest test not reading environment variables with dotenv

我们两清 提交于 2021-01-28 05:41:15

问题


I'm running a test on a function that calls for environment variables, I'm getting undefined. Solutions I tried and didn't work:

1/ add require('dotenv').config({path:'../.env'}) in my test file

2/ pass globals in package.json

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

3/ pass my variables in test command in package.json

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

4/ added an Object.assign in a beforeEach() in my test file

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

and got the error "Jest encountered an unexpected token"

5/ I created a jest.config.js file on the root

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

Most of these solution were suggested here: https://github.com/vuejs/vue-test-utils/issues/193 but none of it worked


回答1:


It works as expected using dotenv package to load environment variables.

E.g.

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

Most likely you need to get the path of the .env file through the path.resolve method.

Unit test results:

 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


来源:https://stackoverflow.com/questions/61781150/jest-test-not-reading-environment-variables-with-dotenv

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!