or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/npm-jest-message-util

A utility library for formatting error messages, stack traces, and test results in Jest testing framework with enhanced error reporting.

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

To install, run

npx @tessl/cli install tessl/npm-jest-message-util@30.1.0

index.mddocs/

Jest Message Util

Jest Message Util is a comprehensive utility library for formatting error messages, stack traces, and test results in the Jest testing framework. It provides enhanced error reporting with syntax highlighting, code frames, path formatting, and intelligent filtering of internal stack trace entries.

Package Information

  • Package Name: jest-message-util
  • Package Type: npm
  • Language: TypeScript
  • Installation: npm install jest-message-util

Core Imports

import {
  formatExecError,
  formatResultsErrors,
  formatStackTrace,
  getStackTraceLines,
  getTopFrame,
  formatPath,
  indentAllLines,
  separateMessageFromStack,
  type Frame,
  type StackTraceConfig,
  type StackTraceOptions
} from "jest-message-util";

For CommonJS:

const {
  formatExecError,
  formatResultsErrors,
  formatStackTrace,
  getStackTraceLines,
  getTopFrame,
  formatPath,
  indentAllLines,
  separateMessageFromStack
} = require("jest-message-util");

Basic Usage

import {
  formatExecError,
  formatResultsErrors,
  formatStackTrace,
  type StackTraceConfig,
  type StackTraceOptions
} from "jest-message-util";

// Configuration for stack trace formatting
const config: StackTraceConfig = {
  rootDir: "/project/root",
  testMatch: ["**/*.test.js", "**/*.spec.js"]
};

const options: StackTraceOptions = {
  noStackTrace: false,
  noCodeFrame: false
};

// Format an execution error (outside test suites)
const execError = new Error("Test suite failed to run");
execError.stack = "Error: Test suite failed to run\n    at Object.<anonymous> (/path/to/test.js:10:5)";

const formattedExecError = formatExecError(
  execError,
  config,
  options,
  "/path/to/test.js"
);

// Format test result errors (assertion failures)
const testResults = [
  {
    ancestorTitles: ["describe block"],
    title: "should pass",
    failureMessages: ["Expected 1 to equal 2"],
    failureDetails: [new Error("Expected 1 to equal 2")]
  }
];

const formattedResults = formatResultsErrors(
  testResults,
  config,
  options,
  "/path/to/test.js"
);

Architecture

Jest Message Util is built around several key components:

  • Error Formatting: Core functions for formatting different types of errors with proper indentation and structure
  • Stack Trace Processing: Utilities for parsing, filtering, and formatting stack traces with code frames
  • Path Management: Functions for converting absolute paths to relative paths and highlighting test files
  • Environment Detection: Special handling for common environment-related errors (DOM/Node.js mismatches)
  • Type System: Full TypeScript support with comprehensive type definitions for all configuration options

Capabilities

Execution Error Formatting

Formats execution errors that occur outside of test suites with proper stack traces, code frames, and error cause handling.

/**
 * Formats execution errors that occur outside of test suites
 * @param error - The error to format (supports various error types)
 * @param config - Stack trace configuration with rootDir and testMatch
 * @param options - Formatting options for stack traces and code frames
 * @param testPath - Optional path to the test file for highlighting
 * @param reuseMessage - Whether to reuse existing message formatting
 * @param noTitle - Whether to suppress the error title
 * @returns Formatted error message with stack trace and code frame
 */
function formatExecError(
  error: Error | TestResult.SerializableError | string | number | undefined,
  config: StackTraceConfig,
  options: StackTraceOptions,
  testPath?: string,
  reuseMessage?: boolean,
  noTitle?: boolean
): string;

Test Result Error Formatting

Formats multiple test result errors with titles, proper grouping, and ancestor test descriptions.

/**
 * Formats multiple test result errors with titles and proper grouping
 * @param testResults - Array of test assertion results with failure messages
 * @param config - Stack trace configuration
 * @param options - Formatting options
 * @param testPath - Optional test file path for highlighting
 * @returns Formatted error messages grouped by test, or null if no failures
 */
function formatResultsErrors(
  testResults: Array<TestResult.AssertionResult>,
  config: StackTraceConfig,
  options: StackTraceOptions,
  testPath?: string
): string | null;

Stack Trace Formatting

Formats complete stack traces with code frames, relative paths, and proper indentation.

/**
 * Formats complete stack traces with code frames and proper indentation
 * @param stack - The raw stack trace string
 * @param config - Stack trace configuration for path formatting
 * @param options - Options controlling display of stack traces and code frames
 * @param testPath - Optional test file path for relative path calculation
 * @returns Formatted stack trace with code frames and colored paths
 */
function formatStackTrace(
  stack: string,
  config: StackTraceConfig,
  options: StackTraceOptions,
  testPath?: string
): string;

Stack Trace Line Processing

Extracts and filters stack trace lines, removing Jest internals and node modules.

/**
 * Extracts and filters stack trace lines, removing internal entries
 * @param stack - The full stack trace string
 * @param options - Optional formatting options with filtering controls
 * @returns Array of filtered stack trace lines with internal entries removed
 */
function getStackTraceLines(
  stack: string,
  options?: StackTraceOptions
): Array<string>;

Stack Frame Extraction

Extracts the top-most relevant frame from stack trace lines, skipping node_modules and Jest internals.

