Load .env File in Jest

Here's how to load .env file in Jest tests.

.env File

A test suite that relies on real systems, say external APIs, might require sensitive information like API keys in order to interact with them. But as with the source code, we don't want to commit sensitive information to the test code. So, we'll rely on the values for things like API keys to be available in the environment, via environment variables.

A great way to specify environment variables in a dev environment is to write them to a non-committed file, called .env. Then this file can be read and its contents put into the environment, making values available via process.env.

There are a several libraries that read .env files into the environment. My favorite is this one:

npm install dotenv --save-dev

The .env file might read:


And my test file that references MY_API_KEY might read:

import { fetchMyData } from './my-api'
test('api integration', async () => {
  const actual = await fetchMyData(process.env.MY_API_KEY)
  expect(actual).toBe({ really: "awesome" })

setupFiles Config

Some tests require setup, and jest has anticipated us and provided a setupFiles config option which will point to our setup file. We'll define our jest.config.js file:

module.exports = {
  setupFiles: ['<rootDir>/test/setup-env.js'],

And then test/setup-env.js will read:

require('dotenv').config({ path: '.env' })

Now, when running jest, the .env file will be read and its contents will be available in the environment.