DEV Community

Alessio Michelini
Alessio Michelini

Posted on

How to mock environment variables with Jest

If you use Jest as your trusty testing framework for your Node.js application, you probably ended up in the situation where the code you are trying to test, uses environmental variables that you access with process.env.

The simplest way to do is to create a file, to be called setEnvVars.js, and to populate it with the env variables you need, for example:

// .jest/setEnvVars.js
process.env.SOME_VAR = 'something';
process.env.SECRET = 'shh-do-not-tell-to-anyone';
// etc...
Enter fullscreen mode Exit fullscreen mode

What I consider a good practice is also to place this file under a .jest folder, so we know that everything inside that, is related to Jest.

And just to make it more clear, you should have a file structure similar to this:

|-- .jest
|   `-- setEnvVars.js
|-- jest.config.js
|-- package-lock.json
|-- package.json
|-- server.js
Enter fullscreen mode Exit fullscreen mode

Now the next thing to set up is to update your jest.config.js and tell it to use that file:

// jest.config.js
module.exports = {
  setupFiles: ['<rootDir>/.jest/setEnvVars.js'],
  // ... other configurations
};
Enter fullscreen mode Exit fullscreen mode

And that's it! Now when you will run the tests, the code will able to access to those mock environmental variables.

Top comments (5)

Collapse
 
darkmavis1980 profile image
Alessio Michelini

Nope

Collapse
 
sofiacoder3000 profile image
Sofia Campos

I found the solution with setupFilesAfterEnv:

// package.json
{
"name": "...",
"version": "1.0.0",
"description": "...",
"main": "index.js",
"scripts": {
...
"test": "jest"
},
...
"jest": {
"verbose": true,
"silent": false,
"setupFilesAfterEnv": [
"./.jest/setEnvVars.js"
]
}
}

Collapse
 
sofiacoder3000 profile image
Sofia Campos

Hi Alesso,
Please, maybe you can help me,
how do you set this setEnvVars.js in package.json config?

// package.json
{
"name": "...",
"version": "1.0.0",
"description": "...",
"main": "index.js",
"scripts": {
...
"test": "jest",
"test:cov": "jest --coverage ",
"test:watch": "jest --watch"
},
"repository": {
...
},
"keywords": [],
"author": "Jakeline Campos",
"license": "MIT",
"dependencies": {
...
},
"devDependencies": {
...
},
"jest": {
"verbose": true,
"silent": false,
"setupFiles": [
".jest/setEnvVars.js"
]
}
}

this not working for me.

Collapse
 
darkmavis1980 profile image
Alessio Michelini
Collapse
 
darkmavis1980 profile image
Alessio Michelini

it should work like that, but I would recommend to separate the jest configuration in another file as it makes it more readable instead of a very long package.json