336

I have an application 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 a Node.js environment variable.
  • or that an Express.js application 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?

2
  • yes you can set the environment variable Commented Dec 30, 2017 at 12:26
  • @Deep AFAIK I can set them only once in jest config. Commented Dec 30, 2017 at 12:56

17 Answers 17

435

The way I did it can be found in this Stack Overflow question.

It is important to use 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 environment
  });

  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 environment values before running the Jest look for the answer below. You should use setupFiles for that.

9
  • 2
    Please provide the full response
    – Yves M.
    Commented Aug 9, 2018 at 9:32
  • 1
    Worked great for me. If you need to use a default export you can do: const testedModule = require('../../config/env').default;
    – Aziz
    Commented Aug 9, 2018 at 19:14
  • 13
    in case this doesn't work for you, make sure when you are reading the env variable in your actual code, you are reading it in a function/limited scope rather than having a global variables pointed to process.env.YOUR_VARIABLE. Commented Feb 18, 2019 at 20:51
  • 1
    @learner if I remember correctly delete process.env.NODE_ENV; is just a leftover from my code and shouldn't matter in your case. What matters is that you call jest.resetModules() before the test and after it you restore initial process.env object (OLD_ENV) Commented Jun 28, 2020 at 11:33
  • 5
    @MEMark you need to create a copy in order not to mutate the original object (which later you need to restore) Commented Sep 1, 2020 at 6:16
300

Jest's setupFiles is the proper way to handle this, and you need not install dotenv, nor use an .env file at all, to make it work.

jest.config.js:

module.exports = {
  setupFiles: ["<rootDir>/.jest/setEnvVars.js"]
};

.jest/setEnvVars.js:

process.env.MY_CUSTOM_TEST_ENV_VAR = 'foo'

That's it.

8
  • 5
    I tried most of the solutions proposed in this thread and this is the one that worked for me.
    – guergana
    Commented Jan 13, 2021 at 13:02
  • This is the best solution! For my production apps I'm using this to set global mocks too. For example if you're dealing with momentjs you can set the timezone here so your snapshots won't fail when changing timezone.
    – icosmin
    Commented Jul 6, 2021 at 6:53
  • Amazing, that's the simplest option to handle environment variables in jest! Commented Aug 5, 2021 at 17:20
  • 4
    I'm not sure what people are happy about, as it clearly doesn't work for any real use case where process.env is read by modules at the import/require time.
    – user64204
    Commented Apr 19, 2022 at 15:50
  • 20
    This doesn't really work if you need to adjust environment variables on a per-test-case basis...
    – jrista
    Commented May 24, 2022 at 17:43
77

Another option is to add it to the jest.config.js file after the module.exports definition:

process.env = Object.assign(process.env, {
  VAR_NAME: 'varValue',
  VAR_NAME_2: 'varValue2'
});

This way it's not necessary to define the environment variables in each .spec file and they can be adjusted globally.

1
  • 2
    This is a great solution for when you want to test different environment variables per test. Most of the other answers I've come across have been at a global level. Thanks!
    – lizacodes
    Commented May 2, 2022 at 3:45
55

In ./package.json:

"jest": {
  "setupFiles": [
    "<rootDir>/jest/setEnvVars.js"
  ]
}

In ./jest/setEnvVars.js:

process.env.SOME_VAR = 'value';

4
  • 2
    Probably the easiest way I've seen. No need to install the dotenv package.
    – MattC
    Commented Apr 13, 2020 at 13:49
  • this won't work with Create-React-App github.com/facebook/create-react-app/issues/5325 for that, env variables to be used in test need to be added in .env.test.local file
    – aixecador
    Commented Jan 9, 2021 at 0:50
  • This didnt work for me with vue-test-utils
    – guergana
    Commented Jan 13, 2021 at 12:58
  • 1
    This didnt work for me because, my env var needed to be initialized before the module loads. So I ended up splitting it in two separate files and define the var before loading the module and that worked. Not a pretty way but work. Commented May 24, 2021 at 16:22
42

You can use the setupFiles feature of the Jest configuration. As the documentation said that,

A list of paths to modules that run some code to configure or set up the testing environment. Each setupFile will be run once per test file. Since every test runs in its own environment, these scripts will be executed in the testing environment immediately before executing the test code itself.

  1. npm install dotenv --save-dev dotenv that uses to access environment variable.

  2. Create your .env file to the root directory of your application and add this line into it:

    #.env
    APP_PORT=8080
    
  3. Create your custom module file as its name being someModuleForTest.js and add this line into it:

    // someModuleForTest.js
    require("dotenv").config()
    
  4. Update your jest.config.js file like this:

    module.exports = {
      setupFiles: ["./someModuleForTest"]
    }
    
  5. You can access an environment variable within all test blocks.

    test("Some test name", () => {
      expect(process.env.APP_PORT).toBe("8080")
    })
    
1
  • 1
    Nice answer! This is a such a clean approach but instead use npm install dotenv --save-dev since it doesn't need to be apart of you application. For simple projects I just skip step 4. and have step 3 at the top of my test file(s) instead of creating a custom module. Commented Mar 10, 2023 at 15:53
27

Expanding a bit on Serhan C.'s answer...

According to the blog post How to Setup dotenv with Jest Testing - In-depth Explanation, you can include "dotenv/config" directly in setupFiles, without having to create and reference an external script that calls require("dotenv").config().

I.e., simply do

module.exports = {
    setupFiles: ["dotenv/config"]
}
3
  • Only this that runs in my side
    – fsevenm
    Commented Dec 17, 2020 at 8:06
  • 2
    The best solution here! It's worth mentioning, that in jest.config.ts you can use it under the globalSetup key instead of the setupFiles key, if you want it to run once before all tests, and not resetting them before every test file
    – A-S
    Commented May 13, 2021 at 9:36
  • This doesn't work.
    – Rahul
    Commented Jun 20 at 12:03
13

In my opinion, it's much cleaner and easier to understand if you extract the retrieval of environment variables into a utility (you probably want to include a check to fail fast if an environment variable is not set anyway), and then you can just mock the utility.

// util.js
exports.getEnv = (key) => {
    const value = process.env[key];
    if (value === undefined) {
      throw new Error(`Missing required environment variable ${key}`);
    }
    return value;
};

// app.test.js
const util = require('./util');
jest.mock('./util');

util.getEnv.mockImplementation(key => `fake-${key}`);

test('test', () => {...});
1
  • I feel like this is the only way to test check like: isProd ? /*something*/ : /*something else*/, for time when you want to send an email for example. Or when relying on external services that do not have a proper test env.
    – Sufiane
    Commented May 11, 2021 at 16:25
10

In test file:

const APP_PORT = process.env.APP_PORT || 8080;

In the test script of ./package.json:

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

In ./env:

APP_PORT=8080
1
  • 1
    If you want to use a dotenv file with a name other than .env, e.g., .env.test, you can set it via env var: DOTENV_CONFIG_PATH=./.env.test jest --setupFiles dotenv/config Commented Sep 29, 2023 at 18:40
6

Depending on how you can organize your code, another option can be to put the environment variable within a function that's executed at runtime.

In this file, the environment variable is set at import time and requires dynamic requires in order to test different environment variables (as described in this answer):

const env = process.env.MY_ENV_VAR;

const envMessage = () => `MY_ENV_VAR is set to ${env}!`;

export default myModule;

In this file, the environment variable is set at envMessage execution time, and you should be able to mutate process.env directly in your tests:

const envMessage = () => {
  const env = process.env.MY_VAR;
  return `MY_ENV_VAR is set to ${env}!`;
}

export default myModule;

Jest test:

const vals = [
  'ONE',
  'TWO',
  'THREE',
];

vals.forEach((val) => {
  it(`Returns the correct string for each ${val} value`, () => {
    process.env.MY_VAR = val;

    expect(envMessage()).toEqual(...
5

you can import this in your jest.config.js

require('dotenv').config()

this work for me

5

To build upon @HenryTipantuña's suggestion is to import dotenv in your jest.config.js and use a .env.test file in the config path

require('dotenv').config({
  path: '.env.test'
})
1
  • This worked for me plus module.exports = {setupFiles: ['dotenv/config']} Commented Jun 19, 2023 at 20:37
4

All the above methods work if you're using require("dotenv").config within the jest.config.js file, a NodeJS application without TypeScript such as what Jialx or Henry Tipantuna has suggested.

But if you're using ts-jest and within the jest.config.ts file.

import dotenv from "dotenv"
dotenv.config()

/* config options below */
4

When using Typescript the following works for me:

in root: jest.config.js

/* eslint-disable @typescript-eslint/no-var-requires */
const { pathsToModuleNameMapper } = require('ts-jest');

const { compilerOptions } = require('./tsconfig.paths.json');

module.exports = {
  // [...]
  moduleNameMapper: pathsToModuleNameMapper(compilerOptions.paths, { prefix: '<rootDir>/' }),
};
process.env = Object.assign(process.env, {
  env_name: 'dev',
  another_var: 'abc123',
});

1

Building on top of @jahller's answer.

I made it responsive so you don't need to keep the files in sync as things change.

Put this at the bottom of your jest.config.js file.

const arr = require('fs')
  .readFileSync('.env', 'utf8')
  .split('\n')
  .reduce((vars, i) => {
    const [variable, value] = i.split('=')
    vars[variable] = value
    return vars
  }, {})

process.env = Object.assign(process.env, arr)

It reads the contents of your .env file, splits every new line and reduces it all back down to an object where you then assign it to process.env

OR

just use dotenv in jest.setup.js 🤷‍♂️

1

i have most simple for implementation env (specialy test.env)

require("dotenv").config({ path: './test.env' });
const { sum } = require('./sum.js');

describe('sum', () => {

  beforeEach(() => {
    jest.resetModules(); // remove cache
  })

  test('should success', () => {
    expect(sum(1, 3)).toEqual(4);
  })
})

0

I think you could try this too:

const currentEnv = process.env;
process.env = { ENV_NODE: 'whatever' };

// test code...

process.env = currentEnv;

This works for me and you don't need module things

1
  • 2
    the problem is that if you import another file that uses process.env then changing it directly won't take any effect. So before each test, you need to tell Jest something like - "hey import and execute this file again". Commented May 10, 2019 at 12:50
0

A simple solution for NodeJS (18) and Typescript (tested with 4 and 5) that uses dotenv-flow npm package:

Install dotenv-flow package:

npm i dotenv-flow

or use pnpm, yarn

Create a jest setup file (e.g. src/setupJest.ts)

import * as dotenvFlow from 'dotenv-flow'
dotenvFlow.config()

Modify the jest.config.ts file:

import type { JestConfigWithTsJest } from 'ts-jest'

const config: JestConfigWithTsJest = {
  ... <your existing configuration settings> ...
  setupFiles: ['./src/setupJest.ts']
}

export default config

Then simply use process.env.<YOUR_ENV_VAR> in jest tests

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.