/**
 * Extracts the top-most relevant frame from stack trace lines
 * @param lines - Array of stack trace lines to parse
 * @returns Parsed frame object with file, line, and column info, or null if none found
 */
function getTopFrame(lines: Array<string>): Frame | null;

Path Formatting

Formats file paths in stack traces with proper highlighting and relative path conversion.

/**
 * Formats file paths in stack traces with highlighting and relative paths
 * @param line - The stack trace line containing the file path
 * @param config - Configuration with rootDir for relative path calculation
 * @param relativeTestPath - Relative test path for highlighting (default: null)
 * @returns Formatted line with highlighted and relative file path
 */
function formatPath(
  line: string,
  config: StackTraceConfig,
  relativeTestPath?: string | null
): string;

Text Indentation

Indents all non-empty lines in a string with proper message indentation.

/**
 * Indents all non-empty lines in a string with MESSAGE_INDENT
 * @param lines - The input string to indent
 * @returns String with all non-empty lines indented
 */
function indentAllLines(lines: string): string;

Message and Stack Separation

Separates error messages from stack traces using regex parsing for proper formatting.

/**
 * Separates error messages from stack traces using regex parsing
 * @param content - The raw error content containing both message and stack
 * @returns Object with separated message and stack components
 */
function separateMessageFromStack(
  content: string
): { message: string; stack: string };

Types

Frame Interface

Represents a stack trace frame with file location and parsing information.

/**
 * Stack trace frame information extending StackData from stack-utils
 */
interface Frame extends StackData {
  /** The file path where the stack frame occurred */
  file: string;
}

/**
 * Stack data from stack-utils parser
 */
interface StackData {
  /** Line number in the source file */
  line?: number;
  /** Column number in the source file */
  column?: number;
  /** File path where the frame occurred */
  file?: string;
  /** Whether this frame is a constructor call */
  constructor?: boolean;
  /** Eval origin information if the frame is from eval'd code */
  evalOrigin?: string;
  /** Whether this frame is a native function call */
  native?: boolean;
  /** Function name if available */
  function?: string;
  /** Method name if this is a method call */
  method?: string;
}

Stack Trace Configuration

Configuration options for stack trace formatting and path handling.

/**
 * Configuration for stack trace formatting, picked from Jest's ProjectConfig
 */
type StackTraceConfig = {
  /** Root directory for calculating relative paths */
  rootDir: string;
  /** Glob patterns for matching test files (for highlighting) */
  testMatch: Array<string>;
};

Stack Trace Options

Options controlling the display of stack traces and code frames.

/**
 * Options for controlling stack trace and code frame display
 */
type StackTraceOptions = {
  /** Whether to suppress stack trace output entirely */
  noStackTrace: boolean;
  /** Whether to suppress code frame generation around error locations */
  noCodeFrame?: boolean;
};

Test Result Types

Types for handling Jest test results and serializable errors.

/**
 * Namespace containing Jest test result types
 */
namespace TestResult {
  /**
   * Serializable error object used in Jest test results
   */
  interface SerializableError {
    /** Error code if available */
    code?: unknown;
    /** Error message */
    message: string;
    /** Stack trace string or null */
    stack: string | null | undefined;
    /** Error type name */
    type?: string;
  }

  /**
   * Result of a single test assertion
   */
  interface AssertionResult {
    /** Array of ancestor describe block titles */
    ancestorTitles: Array<string>;
    /** Test execution duration in milliseconds */
    duration?: number | null;
    /** Array of failure messages for failed tests */
    failureMessages: Array<string>;
    /** Array of failure details objects */
    failureDetails: Array<unknown>;
    /** Full test name including ancestors */
    fullName: string;
    /** Number of passing assertions in this test */
    numPassingAsserts: number;
    /** Test execution status */
    status: 'passed' | 'failed' | 'skipped' | 'pending' | 'todo' | 'disabled';
    /** Test title (without ancestors) */
    title: string;
    /** Source location of the test if available */
    location?: { column: number; line: number } | null;
  }
}

Error Handling

Jest Message Util provides comprehensive error handling features:

  • Environment Error Detection: Automatically detects and warns about wrong test environments (DOM references in Node.js environment or vice versa)
  • Error Cause Chains: Supports nested error causes and displays them with proper indentation
  • Aggregate Errors: Handles AggregateError with multiple sub-errors and formats them individually
  • Malformed Error Handling: Gracefully handles various error types including strings, numbers, and undefined values

Advanced Features

Code Frame Generation

When formatting stack traces, the library automatically generates code frames showing the relevant source code around error locations:

// Automatically shows code context around the error line
const formatted = formatStackTrace(error.stack, config, {
  noStackTrace: false,
  noCodeFrame: false  // Enable code frames
});

Path Highlighting

Test files are automatically highlighted in stack traces based on the testMatch configuration:

const config: StackTraceConfig = {
  rootDir: "/project",
  testMatch: ["**/*.test.js", "**/*.spec.ts"]  // These paths will be highlighted
};

Internal Filtering

Stack traces automatically filter out:

  • Node.js internals
  • Jest framework internals
  • Anonymous functions and promises
  • Jasmine test runner internals
  • Native function calls

The filtering preserves the first stack frame even if it's from Jest to maintain useful debugging context.