I have an app that depends on environmental variables like:
const APP_PORT = process.env.APP_PORT || 8080;
and I would like to test that fo
Jest's setupFiles is the proper way to handle this, and you need not install dotenv
, nor use an .env
file at all, to make it work.
jest.config.js
:
module.exports = {
setupFiles: ["<rootDir>/.jest/setEnvVars.js"]
};
.jest/setEnvVars.js
:
process.env.MY_CUSTOM_TEST_ENV_VAR = 'foo'
That's it.
Expanding a bit on Serhan C.'s answer (https://stackoverflow.com/a/57944454/2708174)...
according to this blog https://tekloon.dev/using-dotenv-with-jest
you can include "dotenv/config"
directly in setupFiles
, without having to create and reference an external script that calls require("dotenv").config()
.
i.e., simply do
module.exports = {
setupFiles: ["dotenv/config"]
}
In ./package.json
:
"jest": {
"setupFiles": [
"<rootDir>/jest/setEnvVars.js"
]
}
In ./jest/setEnvVars.js
:
process.env.SOME_VAR = 'value';
In my opinion, it's much cleaner and easier to understand if you extract the retrieval of environment variables into a util (you probably want to include a check to fail fast if an environment variable is not set anyway), then you can just mock the util.
// util.js
exports.getEnv = (key) => {
const value = process.env[key];
if (value === undefined) {
throw new Error(`Missing required environment variable ${key}`);
}
return value;
};
// app.test.js
const util = require('./util');
jest.mock('./util');
util.getEnv.mockImplementation(key => `fake-${key}`);
test('test', () => {...});
Another option is to add it to the jest.config.js
file after the module.exports
definition:
process.env = Object.assign(process.env, {
VAR_NAME: 'varValue',
VAR_NAME_2: 'varValue2'
});
This way it's not necessary to define the ENV
variables in each .spec
file and they can be adjusted globally.
I think you could try this too:
const currentEnv = process.env;
process.env = { ENV_NODE: 'whatever' };
// test code...
process.env = currentEnv;
This works for me and you don't need module things