How to Mock process.env in Jest

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:

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

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

JavaScript Course

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:

describe('process.env', () => {
    const env = process.env

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

    afterEach(() => {
        process.env = env
    })
})
Copied to clipboard!

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.

Remove ads

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:

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"
})
Copied to clipboard!

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:

module.exports = {
    setupFilesAfterEnv: ['<rootDir>/setup-test-env.js']
}
jest.config.jsrootDir is resolved to the root of your project
Copied to clipboard!

Summary

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

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
Remove ads
Remove ads

πŸ“š Get access to exclusive content

Want to get access to exclusive content? Support webtips with the price of a coffee to get access to tips, checklists, cheatsheets, and much more. β˜•

Get access Support us
Remove ads Read more on
Remove ads
Remove ads
πŸŽ‰ Thank you for subscribing to our newsletter. x