How to Use dotenv with Jest

This article is a translated version of my original post on Qiita. Original (Japanese): https://qiita.com/segur/items/9a744d9af84d2690c326

dotenv Wasn't Working with Jest

I struggled with dotenv when using Jest. Since I couldn't find a Japanese-language article on the fix, I'm writing it down before I forget.

What Is dotenv?

dotenv is an npm package that loads the contents of a .env file as environment variables in Node.js. npm - dotenv

For detailed usage, this article is very helpful: Using .env Files Instead of Environment Variables (dotenv)

What Is Jest?

Jest is a JavaScript testing framework. Jest Official Site

The Problem: dotenv Wasn't Working in Jest

When I ran test code with Jest, the following code didn't work:

import dotenv from 'dotenv'

// Load .env values into an object
const config = dotenv.config().parsed;

The Fix: Add a Setting to package.json

After searching for a solution, I found this article: Using dotenv with Jest

The fix is to add the following to package.json:

{
  "jest": {
    "setupFiles": [
      "dotenv/config"
    ]
  }
}

I tried it and it worked.

Closing

Glad I got it resolved. References used: