DEV Community

Cover image for Jest with global Dotenv configuration
Dailos Rafael Díaz Lara
Dailos Rafael Díaz Lara

Posted on • Updated on

Jest with global Dotenv configuration

🎯 Target

I want to have several .env files in order to define different conditions depending on the environment where my code is running. Based on that, in my testing process I want to load a global configuration once for the whole testing suites.

😅 Overview

There are some options to load environment variables in my tests, using Dotenv.

  • node -r dotenv/config node_modules/.bin/jest

    That is one of the most usual approaches but I don't like it because this way, Dotenv literally needs a .env file defined at the root of the project so I cannot set a custom configuration file.

  • require(dotenv).config({ path: 'path/to/env_file' });

    This option requires to type this command in every testing file where I'm going to use environment variables. It could be a solution but I don't like it at all because I have to pay attention to the relative path for the environment file location in every testing file.

  • setupFiles Jest configuration property.

    That is fine but as the official documentation suggests, the environment is processed once per testing file. This conditions will dealy a little my tests execution and in addition, I don't want it. I want a global configuration at the very begining of the testing process.

😎 My best matching

After diving a little in the Jest documentation, I found this configuration property: globalSetup.

In order to use this property, I created the dotenv-test.js file into dotenv folder (located at the root of the project).

// dotenv-test.js file content.

const path = require('path');
const dotenv = require('dotenv');

module.exports = async () => {
    dotenv.config({ path: path.resolve(__dirname, '../env/.env.test') });
};
Enter fullscreen mode Exit fullscreen mode

Following the property documentation guidelines, this file must export an asynchronous function that will be executed before the whole testing files.

When the testing framework runs at the first time, this file is executed, loading the selected environment variables and setting them globally, for the whole testing files and just once. That's all.

Finally, I have just to introduce this property into the Jest configuration file (jest.config.json) and provide the location of the Dotenv file.

{
    ...
    "globalSetup": "<rootDir>/dotenv/dotenv-test.js",
    ...
}
Enter fullscreen mode Exit fullscreen mode

👋 Final words

I hope this tip is useful for you. If you have any question, feel free to contact me. Here there are my Twitter, Linkedin and Github profiles.

💾 Resources

Discussion (0)