or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

index.md
tile.json

index.mddocs/

0

# Jest Message Util

1

2

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.

3

4

## Package Information

5

6

- **Package Name**: jest-message-util

7

- **Package Type**: npm

8

- **Language**: TypeScript

9

- **Installation**: `npm install jest-message-util`

10

11

## Core Imports

12

13

```typescript

14

import {

15

formatExecError,

16

formatResultsErrors,

17

formatStackTrace,

18

getStackTraceLines,

19

getTopFrame,

20

formatPath,

21

indentAllLines,

22

separateMessageFromStack,

23

type Frame,

24

type StackTraceConfig,

25

type StackTraceOptions

26

} from "jest-message-util";

27

```

28

29

For CommonJS:

30

31

```javascript

32

const {

33

formatExecError,

34

formatResultsErrors,

35

formatStackTrace,

36

getStackTraceLines,

37

getTopFrame,

38

formatPath,

39

indentAllLines,

40

separateMessageFromStack

41

} = require("jest-message-util");

42

```

43

44

## Basic Usage

45

46

```typescript

47

import {

48

formatExecError,

49

formatResultsErrors,

50

formatStackTrace,

51

type StackTraceConfig,

52

type StackTraceOptions

53

} from "jest-message-util";

54

55

// Configuration for stack trace formatting

56

const config: StackTraceConfig = {

57

rootDir: "/project/root",

58

testMatch: ["**/*.test.js", "**/*.spec.js"]

59

};

60

61

const options: StackTraceOptions = {

62

noStackTrace: false,

63

noCodeFrame: false

64

};

65

66

// Format an execution error (outside test suites)

67

const execError = new Error("Test suite failed to run");

68

execError.stack = "Error: Test suite failed to run\n at Object.<anonymous> (/path/to/test.js:10:5)";

69

70

const formattedExecError = formatExecError(

71

execError,

72

config,

73

options,

74

"/path/to/test.js"

75

);

76

77

// Format test result errors (assertion failures)

78

const testResults = [

79

{

80

ancestorTitles: ["describe block"],

81

title: "should pass",

82

failureMessages: ["Expected 1 to equal 2"],

83

failureDetails: [new Error("Expected 1 to equal 2")]

84

}

85

];

86

87

const formattedResults = formatResultsErrors(

88

testResults,

89

config,

90

options,

91

"/path/to/test.js"

92

);

93

```

94

95

## Architecture

96

97

Jest Message Util is built around several key components:

98

99

- **Error Formatting**: Core functions for formatting different types of errors with proper indentation and structure

100

- **Stack Trace Processing**: Utilities for parsing, filtering, and formatting stack traces with code frames

101

- **Path Management**: Functions for converting absolute paths to relative paths and highlighting test files

102

- **Environment Detection**: Special handling for common environment-related errors (DOM/Node.js mismatches)

103

- **Type System**: Full TypeScript support with comprehensive type definitions for all configuration options

104

105

## Capabilities

106

107

### Execution Error Formatting

108

109

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

110

111

```typescript { .api }

112

/**

113

* Formats execution errors that occur outside of test suites

114

* @param error - The error to format (supports various error types)

115

* @param config - Stack trace configuration with rootDir and testMatch

116

* @param options - Formatting options for stack traces and code frames

117

* @param testPath - Optional path to the test file for highlighting

118

* @param reuseMessage - Whether to reuse existing message formatting

119

* @param noTitle - Whether to suppress the error title

120

* @returns Formatted error message with stack trace and code frame

121

*/

122

function formatExecError(

123

error: Error | TestResult.SerializableError | string | number | undefined,

124

config: StackTraceConfig,

125

options: StackTraceOptions,

126

testPath?: string,

127

reuseMessage?: boolean,

128

noTitle?: boolean

129

): string;

130

```

131

132

### Test Result Error Formatting

133

134

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

135

136

```typescript { .api }

137

/**

138

* Formats multiple test result errors with titles and proper grouping

139

* @param testResults - Array of test assertion results with failure messages

140

* @param config - Stack trace configuration

141

* @param options - Formatting options

142

* @param testPath - Optional test file path for highlighting

143

* @returns Formatted error messages grouped by test, or null if no failures

144

*/

145

function formatResultsErrors(

146

testResults: Array<TestResult.AssertionResult>,

147

config: StackTraceConfig,

148

options: StackTraceOptions,

149

testPath?: string

150

): string | null;

151

```

152

153

### Stack Trace Formatting

154

155

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

156

157

```typescript { .api }

158

/**

159

* Formats complete stack traces with code frames and proper indentation

160

* @param stack - The raw stack trace string

161

* @param config - Stack trace configuration for path formatting

162

* @param options - Options controlling display of stack traces and code frames

163

* @param testPath - Optional test file path for relative path calculation

164

* @returns Formatted stack trace with code frames and colored paths

165

*/

166

function formatStackTrace(

167

stack: string,

168

config: StackTraceConfig,

169

options: StackTraceOptions,

170

testPath?: string

171

): string;

172

```

173

174

### Stack Trace Line Processing

175

176

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

177

178

```typescript { .api }

179

/**

180

* Extracts and filters stack trace lines, removing internal entries

181

* @param stack - The full stack trace string

182

* @param options - Optional formatting options with filtering controls

183

* @returns Array of filtered stack trace lines with internal entries removed

184

*/

185

function getStackTraceLines(

186

stack: string,

187

options?: StackTraceOptions

188

): Array<string>;

189

```

190

191

### Stack Frame Extraction

192

193

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

194

195

```typescript { .api }

196

/**

197

* Extracts the top-most relevant frame from stack trace lines

198

* @param lines - Array of stack trace lines to parse

199

* @returns Parsed frame object with file, line, and column info, or null if none found

200

*/

201

function getTopFrame(lines: Array<string>): Frame | null;

202

```

