Disable Chalk while running tests with Jest

René Kulik on 14.08.2023


I created a CLI tool to create conventional commits. During the execution the tool uses Chalk to display colorized texts:

Conventional Commits workflow

To ensure the application is working as expected, it is covered by unit tests written in Jest. One of those tests focusses on the logger functionality that prints to the console. Under the hood it uses Chalk to colorize the output.

Unfortunately, since Chalk is used in the background, even the simplest unit test which is expecting a specific output by passing in a specific input would result in an error:

Failed unit test

Regardless of the text, the test fails because the textcolor does not match. As the color is only of secondary interest, it should be ignored in the tests. In the following parts I am going to describe how to handled this.

Mocking Chalk

One option to achieve this is to mock the Chalk package and, depending on the test case, define a return value:

// Mock the Chalk package
jest.mock('chalk', () => ({
  blue: jest.fn(),

// Mock the return value once
chalk.blue.mockReturnValueOnce('This is an info!');

This approach comes with the drawback, that return values have to be explicitly mocked for all tests.

Disable all colors

An alternative option is to use Chalk’s level setting to specify the level of color support. By using 0 all colors will be disabled. This is very handy as you do not have to worry about mocking specific Chalk functions, you just disable them globally during test runs. Therefore, I also decided to go with this solution.

The next part describes how to set up Chalk to use level 0 for the test environment.

Set up Jest

The following configuration has to be added to a setup file, in this case jest.setup.js:

import chalk from 'chalk';

chalk.level = 0;

Afterwards the setupFilesAfterEnv configuration in jest.config.js needs to be extended with the jest.setup.js file:

export default {
  setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],