3 > Stringify any JavaScript value.
5 - Supports all built-in JavaScript types
6 - primitive types: `Boolean`, `null`, `Number`, `String`, `Symbol`, `undefined`
7 - other non-collection types: `Date`, `Error`, `Function`, `RegExp`
9 - `arguments`, `Array`, `ArrayBuffer`, `DataView`, `Float32Array`, `Float64Array`, `Int8Array`, `Int16Array`, `Int32Array`, `Uint8Array`, `Uint8ClampedArray`, `Uint16Array`, `Uint32Array`,
10 - `Map`, `Set`, `WeakMap`, `WeakSet`
12 - [Blazingly fast](https://gist.github.com/thejameskyle/2b04ffe4941aafa8f970de077843a8fd)
13 - similar performance to `JSON.stringify` in v8
14 - significantly faster than `util.format` in Node.js
15 - Serialize application-specific data types with built-in or user-defined plugins
20 $ yarn add pretty-format
26 const prettyFormat = require('pretty-format'); // CommonJS
30 import prettyFormat from 'pretty-format'; // ES2015 modules
34 const val = {object: {}};
35 val.circularReference = val;
36 val[Symbol('foo')] = 'foo';
37 val.map = new Map([['prop', 'value']]);
38 val.array = [-0, Infinity, NaN];
40 console.log(prettyFormat(val));
48 "circularReference": [Circular],
63 console.log(prettyFormat(onClick));
69 printFunctionName: false,
71 console.log(prettyFormat(onClick, options));
77 | key | type | default | description |
78 | :------------------ | :-------- | :--------- | :------------------------------------------------------ |
79 | `callToJSON` | `boolean` | `true` | call `toJSON` method (if it exists) on objects |
80 | `escapeRegex` | `boolean` | `false` | escape special characters in regular expressions |
81 | `highlight` | `boolean` | `false` | highlight syntax with colors in terminal (some plugins) |
82 | `indent` | `number` | `2` | spaces in each level of indentation |
83 | `maxDepth` | `number` | `Infinity` | levels to print in arrays, objects, elements, and so on |
84 | `min` | `boolean` | `false` | minimize added space: no indentation nor line breaks |
85 | `plugins` | `array` | `[]` | plugins to serialize application-specific data types |
86 | `printFunctionName` | `boolean` | `true` | include or omit the name of a function |
87 | `theme` | `object` | | colors to highlight syntax in terminal |
89 Property values of `theme` are from [ansi-styles colors](https://github.com/chalk/ansi-styles#colors)
92 const DEFAULT_THEME = {
101 ## Usage with plugins
103 The `pretty-format` package provides some built-in plugins, including:
105 - `ReactElement` for elements from `react`
106 - `ReactTestComponent` for test objects from `react-test-renderer`
110 const prettyFormat = require('pretty-format');
111 const ReactElement = prettyFormat.plugins.ReactElement;
112 const ReactTestComponent = prettyFormat.plugins.ReactTestComponent;
114 const React = require('react');
115 const renderer = require('react-test-renderer');
119 // ES2015 modules and destructuring assignment
120 import prettyFormat from 'pretty-format';
121 const {ReactElement, ReactTestComponent} = prettyFormat.plugins;
123 import React from 'react';
124 import renderer from 'react-test-renderer';
128 const onClick = () => {};
129 const element = React.createElement('button', {onClick}, 'Hello World');
131 const formatted1 = prettyFormat(element, {
132 plugins: [ReactElement],
133 printFunctionName: false,
135 const formatted2 = prettyFormat(renderer.create(element).toJSON(), {
136 plugins: [ReactTestComponent],
137 printFunctionName: false,
150 For snapshot tests, Jest uses `pretty-format` with options that include some of its built-in plugins. For this purpose, plugins are also known as **snapshot serializers**.
152 To serialize application-specific data types, you can add modules to `devDependencies` of a project, and then:
154 In an **individual** test file, you can add a module as follows. It precedes any modules from Jest configuration.
157 import serializer from 'my-serializer-module';
158 expect.addSnapshotSerializer(serializer);
160 // tests which have `expect(value).toMatchSnapshot()` assertions
163 For **all** test files, you can specify modules in Jest configuration. They precede built-in plugins for React, HTML, and Immutable.js data types. For example, in a `package.json` file:
168 "snapshotSerializers": ["my-serializer-module"]
175 A plugin is a JavaScript object.
177 If `options` has a `plugins` array: for the first plugin whose `test(val)` method returns a truthy value, then `prettyFormat(val, options)` returns the result from either:
179 - `serialize(val, …)` method of the **improved** interface (available in **version 21** or later)
180 - `print(val, …)` method of the **original** interface (if plugin does not have `serialize` method)
184 Write `test` so it can receive `val` argument of any type. To serialize **objects** which have certain properties, then a guarded expression like `val != null && …` or more concise `val && …` prevents the following errors:
186 - `TypeError: Cannot read property 'whatever' of null`
187 - `TypeError: Cannot read property 'whatever' of undefined`
189 For example, `test` method of built-in `ReactElement` plugin:
192 const elementSymbol = Symbol.for('react.element');
193 const test = val => val && val.$$typeof === elementSymbol;
196 Pay attention to efficiency in `test` because `pretty-format` calls it often.
200 The **improved** interface is available in **version 21** or later.
202 Write `serialize` to return a string, given the arguments:
204 - `val` which “passed the test”
205 - unchanging `config` object: derived from `options`
206 - current `indentation` string: concatenate to `indent` from `config`
207 - current `depth` number: compare to `maxDepth` from `config`
208 - current `refs` array: find circular references in objects
209 - `printer` callback function: serialize children
213 | key | type | description |
214 | :------------------ | :-------- | :------------------------------------------------------ |
215 | `callToJSON` | `boolean` | call `toJSON` method (if it exists) on objects |
216 | `colors` | `Object` | escape codes for colors to highlight syntax |
217 | `escapeRegex` | `boolean` | escape special characters in regular expressions |
218 | `indent` | `string` | spaces in each level of indentation |
219 | `maxDepth` | `number` | levels to print in arrays, objects, elements, and so on |
220 | `min` | `boolean` | minimize added space: no indentation nor line breaks |
221 | `plugins` | `array` | plugins to serialize application-specific data types |
222 | `printFunctionName` | `boolean` | include or omit the name of a function |
223 | `spacingInner` | `strong` | spacing to separate items in a list |
224 | `spacingOuter` | `strong` | spacing to enclose a list of items |
226 Each property of `colors` in `config` corresponds to a property of `theme` in `options`:
228 - the key is the same (for example, `tag`)
229 - the value in `colors` is a object with `open` and `close` properties whose values are escape codes from [ansi-styles](https://github.com/chalk/ansi-styles) for the color value in `theme` (for example, `'cyan'`)
231 Some properties in `config` are derived from `min` in `options`:
233 - `spacingInner` and `spacingOuter` are **newline** if `min` is `false`
234 - `spacingInner` is **space** and `spacingOuter` is **empty string** if `min` is `true`
236 ### Example of serialize and test
238 This plugin is a pattern you can apply to serialize composite data types. Of course, `pretty-format` does not need a plugin to serialize arrays :)
241 // We reused more code when we factored out a function for child items
242 // that is independent of depth, name, and enclosing punctuation (see below).
243 const SEPARATOR = ',';
244 function serializeItems(items, config, indentation, depth, refs, printer) {
245 if (items.length === 0) {
248 const indentationItems = indentation + config.indent;
250 config.spacingOuter +
255 printer(item, config, indentationItems, depth, refs), // callback
257 .join(SEPARATOR + config.spacingInner) +
258 (config.min ? '' : SEPARATOR) + // following the last item
259 config.spacingOuter +
266 return Array.isArray(val);
268 serialize(array, config, indentation, depth, refs, printer) {
269 const name = array.constructor.name;
270 return ++depth > config.maxDepth
272 : (config.min ? '' : name + ' ') +
274 serializeItems(array, config, indentation, depth, refs, printer) +
289 text: 'Write serialize',
304 "filter": "completed",
308 "text": "Write test",
312 "text": "Write serialize",
328 "filter": "completed",
332 "text": "Write test",
336 "text": "Write serialize",
352 "filter": "completed",
366 {"filter": "completed", "items": [{"completed": true, "text": "Write test"}, {"completed": true, "text": "Write serialize"}]}
372 The **original** interface is adequate for plugins:
374 - that **do not** depend on options other than `highlight` or `min`
375 - that **do not** depend on `depth` or `refs` in recursive traversal, and
377 - do **not** require indentation, or
378 - do **not** occur as children of JavaScript data structures (for example, array)
380 Write `print` to return a string, given the arguments:
382 - `val` which “passed the test”
383 - current `printer(valChild)` callback function: serialize children
384 - current `indenter(lines)` callback function: indent lines at the next level
385 - unchanging `config` object: derived from `options`
386 - unchanging `colors` object: derived from `options`
388 The 3 properties of `config` are `min` in `options` and:
390 - `spacing` and `edgeSpacing` are **newline** if `min` is `false`
391 - `spacing` is **space** and `edgeSpacing` is **empty string** if `min` is `true`
393 Each property of `colors` corresponds to a property of `theme` in `options`:
395 - the key is the same (for example, `tag`)
396 - the value in `colors` is a object with `open` and `close` properties whose values are escape codes from [ansi-styles](https://github.com/chalk/ansi-styles) for the color value in `theme` (for example, `'cyan'`)
398 ### Example of print and test
400 This plugin prints functions with the **number of named arguments** excluding rest argument.
405 return `[Function ${val.name || 'anonymous'} ${val.length}]`;
408 return typeof val === 'function';
424 "onClick": [Function onClick 1],
425 "render": [Function render 0],
432 "onClick": [Function onClick],
433 "render": [Function render],
438 This plugin **ignores** the `printFunctionName` option. That limitation of the original `print` interface is a reason to use the improved `serialize` interface, described above.
442 plugins: [pluginOld],
443 printFunctionName: false,
447 "onClick": [Function onClick 1],
448 "render": [Function render 0],
453 printFunctionName: false,
457 "onClick": [Function],
458 "render": [Function],