A utility library for formatting error messages, stack traces, and test results in Jest testing framework with enhanced error reporting.
npx @tessl/cli install tessl/npm-jest-message-util@30.1.0Jest 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.
npm install jest-message-utilimport {
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");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"
);Jest Message Util is built around several key components:
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;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;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;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>;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;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;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;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 };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;
}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>;
};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;
};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;
}
}Jest Message Util provides comprehensive error handling features:
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
});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
};Stack traces automatically filter out:
The filtering preserves the first stack frame even if it's from Jest to maintain useful debugging context.