Using dotenv with Jest

Florian Hämmerle
1 min readNov 22, 2018

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:

require('dotenv').config()

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.

{
"scripts": {
"test": "jest --setupFiles dotenv/config"
}
}

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:

// jest.config.js
module.exports = {
setupFiles: ["dotenv/config"],
}

Or directly in package.json under jest:

{
"name": "my-package",
"jest": {
"setupFiles": ["dotenv/config"]
}
}

Links

--

--

Florian Hämmerle

raised & based in the Alps • co-founded a digital studio • former CPO at a news company • partner at a software consultancy • into products and innovation