How to mock environnement variable with jest and TypeScript

Stanislas Randriamilasoa
1 min readJan 14, 2023

--

When writing tests for your application, it’s often necessary to mock certain aspects of the environment, such as environment variables. This allows you to test your code in a controlled and predictable manner, without relying on external factors that may change over time.

Jest is a popular JavaScript testing framework that makes it easy to mock environment variables. In this blog post, we’ll show you how to set up a mock environment variable with Jest.

1- Option 1

An easy approach is to create a file named setEnvVars.js, and add the necessary environment variables within it. For instance in “.jest” folder:

// .jest/setEnvVars.ts
process.env.MY_VAR= 'myvarvalue';
process.env.MY_SECRET= 'mysupersecret-value';

The next step is to modify your jest.config.ts file and indicate it to utilize the setEnvVars.ts file.

// jest.config.ts

import type { Config } from 'jest';

const config: Config = {
setupFiles: ['<rootDir>/jest/setVenVars.ts'],
// ... additional settings
};

export default config;

That’s all! Now when you execute your tests, the code will have access to the mocked environment variables.

2- Option 2

Alternatively, you can use jest-environment-dotenv to handle this for you.

npm install jest-environment-dotenv

and in jest.config.ts

// jest.config.ts
{
testEnvironment: 'jest-environment-dotenv',
testEnvironmentOptions: {
path: '.env.test',
},
}

In your test files, you will be able to access the environment variables from the process.env object.

That’s it! Your environment variables should now be accessible in your Jest tests.

--

--