203

204

### Path Formatting

205

206

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

207

208

```typescript { .api }

209

/**

210

* Formats file paths in stack traces with highlighting and relative paths

211

* @param line - The stack trace line containing the file path

212

* @param config - Configuration with rootDir for relative path calculation

213

* @param relativeTestPath - Relative test path for highlighting (default: null)

214

* @returns Formatted line with highlighted and relative file path

215

*/

216

function formatPath(

217

line: string,

218

config: StackTraceConfig,

219

relativeTestPath?: string | null

220

): string;

221

```

222

223

### Text Indentation

224

225

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

226

227

```typescript { .api }

228

/**

229

* Indents all non-empty lines in a string with MESSAGE_INDENT

230

* @param lines - The input string to indent

231

* @returns String with all non-empty lines indented

232

*/

233

function indentAllLines(lines: string): string;

234

```

235

236

### Message and Stack Separation

237

238

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

239

240

```typescript { .api }

241

/**

242

* Separates error messages from stack traces using regex parsing

243

* @param content - The raw error content containing both message and stack

244

* @returns Object with separated message and stack components

245

*/

246

function separateMessageFromStack(

247

content: string

248

): { message: string; stack: string };

249

```

250

251

## Types

252

253

### Frame Interface

254

255

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

256

257

```typescript { .api }

258

/**

259

* Stack trace frame information extending StackData from stack-utils

260

*/

261

interface Frame extends StackData {

262

/** The file path where the stack frame occurred */

263

file: string;

264

}

265

266

/**

267

* Stack data from stack-utils parser

268

*/

269

interface StackData {

270

/** Line number in the source file */

271

line?: number;

272

/** Column number in the source file */

273

column?: number;

274

/** File path where the frame occurred */

275

file?: string;

276

/** Whether this frame is a constructor call */

277

constructor?: boolean;

278

/** Eval origin information if the frame is from eval'd code */

279

evalOrigin?: string;

280

/** Whether this frame is a native function call */

281

native?: boolean;

282

/** Function name if available */

283

function?: string;

284

/** Method name if this is a method call */

285

method?: string;

286

}

287

```

288

289

### Stack Trace Configuration

290

291

Configuration options for stack trace formatting and path handling.

292

293

```typescript { .api }

294

/**

295

* Configuration for stack trace formatting, picked from Jest's ProjectConfig

296

*/

297

type StackTraceConfig = {

298

/** Root directory for calculating relative paths */

299

rootDir: string;

300

/** Glob patterns for matching test files (for highlighting) */

301

testMatch: Array<string>;

302

};

303

```

304

305

### Stack Trace Options

306

307

Options controlling the display of stack traces and code frames.

308

309

```typescript { .api }

310

/**

311

* Options for controlling stack trace and code frame display

312

*/

313

type StackTraceOptions = {

314

/** Whether to suppress stack trace output entirely */

315

noStackTrace: boolean;

316

/** Whether to suppress code frame generation around error locations */

317

noCodeFrame?: boolean;

318

};

319

```

320

321

### Test Result Types

322

323

Types for handling Jest test results and serializable errors.

324

325

```typescript { .api }

326

/**

327

* Namespace containing Jest test result types

328

*/

329

namespace TestResult {

330

/**

331

* Serializable error object used in Jest test results

332

*/

333

interface SerializableError {

334

/** Error code if available */

335

code?: unknown;

336

/** Error message */

337

message: string;

338

/** Stack trace string or null */

339

stack: string | null | undefined;

340

/** Error type name */

341

type?: string;

342

}

343

344

/**

345

* Result of a single test assertion

346

*/

347

interface AssertionResult {

348

/** Array of ancestor describe block titles */

349

ancestorTitles: Array<string>;

350

/** Test execution duration in milliseconds */

351

duration?: number | null;

352

/** Array of failure messages for failed tests */

353

failureMessages: Array<string>;

354

/** Array of failure details objects */

355

failureDetails: Array<unknown>;

356

/** Full test name including ancestors */

357

fullName: string;

358

/** Number of passing assertions in this test */

359

numPassingAsserts: number;

360

/** Test execution status */

361

status: 'passed' | 'failed' | 'skipped' | 'pending' | 'todo' | 'disabled';

362

/** Test title (without ancestors) */

363

title: string;

364

/** Source location of the test if available */

365

location?: { column: number; line: number } | null;

366

}

367

}

368

```

369

370

## Error Handling

371

372

Jest Message Util provides comprehensive error handling features:

373

374

- **Environment Error Detection**: Automatically detects and warns about wrong test environments (DOM references in Node.js environment or vice versa)

375

- **Error Cause Chains**: Supports nested error causes and displays them with proper indentation

376

- **Aggregate Errors**: Handles AggregateError with multiple sub-errors and formats them individually

377

- **Malformed Error Handling**: Gracefully handles various error types including strings, numbers, and undefined values

378

379

## Advanced Features

380

381

### Code Frame Generation

382

383

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

384

385

```typescript

386

// Automatically shows code context around the error line

387

const formatted = formatStackTrace(error.stack, config, {

388

noStackTrace: false,

389

noCodeFrame: false // Enable code frames

390

});

391

```

392

393

### Path Highlighting

394

395

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

396

397

```typescript

398

const config: StackTraceConfig = {

399

rootDir: "/project",

400

testMatch: ["**/*.test.js", "**/*.spec.ts"] // These paths will be highlighted

401

};

402

```

403

404

### Internal Filtering

405

406

Stack traces automatically filter out:

407

- Node.js internals

408

- Jest framework internals

409

- Anonymous functions and promises

410

- Jasmine test runner internals

411

- Native function calls

412

413

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