I was looking for a convenient way to use the dotenv package in our Jest tests and it turns out there’s an easy way!

The first and probably most obvious way is to just load dotenv in the jest setup file. However, most of our projects do not have a jest setup file and I wasn’t keen on adding a setup file just for loading dotenv. Here is how you would do it in the jest setup file:

While reading through the Jest CLI help (npx jest -h) I stumbled upon the --setupFiles argument which allows to include dotenv just as with Node’s --require option. Used in the test script of package.json it looks like this.

As you can see there is no need for an extra setup file. Hurrah 🥳.

In the responses Alex Alexeev & Eric Van Der Dijs pointed out that setting updotenv for Jest is also possible via jest.config.js:

Or directly in package.json under jest:

Links

raised and based in the Alps • co-founded a digital studio • currently CPO at a news company • into products, design and innovation