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 for example:
express
app is running on the port set with process.env.APP_PORT
How can I achieve this with Jest? Can I set these process.env
variables before each test or should I mock it somehow maybe?
The way I did it can be found in this SO question.
It is important to resetModules before each test and then dynamically import the module inside the test:
describe('environmental variables', () => {
const OLD_ENV = process.env;
beforeEach(() => {
jest.resetModules() // most important - it clears the cache
process.env = { ...OLD_ENV }; // make a copy
});
afterAll(() => {
process.env = OLD_ENV; // restore old env
});
test('will receive process.env variables', () => {
// set the variables
process.env.NODE_ENV = 'dev';
process.env.PROXY_PREFIX = '/new-prefix/';
process.env.API_URL = 'https://new-api.com/';
process.env.APP_PORT = '7080';
process.env.USE_PROXY = 'false';
const testedModule = require('../../config/env').default
// ... actual testing
});
});
If you look for a way to load env values before running the Jest look for the answer below. You should use setupFiles for that.