Using .env files for unit testing with jest

Your top config path using ./ is relative from the point of injection, it's likely your test suite might be inside a folder named test which causes it to not be found when running your unit tests. dotenv.config(); Uses global injection strategy which is similar to absolute pathing.


You can load the env files for all your tests like this. The setup file will be executed once per each test file that is loaded.

jest.config.js:

module.exports = {
    setupFiles: ["<rootDir>/test/setup-tests.ts"],
};

test/setup-tests.ts:

import dotenv from 'dotenv';

dotenv.config({ path: './config.env.test' });

(2020) According to the docs of dotenv, you shouldn't use dotenv in testing (more on that later). If you need some globally available values, there are multiple ways to set it up, for instance:

  1. setup global variables with jest:
// jest.config.json:
{
  "globals": {
    "a": 1
  }
}
// test:
test('global vars', () => {
  expect(global.a).toBe(1);
});
  1. Use a setup file:
// jest.config.json:
{
  "setupFiles": ['./jestSetup.js'],
}
// jestSetup.js:
process.env.FOO = 'FOO';
global.bar = 'bar';
// test:
test('env vars and global vars', () => {
  expect(process.env.FOO).toBe('FOO');
  expect(global.bar).toBe('bar');
});

  1. use globalSetup and globalTeardown: Very similar to 2.

The reason against using dotenv is that values in process.env are meant to be different in different deployments, which are set by the environment, not by you. If a variable doesn't change in different environments, then it's not an environmental variable, it's just a global variable that you set manually. The dotenv doc further points to the 12 factor app which is a good read.


None of these worked for me, but I found a great article on configuring dotenv by default in Jest in the package.json:

{
  "scripts": {
    "test": "jest --setupFiles dotenv/config"
  }
}