or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/npm-jest-expect-message

Add custom message to Jest expects

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/jest-expect-message@1.1.x

To install, run

npx @tessl/cli install tessl/npm-jest-expect-message@1.1.0

index.mddocs/

jest-expect-message

jest-expect-message extends Jest's expect function to support custom error messages, allowing developers to provide more descriptive failure messages when assertions fail. It provides seamless integration with existing Jest test suites and maintains full compatibility with all Jest matchers.

Package Information

  • Package Name: jest-expect-message
  • Package Type: npm
  • Language: JavaScript (with TypeScript support)
  • Installation: npm install --save-dev jest-expect-message

Core Imports

This package is a Jest setup extension and is imported through Jest configuration rather than direct import statements:

Jest v24+ Configuration:

{
  "jest": {
    "setupFilesAfterEnv": ["jest-expect-message"]
  }
}

Jest v23- Configuration:

{
  "jest": {
    "setupTestFrameworkScriptFile": "jest-expect-message"
  }
}

Custom Setup File:

import 'jest-expect-message';

TypeScript Configuration:

{
  "files": ["node_modules/jest-expect-message/types/index.d.ts"]
}

Basic Usage

// Basic custom message
test('should add numbers correctly', () => {
  expect(1 + 1, 'Addition should work correctly').toBe(2);
});

// Custom message with options
test('should validate user input', () => {
  const user = { name: 'Alice', age: 25 };
  expect(user.age, 'Age should be a valid number', { 
    showPrefix: false 
  }).toBeGreaterThan(18);
});

// Works with all Jest matchers
test('should handle arrays', () => {
  const items = ['apple', 'banana'];
  expect(items, 'Array should contain expected items').toContain('apple');
});

// Async expectations
test('should handle promises', async () => {
  await expect(
    Promise.resolve('success'), 
    'Promise should resolve with success message'
  ).resolves.toBe('success');
});

Capabilities

Enhanced Expect Function

The core functionality that enhances Jest's expect function to accept custom messages.

/**
 * Enhanced expect function with custom message support
 * @param actual - The value to test (same as standard Jest expect)
 * @param message - Optional custom error message to display on failure
 * @param options - Optional configuration for message display
 * @returns Jest matchers with custom message support
 */
expect(actual, message?, options?);

Parameters:

  • actual: any - The value you would normally pass into an expect to assert against
  • message: string (optional) - Custom message displayed when the expectation fails
  • options: MessageOptions (optional) - Configuration object controlling message display

Returns: Standard Jest matchers (JestMatchers<T>) with custom message functionality

Message Display Options

Configuration object for controlling how custom messages are displayed in test failures.

interface MessageOptions {
  /** Show "Custom message:" prefix before the message. Default: true */
  showPrefix?: boolean;
  /** Show the original matcher error message. Default: true */
  showMatcherMessage?: boolean;
  /** Show the stack trace in error output. Default: true */
  showStack?: boolean;
}

Properties:

  • showPrefix: boolean - Controls whether "Custom message:" prefix is shown (default: true)
  • showMatcherMessage: boolean - Controls whether original Jest matcher message is shown (default: true)
  • showStack: boolean - Controls whether stack trace is included in error output (default: true)

Enhanced Expect.extend Method

The enhanced expect function preserves Jest's extend functionality for adding custom matchers.

/**
 * Extend Jest with custom matchers while preserving message functionality
 * @param matchers - Object containing custom matcher functions
 */
expect.extend(matchers);

Parameters:

  • matchers: object - Custom matchers to add to Jest's expect function

Usage Example:

expect.extend({
  toBeDivisibleBy(received, argument) {
    const pass = received % argument === 0;
    const message = pass
      ? () => `expected ${received} not to be divisible by ${argument}`
      : () => `expected ${received} to be divisible by ${argument}`;
    return { message, pass };
  }
});

// Use custom matcher with custom message
test('custom matcher with message', () => {
  expect(100, '100 should be divisible by 10').toBeDivisibleBy(10);
});

Message Display Examples

Default Message Display

test('default message display', () => {
  expect(1 + 1, 'Math should work correctly').toBe(3);
});

Error Output:

Custom message:
  Math should work correctly

expect(received).toBe(expected) // Object.is equality

Expected: 3
Received: 2

Hide Message Prefix

test('hide prefix', () => {
  expect(1 + 1, 'Math should work correctly', { 
    showPrefix: false 
  }).toBe(3);
});

Error Output:

Math should work correctly

expect(received).toBe(expected) // Object.is equality

Expected: 3
Received: 2

Hide Original Matcher Message

test('hide matcher message', () => {
  expect(1 + 1, 'Math should work correctly', { 
    showMatcherMessage: false 
  }).toBe(3);
});

Error Output:

Custom message:
  Math should work correctly

Hide Stack Trace

test('hide stack trace', () => {
  expect(1 + 1, 'Math should work correctly', { 
    showStack: false 
  }).toBe(3);
});

Error Output:

Custom message:
  Math should work correctly

expect(received).toBe(expected) // Object.is equality

Expected: 3
Received: 2

TypeScript Support

The package includes comprehensive TypeScript definitions for type safety and IntelliSense support.

declare namespace jest {
  interface Expect {
    <T = any>(
      actual: T,
      message?: string,
      options?: { 
        showMatcherMessage?: boolean; 
        showPrefix?: boolean; 
        showStack?: boolean 
      }
    ): JestMatchers<T>;
  }
}

TypeScript Usage:

test('TypeScript example', () => {
  const user: { name: string; age: number } = { name: 'Alice', age: 25 };
  expect(user.age, 'Age should be valid').toBeGreaterThan(0);
});

Compatibility and Integration

Jest Matcher Compatibility

  • All Standard Matchers: Works with toBe, toEqual, toContain, toBeGreaterThan, etc.
  • Negation Matchers: Compatible with .not modifiers
  • Async Matchers: Supports .resolves and .rejects for Promise testing
  • Custom Matchers: Integrates seamlessly with expect.extend() custom matchers
  • Asymmetric Matchers: Works with expect.any(), expect.objectContaining(), etc.

ESLint Configuration

When using ESLint with jest rules, configure to allow 2 arguments for expect:

{
  "rules": {
    "jest/valid-expect": [
      "error",
      {
        "maxArgs": 2
      }
    ]
  }
}

Setup Requirements

The package must be loaded before Jest runs tests. It modifies the global expect function to add message support while preserving all existing functionality.

Important Notes:

  • No runtime dependencies
  • Compatible with all Jest versions
  • Preserves all existing Jest functionality
  • Adds zero overhead when messages are not used
  • Maintains full TypeScript type safety