Context
Our tests are isolated from the production code.
my-project/
├── src/
├── test/
├── .env.local
├── package.json
└── ...
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" });
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"],
};
Done!
Examples
Here is my set up:
my-project/
├── .jest/
│ └── env.js
├── public/
├── src/
├── test/
├── package.json
├── .env.local
├── jest.config.js
└── ...
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
};
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";
Top comments (1)
💛🌴