Mocking .env variables in isolation during Jest tests can be useful to test different scenarios without changing the actual .env file. This is helpful for functions that read from the .env file especially in a different scope or context.
getFilePath.ts
export const getFilePath = () => process.env.FILE_PATH;
getFilePath.test.ts
import { getFilePath } from "./getFilePath";
describe("mock-env-jest", () => {
const originalEnv = process.env;
beforeEach(() => {
process.env = {
...originalEnv,
FILE_PATH: "whatever-you-want",
};
});
afterEach(() => {
process.env = originalEnv;
});
it("shows your variable", () => {
expect(process.env.FILE_PATH).toBe("whatever-you-want");
});
it("shows your variable in a different scope", () => {
expect(getFilePath()).toBe("whatever-you-want");
});
});
Assuming you have a
.env
file with a different value forFILE_PATH
output:
PASS src/tests/getFilePath.test.ts
mock-env-jest
√ shows your variable (2 ms)
√ shows your variable in a different scope (1 ms)