'How to send environment variables to Jest CLI?

I have a script that runs a Jest test for me, and I want to set an environment variable before running it, something like this:

my_test_script.sh

IMPORTANT_ENV_VAR=value_that_matters
./node_modules/.bin/jest --useStderr ./__tests__/my.test.js

However, inside "my.test.js" the IMPORTANT_ENV_VAR is not set when I run my test like this.

How do I pass the environment variable into the Jest CLI ?



Solution 1:[1]

Going off of @Andrea Bisello's answer, you can load the environment variables from a plain JavaScript file. This is the key take-away.

So, in my environment, I already had a jest.config.ts. Since I was already using a .env file for defining my environment variables (located at the root of my project), I just needed a way to load them when running jest from a CLI at the root of my project.

Doing that is very simple; just add this to the jest.config.ts or jest.config.js:

// jest.config.{ts,js}
const { config } = require('dotenv');

config();

Then, from the root of your repo, you can do something like:

npx jest

Solution 2:[2]

Because it's hard to set environment variables in a platform-independent way under npm/package.json, and because jest --setupFiles, while in the usage, isn't in the docs and doesn't seem to work (24.9), jest REALLY DOES need a --envVar option to support environmental overrides external to package.json (like dev/production).

Solution 3:[3]

What i do to solve the problem is ugly, but works.

I'm searching for a better solution (Simply set a Environment Variable by cli), not able to find it.

i create a js file that set the environment variable and i load that file passing it to the setupFile cli command. for example

jest --setupFile=setter.js

and setter.js contains

process.env.A = "B"

so, before running each test, i can read the process.env.A variable.

Solution 4:[4]

Use cross-env:

{
  "scripts": {
    "build": "cross-env NODE_ENV=production webpack --config build/webpack.config.js"
  },
  "devDependencies": {
    "cross-env": "7.0.3",
  }
}

Its purpose is exactly to pass environment variables to an npm script in a cross-platform way.

Solution 5:[5]

Whoops!
Not a Jest problem, I just needed to export in the shell script :

export IMPORTANT_ENV_VAR=value_that_matters
./node_modules/.bin/jest --useStderr ./__tests__/my.test.js

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 user3773048
Solution 2 Glenn Widener
Solution 3 Andrea Bisello
Solution 4 Peter V. Mørch
Solution 5 Kris Randall