Using .env files for unit testing with jest

Solution 1:

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"
  }
}

Solution 2:

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' });

Solution 3:

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.

Solution 4:

(2020) According to the dotenv doc, you shouldn't use dotenv in testing. If what you need is just 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', () => {
  expect(global.a).toBe(1);
});
  1. Use setup file:
// jest.config.json:
{
  "setupFiles": ['./jestSetup.js'],
}
// jestSetup.js:
process.env.FOO = 'FOO';
global.bar = 'bar';
// test:
test('env', () => {
  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 process.env are meant to be different in different deployments, which are not set 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.

Solution 5:

Just adding setupFiles: ['dotenv/config'] in jest.config.ts worked for me.

Useful article found here.

Full setup:


const jestConfig = {
    preset: 'ts-jest',
    globals: {
        'ts-jest': {
            tsconfig: '<rootDir>/tsconfig.spec.json',
        },
    },
    verbose: true,
    testMatch: ['<rootDir>/test/**/*(*.)+(test).+(tsx)'],
    setupFiles: [
        'dotenv/config'
    ],
    setupFilesAfterEnv: ['<rootDir>/test/setupTests.ts'],
    moduleFileExtensions: ['js', 'ts', 'tsx'],
    collectCoverage: true,
    coverageDirectory: 'target/coverage',
    collectCoverageFrom: [
        'src/**/*.tsx',
    ],
    moduleNameMapper: {
        '^.+\\.(css)$': 'identity-obj-proxy',
        '^.+\\.(png|svg|pdf|jpg|jpeg)$': 'jest-transform-stub'
    },
    transform: {
        '^.+\\.(js|jsx)$': 'babel-jest',
    },
    transformIgnorePatterns: ['[/\\\\]node_modules[/\\\\].+\\.(js|jsx|mjs)$'],
};

export default jestConfig;