Skip to content

Instantly share code, notes, and snippets.

@SlideeScherz
Last active April 11, 2024 14:40
Show Gist options
  • Save SlideeScherz/2359cfc30ca0ad4e664454667a97292f to your computer and use it in GitHub Desktop.
Save SlideeScherz/2359cfc30ca0ad4e664454667a97292f to your computer and use it in GitHub Desktop.
Snippet for mocking .env variables in Jest

Mocking .env in Jest

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 for FILE_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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment