DEV Community

Quan Phan
Quan Phan

Posted on • Updated on

Set up environment variables in Jest for your frontend

Context

Our tests are isolated from the production code.

my-project/
├── src/
├── test/
├── .env.local
├── package.json
└── ...
Enter fullscreen mode Exit fullscreen mode

Our production code (in src/) uses several environment variables imported from .env or .env.local.

Goal

We want to test the part of the production code that uses the environment variables in .env.local.

Problem

Without proper set up, Jest will not load the environment variables into process.env.

How to

Create a JS set up file for Jest. In the JS file, load the environment variables:

// env.js
require("dotenv").config({ path: "path/to/env/file" });
Enter fullscreen mode Exit fullscreen mode

Create a jest.config.js file (at the same level as package.json), and put in there:

module.exports = {
   // other settings
   setupFiles: ["<rootDir>/path/set/up/file.js"],
};
Enter fullscreen mode Exit fullscreen mode

Done!

Examples

Here is my set up:

my-project/
├── .jest/
│   └── env.js
├── public/
├── src/
├── test/
├── package.json
├── .env.local
├── jest.config.js
└── ...
Enter fullscreen mode Exit fullscreen mode

In jest.config.js...

module.exports = {
   // other settings
   setupFiles: ["<rootDir>/.jest/env.js"], // Keep the <rootDir> as is, DON'T replace it with your root directory
};
Enter fullscreen mode Exit fullscreen mode

In .jest/env.js...

require("dotenv").config({ path: ".env.local" });
// after this line, you can edit any variable in process.env
// to fit the test environment. for example...
process.env.ENVIRONMENT = "test";
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
dotenv profile image
Dotenv

💛🌴