Mock process.env in Jest
Here's how to mock out process.env in a Jest test.
This essentially from this StackOverflow post, reproduced here for my own reference.
The Concept
It turns out that you can set process.env
to the value you want, not just read from it. What we'll want to do is save a version of the original process.env
object, then set the value we want for our test, then reset it to the original when we're done.
A Source File
Let's say I have a function that relies on process.env
for its work. A contrived example:
export function myFunction() {
return process.env.NEXT_PUBLIC_ENV === 'test' ? 'testValue' : 'prodValue'
}
A Test Suite
describe('myFunction', () => {
const ORIG_ENV = process.env
beforeEach(() => {
jest.resetModules()
process.env = { ...ORIG_ENV }
})
afterEach(() => {
process.env = ORIG_ENV
})
test('region, with override, use override', () => {
process.env.NEXT_PUBLIC_ENV = 'test'
expect(myFunction()).toEqual('testValue')
})
})
The call to jest.resetModules
is to make sure that the setting of process.env
doesn't leak out into other tests.
From the jest docs, jest.resetModules
:
Resets the module registry - the cache of all required modules. This is useful to isolate modules where local state might conflict between tests.
Set and unset. Noodles, don't noodles. process.env
is yours.