问题
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