Using DotEnv files with Jest, with a free gift

TL;DR Don’t forget to “dotenv/config” for those jest tests that need to access process.env.

Just spent an hour wondering why a jest test is not picking up process.env variables.

It’s embarrassingly simple as you can see from this gist:

However I had forgotten the import “dotenv/config”.

I then realized that I don’t have a good ‘minimal’ starter project for setting up TypeScript, Jest and Node so I used this simple example to create a good project: https://github.com/Simple-Innovation/simple-jest-dotenv.

Its also a template repository so you can use it to quickly get started for new node, typescript and jest projects.

Enjoy.

TL;DR Don’t forget to “dotenv/config” for those jest tests that need to access process.env.

--

--

Sebastian Rogers

Technical Director for Simple Innovations Ltd. First paid for code in 1980, but still has all his own hair.