or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

diff-generation.mdindex.mdmatcher-display.mdvalue-formatting.mdvalue-validation.md
tile.json

tessl/npm-jest-matcher-utils

A set of utility functions for expect and related packages

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/jest-matcher-utils@30.1.x

To install, run

npx @tessl/cli install tessl/npm-jest-matcher-utils@30.1.0

index.mddocs/

Jest Matcher Utils

Jest Matcher Utils is a TypeScript utility library that provides essential functions for Jest's expect assertion library and related testing packages. It offers comprehensive formatting, styling, comparison, and validation functions for creating clear and informative test failure messages.

Package Information

  • Package Name: jest-matcher-utils
  • Package Type: npm
  • Language: TypeScript
  • Installation: npm install jest-matcher-utils (typically installed as part of Jest)

Core Imports

import {
  stringify,
  printReceived,
  printExpected,
  matcherHint,
  matcherErrorMessage,
  diff,
  EXPECTED_COLOR,
  RECEIVED_COLOR,
  INVERTED_COLOR,
  BOLD_WEIGHT,
  DIM_COLOR,
  SUGGEST_TO_CONTAIN_EQUAL,
  SERIALIZABLE_PROPERTIES,
  type MatcherHintOptions,
  type DiffOptions
} from "jest-matcher-utils";

For CommonJS:

const {
  stringify,
  printReceived,
  printExpected,
  matcherHint,
  matcherErrorMessage,
  diff,
  EXPECTED_COLOR,
  RECEIVED_COLOR,
  INVERTED_COLOR,
  BOLD_WEIGHT,
  DIM_COLOR,
  SUGGEST_TO_CONTAIN_EQUAL,
  SERIALIZABLE_PROPERTIES
} = require("jest-matcher-utils");

Basic Usage

import {
  matcherHint,
  matcherErrorMessage,
  printReceived,
  printExpected,
  diff,
  printWithType,
  ensureNumbers,
  EXPECTED_COLOR,
  RECEIVED_COLOR
} from "jest-matcher-utils";

// Custom matcher example
function toBeGreaterThan(received: unknown, expected: unknown) {
  // Validate inputs
  ensureNumbers(received, expected, 'toBeGreaterThan');
  
  const pass = (received as number) > (expected as number);
  const hint = matcherHint('toBeGreaterThan', 'received', 'expected');
  
  if (!pass) {
    const diffOutput = diff(expected, received);
    const message = matcherErrorMessage(
      hint,
      `Expected value to be greater than ${EXPECTED_COLOR(String(expected))}`,
      diffOutput || `Received: ${printReceived(received)}`
    );
    return { pass, message: () => message };
  }
  
  return { pass, message: () => '' };
}

// Using formatting functions
const value = { name: 'Alice', age: 25 };
console.log(printReceived(value));  // Red-colored output
console.log(printExpected(value));  // Green-colored output

Architecture

Jest Matcher Utils is organized around several core areas:

  • Formatting Functions: Convert objects to styled string representations (stringify, printReceived, printExpected)
  • Display Utilities: Create consistent test output formatting (matcherHint, getLabelPrinter, pluralize)
  • Validation Functions: Ensure proper types for matcher operations (ensureNumbers, ensureActualIsNumber)
  • Diff Generation: Compare and visualize differences between values (diff, printDiffOrStringify)
  • Error Handling: Create informative error messages for test failures (matcherErrorMessage)
  • Style Constants: Predefined color and formatting functions (EXPECTED_COLOR, RECEIVED_COLOR)

Capabilities

Value Formatting

Core functions for converting objects to formatted string representations with proper styling and whitespace handling.

/**
 * Convert objects to string representation with formatting
 */
function stringify(
  object: unknown,
  maxDepth?: number,
  maxWidth?: number
): string;

/**
 * Format received values with red color and whitespace indicators
 */
function printReceived(object: unknown): string;

/**
 * Format expected values with green color and whitespace indicators  
 */
function printExpected(value: unknown): string;

/**
 * Highlight trailing whitespace in text with inverse colors
 */
function highlightTrailingWhitespace(text: string): string;

/**
 * Print value with its type information
 */
function printWithType<T>(
  name: string,
  value: T,
  print: (value: T) => string
): string;

Value Formatting

Matcher Display

Functions for creating consistent matcher hints and error messages in test output.

/**
 * Generate hint display for matcher assertions
 */
function matcherHint(
  matcherName: string,
  received?: string,
  expected?: string,
  options?: MatcherHintOptions
): string;

/**
 * Create formatted error message for matcher failures
 */
function matcherErrorMessage(
  hint: string,
  generic: string,
  specific?: string
): string;

/**
 * Create a function that formats labels with consistent alignment
 */
function getLabelPrinter(...strings: Array<string>): PrintLabel;

/**
 * Pluralize a word based on count
 */
function pluralize(word: string, count: number): string;

interface MatcherHintOptions {
  comment?: string;
  expectedColor?: MatcherHintColor;
  isDirectExpectCall?: boolean;
  isNot?: boolean;
  promise?: string;
  receivedColor?: MatcherHintColor;
  secondArgument?: string;
  secondArgumentColor?: MatcherHintColor;
}

type PrintLabel = (string: string) => string;
type MatcherHintColor = (arg: string) => string;

Matcher Display

Value Validation

Functions for validating types and values in matcher operations.

/**
 * Validate that matcher doesn't receive an expected argument
 */
function ensureNoExpected(
  expected: unknown,
  matcherName: string,
  options?: MatcherHintOptions
): void;

/**
 * Validate that actual value is a number or bigint
 */
function ensureActualIsNumber(
  actual: unknown,
  matcherName: string,
  options?: MatcherHintOptions
): void;

/**
 * Validate that expected value is a number or bigint
 */
function ensureExpectedIsNumber(
  expected: unknown,
  matcherName: string,
  options?: MatcherHintOptions
): void;

/**
 * Validate that both actual and expected values are numbers or bigints
 */
function ensureNumbers(
  actual: unknown,
  expected: unknown,
  matcherName: string,
  options?: MatcherHintOptions
): void;

/**
 * Validate that expected value is a non-negative integer
 */
function ensureExpectedIsNonNegativeInteger(
  expected: unknown,
  matcherName: string,
  options?: MatcherHintOptions
): void;

Value Validation

Diff Generation

Functions for comparing values and generating visual diffs for test output.

/**
 * Generate diff between two values
 */
function diff(
  a: unknown,
  b: unknown,
  options?: DiffOptions
): string | null;

/**
 * Generate diff output or stringify values for comparison
 */
function printDiffOrStringify(
  expected: unknown,
  received: unknown,
  expectedLabel: string,
  receivedLabel: string,
  expand: boolean
): string;

/**
 * Replace matched values with asymmetric matchers for comparison
 */
function replaceMatchedToAsymmetricMatcher(
  replacedExpected: unknown,
  replacedReceived: unknown,
  expectedCycles: Array<unknown>,
  receivedCycles: Array<unknown>
): {replacedExpected: unknown; replacedReceived: unknown};

type DiffOptions = {
  aAnnotation?: string;
  bAnnotation?: string;
  changeColor?: (arg: string) => string;
  changeLineTrailingSpaceColor?: (arg: string) => string;
  commonColor?: (arg: string) => string;
  commonLineTrailingSpaceColor?: (arg: string) => string;
  contextLines?: number;
  expand?: boolean;
  includeChangeCounts?: boolean;
  omitAnnotationLines?: boolean;
  patchColor?: (arg: string) => string;
};

Diff Generation

Style Constants

/** Green color for expected values in test output */
const EXPECTED_COLOR: Chalk;

/** Red color for received values in test output */
const RECEIVED_COLOR: Chalk;

/** Inverse color formatting */
const INVERTED_COLOR: Chalk;

/** Bold text formatting */
const BOLD_WEIGHT: Chalk;

/** Dim text formatting for secondary elements */
const DIM_COLOR: Chalk;

/** Suggestion message for using toContainEqual instead of toContain */
const SUGGEST_TO_CONTAIN_EQUAL: string;

/** Symbol for marking serializable properties on objects */
const SERIALIZABLE_PROPERTIES: symbol;