Pretty Format

30.3.0 · active · verified Sun Apr 19

pretty-format is a robust utility for stringifying any JavaScript value, particularly useful for debugging and generating consistent output for snapshot testing. Maintained as a core package within the Jest testing framework, it is currently on version 30.3.0 and aligns its major releases with Jest itself, which aims for more frequent major updates going forward. Key differentiators include its extensibility through a powerful plugin system, allowing serialization of application-specific data types (often called snapshot serializers in the context of Jest). It can handle circular references, various built-in types, and offers extensive configuration options for output style, indentation, and color highlighting.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates basic usage of `pretty-format` with a complex object, including circular references, various JavaScript types, and the use of built-in React plugins and a simple custom plugin.

import { format, plugins } from 'pretty-format';

const { ReactElement, ReactTestComponent } = plugins;

const val = {
  string: 'hello world',
  number: 123.45,
  boolean: true,
  array: [-0, Infinity, NaN, null, undefined],
  object: { key: 'value', nested: { id: 1 } },
  circularReference: null,
  map: new Map([['prop', 'value']]),
  set: new Set([1, 2, 3]),
  symbol: Symbol('description'),
  func: function myFunc() {},
  date: new Date('2023-01-01T12:00:00.000Z')
};

val.circularReference = val; // Create a circular reference

const options = {
  indent: 2,
  min: false,
  callToJSON: true,
  plugins: [ReactElement, ReactTestComponent]
};

console.log(format(val, options));

// Example with a custom plugin (simple)
const customPlugin = {
  test(value) {
    return value instanceof Error;
  },
  serialize(value, config, indentation, depth, refs, printer) {
    return `Custom Error: ${value.message}`;
  },
};

const error = new Error('Something went wrong');
console.log(format(error, { plugins: [customPlugin] }));

view raw JSON →