Table of contents
1.
Introduction
2.
Configuring Jest
2.1.
Different ways to configure.
2.1.1.
New JSON file
2.1.2.
Package.json file
2.1.3.
Example configuration
2.1.4.
jest.config.js file
3.
Different configuration options
3.1.
Coverage
3.1.1.
collectCoverage
3.1.2.
Configuration
3.1.3.
Output
3.1.4.
coverageThreshold
3.1.5.
Configuration
3.1.6.
coverageReporters
3.1.7.
coverageDirectory
3.2.
Test
3.2.1.
testTimeouts
3.2.2.
Configuration
3.2.3.
Globals
3.2.4.
Configuration
3.3.
Mock
3.3.1.
autoMock
3.3.2.
clearMock
4.
FAQs
5.
Key Takeaways
Last Updated: Mar 27, 2024

Jest Configuration

Author Aditya Anand
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Welcome readers! In this blog, we will learn how to configure Jest for different purposes, like code coverage, test timeout and mock related, etc. if you are unfamiliar with Jest, please go through Getting started with Jest blog. we will see step by step process to configure Jest, we will see different ways to achieve the same result. We will see some of the many configuration options provided by Jest. I hope you learn a lot from this tutorial.

Configuring Jest

We can start writing our unit test in Jest with very minimal configurations, we have to add the following in the package.json file, and we are good to go.

"scripts": {
      "test": "jest"
  },

But Jest also provides many different configuration options to achieve a specific result, for example, collectCoverage, coverageThreshold, coverageDirectory, coverageReporters, autoMocks, clearMocks, testTimeout, globals, watchman, watchPlugins, testRunner, verbose, watchman, snapshotFormat, snapshotResolver, snapshotSerializer, etc. to name a few.

These configuration options allow Jest to be very efficient and save a lot of testing time and effort.

Different ways to configure.

Jest allows you to do configurations in three ways, ensuring flexibility in its usage.

  • We can make a new JSON file specific to the configuration.
  • We can configure it in the package.json file itself.
  • We can also configure through the jest.config.js file.

Next, we will see the step-by-step process of configuration using these ways.

New JSON file

Create a new JSON file called jestConfig.json file in the folder containing package.json, and write all your configurations in the jestConfig.json file itself. In the package.json file, we have to specify the config property, as shown below.

"scripts": {
          "test": "jest --config=jestConfig.json"
  }

Now open the jestConfig.json file and start writing configurations. An example configuration is shown below.

Example configuration

{
    "collectCoverage" : true,
    "coverageThreshold": {
      "global": {
                  "branches":75,
                  "functions":100,
                  "lines":85
           }
    },
    "testTimeout": 300,
    "globals": {
          "globalVar": "a global variable"
      },
      "snapshotFormat": {
            "printBasicPrototype": false
      }
}

Package.json file

We can also write and save all our Jest configurations in the package.json file without creating a new one. For this, open package.json, make a new property called Jest and write all your configurations there. This is what your package.json will look like.

{
  "name": "nodeprojects",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "jest --config=jestConfig.json"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
      "jest": "^27.4.7"
  },
  "jest":{
    // write your configurations here
  }
}

Now simply copy-paste all the configurations which we have written in the previous method.

Example configuration

"jest":{
    "collectCoverage" : true,
    "coverageThreshold": {
        "global": {
            "branches":75,
          "functions":100,
          "lines":85
      }
  },
  "testTimeout": 300,
  "globals": {
        "globalVar": "a global variable"
    },
    "snapshotFormat": {
          "printBasicPrototype": false
    }
}

jest.config.js file

You can also configure Jest using the jest.config.js file, create a new file jest.config.js, in the same folder containing package.json, and start writing your configurations.

module.exports = {
    // Write all your configurations here.    
};

Different configuration options

So far, we have learned how to configure Jest in different ways. Now we will see some of the many example configurations provided by Jest and their functionalities.

Coverage

Test coverage is a measure used to describe the degree to which the source code of a program is executed when a particular test suite runs, as no of lines covered, no of branches covered, no of functions covered, etc.

collectCoverage

When collectCoverage configuration is set to be true, Jest will collect the coverage and print it in the console in tabular format.

Configuration

{
    "collectCoverage" : true
}

Output

coverageThreshold

We can specify the %Branch %Func, etc., using this configuration, as needed. Using global key under coverageThreshold, we can set different values for all functions under test, we can specify values specific to any function as well.

Configuration

{
  "collectCoverage" : true,
  "coverageThreshold": {
      "global": {
          "branches":50,
          "functions":100,
          "lines":85
      },
    "./function.js": {
        "branches":50,
        "functions":100,
        "lines":85
     }
  }
}

coverageReporters

Instead of printing our collected coverage in the console, Jest also provides coverageReport configuration, allowing testers to save the collected coverage information in a file.

coverageDirectory

coverageDirectory configuration allows testers to specify the directory where we want to save our coverage report.

Configuration

{
"coverageReporters": [
    "lcov","text"
],
"coverageDirectory": "./coverageReport/"
} 

Test

testTimeouts

This configuration will limit the execution time of any test, meaning any test-taking more than this much time in milliseconds will be considered as failed. This property allows checking the efficiency of functions under test.

Configuration

{
    "testTimeout": 300
}

Globals

Using this configuration, we can make a global variable, which can be used anywhere in the test.

Configuration

{
  "globals": {
      "globalVar": "a global variable"
  }
}

Mock

Mocking is an integral part of unit testing, in order to test API calls, etc. testers heavily rely on mocking these calls, this configuration will allow testers to easily mock modules, clear mocks, etc.

Please check out Mocking in Jest blog to learn more.

autoMock

autoMock configuration will enable testers to mock all the modules imported in the test automatically.

clearMock

This configuration will delete all the previous mocks created for each test.

FAQs

  1. Does jest use Jsdom?
    Jest ships with jsdom, which simulates a DOM environment as if you were in the browser.
     
  2. How many test cases are enough?
    To thoroughly test that all the requirements of an application are met, there must be at least two test cases for each condition: one positive test and one negative test. If a requirement has sub-requirements, each sub-requirement must have at least two test cases.
     
  3. Does Jest use chai?
    If you like chai, you can upgrade to Jest and continue using chai.
     
  4. How do you mock a promise in Jest?
    We call jest.mock('../request') to tell Jest to use our manual mock. It expects the return value to be a Promise that will be resolved. You can chain as many Promises as you like and call expect at any time, as long as you return a Promise at the end. 

Key Takeaways

In this blog, we learned how to configure Jest, and we have seen different methods to configure. We also learned some configuration options provided by Jest. These configurations offer a lot of functionalities like code coverage, mock-related functionality like auto mock clear mock, etc. To learn more about mock functions, head over to here.

Learning never stops, and to feed your quest to learn and become more skilled, head over to our practice platform Coding Ninjas Studio to practice top problems, attempt mock tests, read interview experiences, and much more.!

Happy Learning!

Live masterclass