DEV Community

Cover image for How to use environment variables when testing with Jest in NodeJs
Tosin Moronfolu
Tosin Moronfolu

Posted on

15 3

How to use environment variables when testing with Jest in NodeJs

I was trying to use my environment variables in my test suites and it was a hustle. After a long time of trying and researching, I finally found a way to do it and I decided to write this article to help save you time, lol.

Funny how it's quite easy and I wonder why it took me so long to get it done. Well, we learn every day.

I'm using dotenv for the environment variables and jest for testing and all you need to do is add the dotenv config to the jest setup files in your package.json file. Yes, it's that easy

{
  "name": "your-application-name",
  "jest": {
    "setupFiles": ["dotenv/config"]
  }
}
Enter fullscreen mode Exit fullscreen mode

I hope with this short article I've been able to help you save time in configuring dotenv with jest, lol.

Cheers 🎉

links:
https://jestjs.io/
https://www.npmjs.com/package/dotenv

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (2)

Collapse
 
beadle85 profile image
Beadle

Thank you so much for taking the time to share this!

Collapse
 
mrshadowgames profile image
MrShadowGames

What about the .env file.. what about the entries in the package.json? I still can't get it to work and it drives me crazy..

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay