CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-jest-matcher-utils

A set of utility functions for expect and related packages

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

matcher-display.mddocs/

Matcher Display

Functions for creating consistent matcher hints and error messages in test output, providing clear and informative failure messages.

Capabilities

Matcher Hint

Generates formatted hint displays for matcher assertions, showing the expected matcher call format.

/**
 * Generate hint display for matcher assertions
 * @param matcherName - Name of the matcher
 * @param received - Text for received value (default: 'received')
 * @param expected - Text for expected value (default: 'expected')
 * @param options - Display options
 * @returns Formatted matcher hint
 */
function matcherHint(
  matcherName: string,
  received?: string,
  expected?: string,
  options?: MatcherHintOptions
): string;

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

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

Usage Examples:

import { matcherHint, EXPECTED_COLOR, RECEIVED_COLOR } from "jest-matcher-utils";

// Basic matcher hint
const hint = matcherHint('toEqual');
// Result: 'expect(received).toEqual(expected)'

// Custom labels
const customHint = matcherHint('toContain', 'array', 'value');
// Result: 'expect(array).toContain(value)'

// Negated matcher
const notHint = matcherHint('toBe', undefined, undefined, { isNot: true });
// Result: 'expect(received).not.toBe(expected)'

// Promise matcher
const promiseHint = matcherHint('resolves.toEqual', undefined, undefined, {
  promise: 'resolves'
});
// Result: 'expect(received).resolves.toEqual(expected)'

// With comment
const commentHint = matcherHint('toEqual', undefined, undefined, {
  comment: 'deep equality'
});
// Result: 'expect(received).toEqual(expected) // deep equality'

// Direct expect call (no received)
const directHint = matcherHint('toHaveBeenCalled', '', '', {
  isDirectExpectCall: true
});
// Result: 'expect.toHaveBeenCalled()'

// Multiple arguments
const multiHint = matcherHint('toBeCloseTo', 'received', 'expected', {
  secondArgument: 'precision'
});
// Result: 'expect(received).toBeCloseTo(expected, precision)'

Matcher Error Message

Creates formatted error messages for matcher failures with consistent styling.

/**
 * Create formatted error message for matcher failures
 * @param hint - Assertion returned from call to matcherHint
 * @param generic - Condition which correct value must fulfill
 * @param specific - Incorrect value returned from call to printWithType
 * @returns Formatted error message
 */
function matcherErrorMessage(
  hint: string,
  generic: string,
  specific?: string
): string;

Usage Examples:

import { matcherErrorMessage, matcherHint, printWithType, printReceived } from "jest-matcher-utils";

// Basic error message
const hint = matcherHint('toBeGreaterThan');
const error = matcherErrorMessage(
  hint,
  'expected value must be a number'
);
// Result: 'expect(received).toBeGreaterThan(expected)\n\nMatcher error: expected value must be a number'

// With specific details
const detailedError = matcherErrorMessage(
  hint,
  'received value must be a number',
  printWithType('Received', 'not a number', printReceived)
);
// Result includes the specific type information

// Complete matcher error workflow
function customMatcher(received: unknown, expected: number) {
  const hint = matcherHint('toBeGreaterThan', 'received', 'expected');
  
  if (typeof received !== 'number') {
    throw new Error(
      matcherErrorMessage(
        hint,
        'received value must be a number',
        printWithType('Received', received, printReceived)
      )
    );
  }
}

Label Printer

Creates a function that formats labels with consistent alignment for multi-line output.

/**
 * Create a function that formats labels with consistent alignment
 * @param strings - Strings to calculate alignment for
 * @returns Function that formats labels with padding
 */
function getLabelPrinter(...strings: Array<string>): PrintLabel;

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

Usage Examples:

import { getLabelPrinter } from "jest-matcher-utils";

// Create aligned label printer
const printLabel = getLabelPrinter('Expected', 'Received');

// Use for consistent formatting
const expectedLine = printLabel('Expected') + 'value1';
const receivedLine = printLabel('Received') + 'value2';
console.log(expectedLine);  // 'Expected: value1'
console.log(receivedLine);  // 'Received: value2'

// Handles different label lengths
const printer = getLabelPrinter('Short', 'Very Long Label');
const short = printer('Short');     // 'Short:          '
const long = printer('Very Long Label'); // 'Very Long Label: '

// Common usage in diff output
const diffPrinter = getLabelPrinter('Expected', 'Received');
const comparison = [
  diffPrinter('Expected') + '{"name": "Alice"}',
  diffPrinter('Received') + '{"name": "Bob"}'
].join('\n');

Pluralize

Pluralizes words based on count for grammatically correct test messages.

/**
 * Pluralize a word based on count
 * @param word - Word to pluralize
 * @param count - Count to determine plural form
 * @returns Pluralized phrase with count
 */
function pluralize(word: string, count: number): string;

Usage Examples:

import { pluralize } from "jest-matcher-utils";

// Basic pluralization
const items = pluralize('item', 1);    // 'one item'
const manyItems = pluralize('item', 3); // '3 items'
const zeroItems = pluralize('item', 0); // 'zero items'

// Works with numbers 0-13 spelled out
const spelled = pluralize('error', 5);  // '5 errors'
const written = pluralize('warning', 1); // 'one warning'

// Common usage in test messages
function validateArray(arr: unknown[]) {
  if (arr.length === 0) {
    throw new Error(`Expected array to have items but received ${pluralize('item', arr.length)}`);
  }
}

// In matcher implementations
const errorCount = errors.length;
const message = `Found ${pluralize('validation error', errorCount)}`;
// Results: 'Found one validation error' or 'Found 3 validation errors'

docs

diff-generation.md

index.md

matcher-display.md

value-formatting.md

value-validation.md

tile.json