I have an application that relies on Jest set environment variables, such as:
const APP_PORT = process.env.APP_PORT || 8080;
I want to test scenarios such as:
Ensuring APP_PORT can be set by a Node.js environment variable.
Verifying that an Express.js application is running on the port specified by process.env.APP_PORT.
How can I achieve this with Jest? Should I set these process.env variables before each test, or is it better to mock them somehow?
You can manage environment variables in Jest tests effectively by following this approach:
Use jest.resetModules() before each test to clear the cache, and make a copy of the current process.env to restore it later. This ensures that each test runs with a clean environment.
describe('environmental variables', () => {
const OLD_ENV = process.env;
beforeEach(() => {
jest.resetModules(); // Clear the module cache
process.env = { ...OLD_ENV }; // Copy current environment variables
});
afterAll(() => {
process.env = OLD_ENV; // Restore original environment variables
});
test('should receive process.env variables', () => {
// Set specific environment variables for this test
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 want to load environment variables before running the Jest tests, you should use the setupFiles option in your Jest configuration. This allows you to set up environment variables globally for all tests.
// jest.config.js
module.exports = {
setupFiles: ['<rootDir>/setupTests.js']
};
And in setupTests.js, you can define your environment variables:
process.env.NODE_ENV = 'test';
process.env.API_URL = 'https://test-api.com/';
Using this methods, you can effectively manage and test the behavior of your application with different environment variables.
Another option is to define environment variables directly in the jest.config.js file. After the module.exports definition, you can add:
// jest.config.js
module.exports = {
// existing configuration options
};
// Set environment variables globally
process.env = Object.assign(process.env, {
VAR_NAME: 'varValue',
VAR_NAME_2: 'varValue2'
});
This approach allows you to set environment variables globally for all tests, eliminating the need to define them in each .spec file and making it easier to adjust them as needed.