Jest - Configuration



In this chapter, we will cover how to configure Jest for optimal testing. We'll look at the configuration file, command-line options, and how to generate code coverage reports.

Jest Configuration File

Jest works well with its default settings, but sometimes customization is needed. You can configure Jest using a dedicated file like jest.config.js, jest.config.ts, jest.config.json, or other supported formats. Jest will automatically detect this file, or you can specify a custom path using the --config flag.

Ways to Configure Jest

Jest configuration can be done in three main ways:

  • Dedicated configuration file (jest.config.js, jest.config.ts, etc.).
  • Inside package.json
  • Command-line arguments for one-time configurations.

Sample Configuration

Here's a simple example of a jest.config.js file:

module.exports = {
    // Specifies the environment (e.g., 'node' for server-side)
    testEnvironment: 'node',  
    
    // Enables detailed test output
    verbose: true,            
    
    // Patterns for finding test files
    testMatch: ['**/?(*.)+(spec|test).js'],  
    
    // Supported file types
    moduleFileExtensions: ['js', 'json', 'jsx', 'ts', 'tsx']  
};

The moduleFileExtensions array defines the types of files Jest will recognize:

  • js: JavaScript files.
  • json: JSON files.
  • jsx: React JavaScript files.
  • ts: TypeScript files.
  • tsx: TypeScript React files.

Jest - CLI Options

Jest also provides several command-line interface (CLI) options that allow you to customize how Jest runs directly from the terminal.

Common CLI Options in Jest

Here are some of the most commonly used Jest CLI options:

Command What It Does
--coverage Generates a code coverage report to show how much of your code is tested.
--watch Runs Jest in watch mode, automatically re-running tests when files change.
--verbose Displays detailed information about each individual test result.
--testNamePattern=<pattern> Runs only tests whose names match the provided pattern. For example, jest --testNamePattern="button".
--maxWorkers=<number> Limits the number of worker processes Jest uses to run tests, optimizing performance.
--runInBand Runs all tests sequentially (useful for debugging or when tests have side effects).

How to Use CLI Options in Jest?

To use any of these options, you can simply pass them when running Jest via the terminal. For example, to generate a code coverage report and display detailed results for each test, you can use the following command:

npm test -- --coverage --verbose

Example Command

Here's an example that runs Jest with multiple options:

jest --coverage --watch --verbose

This command:

  • --coverage: Collects code coverage data.
  • --watch: Runs Jest in watch mode, automatically re-running tests when files change.
  • --verbose: Displays detailed test results for each individual test.

Jest - Code Coverage Reports

Jest can automatically collect code coverage data, showing how much of your code is tested by your test suite. It generates coverage reports when you run tests and supports different formats.

Enabling Code Coverage

To enable code coverage in Jest, you can either set the collectCoverage option in your configuration file or use the --coverage flag from the command line.

In the Configuration File (jest.config.js):

module.exports = {
    collectCoverage: true,
};

Using the CLI Flag:

npx jest --coverage

When you run Jest with code coverage enabled, it will generate coverage reports in the terminal and store them in the specified coverageDirectory (e.g., coverage/).

Coverage Report Formats

By default, Jest generates coverage reports in the following formats:

  • text: Displays coverage in the terminal.
  • html: Generates an HTML report in the coverage/lcov-report directory.
  • lcov: Creates a detailed lcov report (useful for integration with code coverage tools like Coveralls or Codecov).
  • json: Outputs a JSON file with coverage information.

You can customize the coverage report formats in the configuration:

module.exports = {
    collectCoverage: true,
    coverageReporters: ['text', 'html', 'lcov'],
};

Coverage Output

Once Jest completes running the tests with coverage enabled, it will output a summary in the terminal that includes:

  • Statements: The percentage of statements covered by tests.
  • Branches: The percentage of code branches (if-else, loops) covered.
  • Functions: The percentage of functions covered.
  • Lines: The percentage of lines covered.

A sample output might look like:

Statements   : 87.6% ( 92/105 )
Branches     : 75% ( 3/4 )
Functions    : 100% ( 5/5 )
Lines        : 87.6% ( 92/105 )

Setting Coverage Thresholds

You can set the minimum coverage percentages (e.g., for statements, branches, functions) in Jest using the coverageThreshold option in your Jest configuration file.

Example configuration:

module.exports = {
    collectCoverage: true,
    coverageThreshold: {
        global: {
            statements: 80,
            branches: 75,
            functions: 90,
            lines: 85,
        },
    },
};

If the coverage falls below these numbers, Jest will fail the tests and output a message with the details.

Advertisements