test process.env with Jest

Tomasz Mularczyk picture Tomasz Mularczyk · Dec 30, 2017 · Viewed 100.4k times · Source

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:

  • APP_PORT can be set by node env variable.
  • or that an 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?

Answer

Tomasz Mularczyk picture Tomasz Mularczyk · Dec 31, 2017

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.