mock a value from .env.test in vitest in typescript

To mock a value from .env.test file in jest test cases written in TypeScript, you can use the jest.mock function in combination with the dotenv package.

First, install the dotenv package by running the following command:

index.ts
npm install dotenv
19 chars
2 lines

Then, in your test file, you can mock the value from .env.test file as shown below:

index.ts
import dotenv from 'dotenv';
import { myFunction } from './myFunction';

jest.mock('dotenv', () => ({ 
  config: jest.fn(),
  parsed: { MY_VALUE: 'from-test' },
}));

describe('myFunction', () => {
  beforeEach(() => {
    dotenv.config(); // load env variables
  });

  it('should return the value from env', () => {
    const result = myFunction();
    expect(result).toEqual('from-test');
  });
});
402 chars
19 lines

In the example above, the dotenv package is mocked so that it returns the MY_VALUE variable from .env.test file. Then, in the beforeEach block, the dotenv.config() method is called to load the env variables. Finally, inside the test case, the myFunction is called and its result is tested against the expected value.

Note: Make sure that the dotenv.config() method is called before the function that uses the env variables is executed. Also, make sure that the .env.test file is placed in the root directory of the project.

gistlibby LogSnag