πŸ’‘ This page contain affiliate links. By making a purchase through them, we may earn a commission at no extra cost to you.
How to Mock process.env in Jest

How to Mock process.env in Jest

Unit testing environment-specific parts in your application
Ferenc Almasi β€’ 2022 January 04 β€’ Read time 3 min read
To mock process.env in Jest, set up a beforeEach and afterEach hook to set, and then restore process.env. Then you can safely manipulate in your test
  • twitter
  • facebook

Modern frontend applications depend on environment variables to present different behaviors in different setups. Most commonly, you will come across that process.env is used in a codebase to differentiate between production and development.

This means that when testing process.env specific parts of your app, you may run into errors if it is not set to the correct state. You may be tempted to write:

Copied to clipboard!
it('should mock process.env', () => {
    process.env.NODE_ENV = 'development'
})

However, this will cause unexpected behaviors, as you will override the process values for other test cases as well.

Need to mock global variables in Jest? Check out this tutorial.

Mocking process.env

To mock process.env the right way, we need to set up before and after hooks to first make a copy of the original object, and then reset it after each test case:

Copied to clipboard! Playground
describe('process.env', () => {
    const env = process.env

    beforeEach(() => {
        jest.resetModules()
        process.env = { ...env }
    })

    afterEach(() => {
        process.env = env
    })
})

For this, we can use the beforeEach and afterEach hooks. Inside the beforeEach, make sure you call jest.resetModules first to clear the cache for the required modules to avoid conflicting local states. Then we can make a copy of process.env from the original object, and in the afterEach hook, we also need to restore the old configuration to avoid conflicting states.


Testing the mocked values

Now that we have everything set up, we can add, remove, or reassign existing properties on process.env, just like you normally would with an object:

Copied to clipboard! Playground
it('should mock process.env', () => {
    process.env.NODE_ENV = 'development'

    console.log(process.env.NODE_ENV) // Will be "development"
})

it('should not mock process.env', () => {
    console.log(process.env.NODE_ENV) // Will be "test"
})

Note that for subsequent it calls, the process.env will be reset to its original state because of the afterEach hook. If you would like to provide a global setup for your process.env, you can also create a setup file that you can reference in your Jest config, using the setupFiles field:

Copied to clipboard!
module.exports = {
    setupFilesAfterEnv: ['<rootDir>/setup-test-env.js']
}
jest.config.js
rootDir is resolved to the root of your project
Looking to improve your skills? Master Jest from start to finish.
Master Jestinfo Remove ads

Summary

In summary, to mock process.env in Jest, you need to:

  • Set up a beforeEach hook to clear the cache for the required modules, and make a copy of process.env
  • Set up an afterEach hook to reset process.env to its original state
  • Add, delete, or reassign values to process.env in your test cases

Are you new to Jest and would like to learn more? Check out the following introduction tutorial below:

Writing Your Very First Unit Test With Jest
  • twitter
  • facebook
Did you find this page helpful?
πŸ“š More Webtips
Frontend Course Dashboard
Master the Art of Frontend
  • check Access 100+ interactive lessons
  • check Unlimited access to hundreds of tutorials
  • check Prepare for technical interviews
Become a Pro

Courses

Recommended

This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.