Jest Matcher Utilities

30.3.0 · active · verified Sun Apr 19

jest-matcher-utils provides a collection of helper functions used internally by Jest and exposed for developers creating custom matchers. These utilities facilitate consistent formatting and error reporting within Jest's `expect` assertions. The package is part of the larger Jest monorepo, which is currently stable at version 30.3.0, with major releases occurring every few years (Jest 30 was released after three years, with a stated aim for more frequent future majors). It's actively maintained, with frequent patch and minor updates addressing bug fixes, performance improvements, and new features across the Jest ecosystem. Its primary differentiation lies in providing the exact formatting and utility logic that Jest itself uses, ensuring seamless integration and a consistent user experience when extending Jest's assertion capabilities. This includes functions for printing values, generating matcher hints, and handling object comparisons, crucial for building custom assertion logic that feels native to Jest.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to create a custom Jest matcher using `jest-matcher-utils` to provide consistent output formatting for success and failure messages, including color coding.

import { matcherHint, printReceived, printExpected, EXPECTED_COLOR, RECEIVED_COLOR } from 'jest-matcher-utils';
import { expect } from '@jest/globals'; // Or global 'expect' if configured

declare global {
  namespace jest {
    interface Matchers<R> {
      toBeDivisibleBy(divisor: number): R;
    }
  }
}

expect.extend({
  toBeDivisibleBy(received: number, argument: number) {
    const pass = received % argument === 0;

    const message = () =>
      matcherHint('.toBeDivisibleBy', 'received', 'argument') +
      '\n\n' +
      `Expected: ${EXPECTED_COLOR(argument)}\n` +
      `Received: ${pass ? printReceived(received) : RECEIVED_COLOR(received)}`;

    if (pass) {
      return {
        message,
        pass: true,
      };
    } else {
      return {
        message,
        pass: false,
      };
    }
  },
});

describe('toBeDivisibleBy', () => {
  test('should pass if the number is divisible', () => {
    expect(4).toBeDivisibleBy(2);
  });

  test('should fail if the number is not divisible', () => {
    expect(() => expect(5).toBeDivisibleBy(2)).toThrowErrorMatchingSnapshot();
  });
});

view raw JSON →