I have an app that depends on environmental variables like:
const APP_PORT = process.env.APP_PORT || 8080;
and I would like to test that for example:
- APP_PORT can be set by node env variable.
- or that an
express
app is running on the port set withprocess.env.APP_PORT
How can I achieve this with Jest? Can I set these process.env
variables before each test or should I mock it somehow maybe?
The way I did it can be found in this SO question.
It is important to resetModules before each test and then dynamically import the module inside the test:
Depending on how you can organize your code, another option can be to put the env variable within a function that's executed at runtime.
In this file, the env var is set at import time, and requires dynamic
require
s in order to test different env vars (as described in this answer):In this file, the env var is set at
envMessage
execution time, and you should be able to mutate process.env directly in your tests:Jest test: