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.

Discussion (0)