1 | # pretty-format
|
2 |
|
3 | Stringify any JavaScript value.
|
4 |
|
5 | - Serialize built-in JavaScript types.
|
6 | - Serialize application-specific data types with built-in or user-defined plugins.
|
7 |
|
8 | ## Installation
|
9 |
|
10 | ```sh
|
11 | $ yarn add pretty-format
|
12 | ```
|
13 |
|
14 | ## Usage
|
15 |
|
16 | ```js
|
17 | const prettyFormat = require('pretty-format'); // CommonJS
|
18 | ```
|
19 |
|
20 | ```js
|
21 | import prettyFormat from 'pretty-format'; // ES2015 modules
|
22 | ```
|
23 |
|
24 | ```js
|
25 | const val = {object: {}};
|
26 | val.circularReference = val;
|
27 | val[Symbol('foo')] = 'foo';
|
28 | val.map = new Map([['prop', 'value']]);
|
29 | val.array = [-0, Infinity, NaN];
|
30 |
|
31 | console.log(prettyFormat(val));
|
32 | /*
|
33 | Object {
|
34 | "array": Array [
|
35 | -0,
|
36 | Infinity,
|
37 | NaN,
|
38 | ],
|
39 | "circularReference": [Circular],
|
40 | "map": Map {
|
41 | "prop" => "value",
|
42 | },
|
43 | "object": Object {},
|
44 | Symbol(foo): "foo",
|
45 | }
|
46 | */
|
47 | ```
|
48 |
|
49 | ## Usage with options
|
50 |
|
51 | ```js
|
52 | function onClick() {}
|
53 |
|
54 | console.log(prettyFormat(onClick));
|
55 | /*
|
56 | [Function onClick]
|
57 | */
|
58 |
|
59 | const options = {
|
60 | printFunctionName: false,
|
61 | };
|
62 | console.log(prettyFormat(onClick, options));
|
63 | /*
|
64 | [Function]
|
65 | */
|
66 | ```
|
67 |
|
68 |
|
69 | | key | type | default | description |
|
70 | | :------------------ | :-------- | :--------- | :------------------------------------------------------ |
|
71 | | `callToJSON` | `boolean` | `true` | call `toJSON` method (if it exists) on objects |
|
72 | | `escapeRegex` | `boolean` | `false` | escape special characters in regular expressions |
|
73 | | `escapeString` | `boolean` | `true` | escape special characters in strings |
|
74 | | `highlight` | `boolean` | `false` | highlight syntax with colors in terminal (some plugins) |
|
75 | | `indent` | `number` | `2` | spaces in each level of indentation |
|
76 | | `maxDepth` | `number` | `Infinity` | levels to print in arrays, objects, elements, and so on |
|
77 | | `min` | `boolean` | `false` | minimize added space: no indentation nor line breaks |
|
78 | | `plugins` | `array` | `[]` | plugins to serialize application-specific data types |
|
79 | | `printFunctionName` | `boolean` | `true` | include or omit the name of a function |
|
80 | | `theme` | `object` | | colors to highlight syntax in terminal |
|
81 |
|
82 | Property values of `theme` are from [ansi-styles colors](https://github.com/chalk/ansi-styles#colors)
|
83 |
|
84 | ```js
|
85 | const DEFAULT_THEME = {
|
86 | comment: 'gray',
|
87 | content: 'reset',
|
88 | prop: 'yellow',
|
89 | tag: 'cyan',
|
90 | value: 'green',
|
91 | };
|
92 | ```
|
93 |
|
94 | ## Usage with plugins
|
95 |
|
96 | The `pretty-format` package provides some built-in plugins, including:
|
97 |
|
98 | - `ReactElement` for elements from `react`
|
99 | - `ReactTestComponent` for test objects from `react-test-renderer`
|
100 |
|
101 | ```js
|
102 | // CommonJS
|
103 | const prettyFormat = require('pretty-format');
|
104 | const ReactElement = prettyFormat.plugins.ReactElement;
|
105 | const ReactTestComponent = prettyFormat.plugins.ReactTestComponent;
|
106 |
|
107 | const React = require('react');
|
108 | const renderer = require('react-test-renderer');
|
109 | ```
|
110 |
|
111 | ```js
|
112 | // ES2015 modules and destructuring assignment
|
113 | import prettyFormat from 'pretty-format';
|
114 | const {ReactElement, ReactTestComponent} = prettyFormat.plugins;
|
115 |
|
116 | import React from 'react';
|
117 | import renderer from 'react-test-renderer';
|
118 | ```
|
119 |
|
120 | ```js
|
121 | const onClick = () => {};
|
122 | const element = React.createElement('button', {onClick}, 'Hello World');
|
123 |
|
124 | const formatted1 = prettyFormat(element, {
|
125 | plugins: [ReactElement],
|
126 | printFunctionName: false,
|
127 | });
|
128 | const formatted2 = prettyFormat(renderer.create(element).toJSON(), {
|
129 | plugins: [ReactTestComponent],
|
130 | printFunctionName: false,
|
131 | });
|
132 | /*
|
133 | <button
|
134 | onClick=[Function]
|
135 | >
|
136 | Hello World
|
137 | </button>
|
138 | */
|
139 | ```
|
140 |
|
141 | ## Usage in Jest
|
142 |
|
143 | 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**.
|
144 |
|
145 | To serialize application-specific data types, you can add modules to `devDependencies` of a project, and then:
|
146 |
|
147 | In an **individual** test file, you can add a module as follows. It precedes any modules from Jest configuration.
|
148 |
|
149 | ```js
|
150 | import serializer from 'my-serializer-module';
|
151 | expect.addSnapshotSerializer(serializer);
|
152 |
|
153 | // tests which have `expect(value).toMatchSnapshot()` assertions
|
154 | ```
|
155 |
|
156 | 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:
|
157 |
|
158 | ```json
|
159 | {
|
160 | "jest": {
|
161 | "snapshotSerializers": ["my-serializer-module"]
|
162 | }
|
163 | }
|
164 | ```
|
165 |
|
166 | ## Writing plugins
|
167 |
|
168 | A plugin is a JavaScript object.
|
169 |
|
170 | 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:
|
171 |
|
172 | - `serialize(val, …)` method of the **improved** interface (available in **version 21** or later)
|
173 | - `print(val, …)` method of the **original** interface (if plugin does not have `serialize` method)
|
174 |
|
175 | ### test
|
176 |
|
177 | 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:
|
178 |
|
179 | - `TypeError: Cannot read property 'whatever' of null`
|
180 | - `TypeError: Cannot read property 'whatever' of undefined`
|
181 |
|
182 | For example, `test` method of built-in `ReactElement` plugin:
|
183 |
|
184 | ```js
|
185 | const elementSymbol = Symbol.for('react.element');
|
186 | const test = val => val && val.$$typeof === elementSymbol;
|
187 | ```
|
188 |
|
189 | Pay attention to efficiency in `test` because `pretty-format` calls it often.
|
190 |
|
191 | ### serialize
|
192 |
|
193 | The **improved** interface is available in **version 21** or later.
|
194 |
|
195 | Write `serialize` to return a string, given the arguments:
|
196 |
|
197 | - `val` which “passed the test”
|
198 | - unchanging `config` object: derived from `options`
|
199 | - current `indentation` string: concatenate to `indent` from `config`
|
200 | - current `depth` number: compare to `maxDepth` from `config`
|
201 | - current `refs` array: find circular references in objects
|
202 | - `printer` callback function: serialize children
|
203 |
|
204 | ### config
|
205 |
|
206 |
|
207 | | key | type | description |
|
208 | | :------------------ | :-------- | :------------------------------------------------------ |
|
209 | | `callToJSON` | `boolean` | call `toJSON` method (if it exists) on objects |
|
210 | | `colors` | `Object` | escape codes for colors to highlight syntax |
|
211 | | `escapeRegex` | `boolean` | escape special characters in regular expressions |
|
212 | | `escapeString` | `boolean` | escape special characters in strings |
|
213 | | `indent` | `string` | spaces in each level of indentation |
|
214 | | `maxDepth` | `number` | levels to print in arrays, objects, elements, and so on |
|
215 | | `min` | `boolean` | minimize added space: no indentation nor line breaks |
|
216 | | `plugins` | `array` | plugins to serialize application-specific data types |
|
217 | | `printFunctionName` | `boolean` | include or omit the name of a function |
|
218 | | `spacingInner` | `strong` | spacing to separate items in a list |
|
219 | | `spacingOuter` | `strong` | spacing to enclose a list of items |
|
220 |
|
221 | Each property of `colors` in `config` corresponds to a property of `theme` in `options`:
|
222 |
|
223 | - the key is the same (for example, `tag`)
|
224 | - 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'`)
|
225 |
|
226 | Some properties in `config` are derived from `min` in `options`:
|
227 |
|
228 | - `spacingInner` and `spacingOuter` are **newline** if `min` is `false`
|
229 | - `spacingInner` is **space** and `spacingOuter` is **empty string** if `min` is `true`
|
230 |
|
231 | ### Example of serialize and test
|
232 |
|
233 | This plugin is a pattern you can apply to serialize composite data types. Side note: `pretty-format` does not need a plugin to serialize arrays.
|
234 |
|
235 | ```js
|
236 | // We reused more code when we factored out a function for child items
|
237 | // that is independent of depth, name, and enclosing punctuation (see below).
|
238 | const SEPARATOR = ',';
|
239 | function serializeItems(items, config, indentation, depth, refs, printer) {
|
240 | if (items.length === 0) {
|
241 | return '';
|
242 | }
|
243 | const indentationItems = indentation + config.indent;
|
244 | return (
|
245 | config.spacingOuter +
|
246 | items
|
247 | .map(
|
248 | item =>
|
249 | indentationItems +
|
250 | printer(item, config, indentationItems, depth, refs), // callback
|
251 | )
|
252 | .join(SEPARATOR + config.spacingInner) +
|
253 | (config.min ? '' : SEPARATOR) + // following the last item
|
254 | config.spacingOuter +
|
255 | indentation
|
256 | );
|
257 | }
|
258 |
|
259 | const plugin = {
|
260 | test(val) {
|
261 | return Array.isArray(val);
|
262 | },
|
263 | serialize(array, config, indentation, depth, refs, printer) {
|
264 | const name = array.constructor.name;
|
265 | return ++depth > config.maxDepth
|
266 | ? '[' + name + ']'
|
267 | : (config.min ? '' : name + ' ') +
|
268 | '[' +
|
269 | serializeItems(array, config, indentation, depth, refs, printer) +
|
270 | ']';
|
271 | },
|
272 | };
|
273 | ```
|
274 |
|
275 | ```js
|
276 | const val = {
|
277 | filter: 'completed',
|
278 | items: [
|
279 | {
|
280 | text: 'Write test',
|
281 | completed: true,
|
282 | },
|
283 | {
|
284 | text: 'Write serialize',
|
285 | completed: true,
|
286 | },
|
287 | ],
|
288 | };
|
289 | ```
|
290 |
|
291 | ```js
|
292 | console.log(
|
293 | prettyFormat(val, {
|
294 | plugins: [plugin],
|
295 | }),
|
296 | );
|
297 | /*
|
298 | Object {
|
299 | "filter": "completed",
|
300 | "items": Array [
|
301 | Object {
|
302 | "completed": true,
|
303 | "text": "Write test",
|
304 | },
|
305 | Object {
|
306 | "completed": true,
|
307 | "text": "Write serialize",
|
308 | },
|
309 | ],
|
310 | }
|
311 | */
|
312 | ```
|
313 |
|
314 | ```js
|
315 | console.log(
|
316 | prettyFormat(val, {
|
317 | indent: 4,
|
318 | plugins: [plugin],
|
319 | }),
|
320 | );
|
321 | /*
|
322 | Object {
|
323 | "filter": "completed",
|
324 | "items": Array [
|
325 | Object {
|
326 | "completed": true,
|
327 | "text": "Write test",
|
328 | },
|
329 | Object {
|
330 | "completed": true,
|
331 | "text": "Write serialize",
|
332 | },
|
333 | ],
|
334 | }
|
335 | */
|
336 | ```
|
337 |
|
338 | ```js
|
339 | console.log(
|
340 | prettyFormat(val, {
|
341 | maxDepth: 1,
|
342 | plugins: [plugin],
|
343 | }),
|
344 | );
|
345 | /*
|
346 | Object {
|
347 | "filter": "completed",
|
348 | "items": [Array],
|
349 | }
|
350 | */
|
351 | ```
|
352 |
|
353 | ```js
|
354 | console.log(
|
355 | prettyFormat(val, {
|
356 | min: true,
|
357 | plugins: [plugin],
|
358 | }),
|
359 | );
|
360 | /*
|
361 | {"filter": "completed", "items": [{"completed": true, "text": "Write test"}, {"completed": true, "text": "Write serialize"}]}
|
362 | */
|
363 | ```
|
364 |
|
365 | ### print
|
366 |
|
367 | The **original** interface is adequate for plugins:
|
368 |
|
369 | - that **do not** depend on options other than `highlight` or `min`
|
370 | - that **do not** depend on `depth` or `refs` in recursive traversal, and
|
371 | - if values either
|
372 | - do **not** require indentation, or
|
373 | - do **not** occur as children of JavaScript data structures (for example, array)
|
374 |
|
375 | Write `print` to return a string, given the arguments:
|
376 |
|
377 | - `val` which “passed the test”
|
378 | - current `printer(valChild)` callback function: serialize children
|
379 | - current `indenter(lines)` callback function: indent lines at the next level
|
380 | - unchanging `config` object: derived from `options`
|
381 | - unchanging `colors` object: derived from `options`
|
382 |
|
383 | The 3 properties of `config` are `min` in `options` and:
|
384 |
|
385 | - `spacing` and `edgeSpacing` are **newline** if `min` is `false`
|
386 | - `spacing` is **space** and `edgeSpacing` is **empty string** if `min` is `true`
|
387 |
|
388 | Each property of `colors` corresponds to a property of `theme` in `options`:
|
389 |
|
390 | - the key is the same (for example, `tag`)
|
391 | - 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'`)
|
392 |
|
393 | ### Example of print and test
|
394 |
|
395 | This plugin prints functions with the **number of named arguments** excluding rest argument.
|
396 |
|
397 | ```js
|
398 | const plugin = {
|
399 | print(val) {
|
400 | return `[Function ${val.name || 'anonymous'} ${val.length}]`;
|
401 | },
|
402 | test(val) {
|
403 | return typeof val === 'function';
|
404 | },
|
405 | };
|
406 | ```
|
407 |
|
408 | ```js
|
409 | const val = {
|
410 | onClick(event) {},
|
411 | render() {},
|
412 | };
|
413 |
|
414 | prettyFormat(val, {
|
415 | plugins: [plugin],
|
416 | });
|
417 | /*
|
418 | Object {
|
419 | "onClick": [Function onClick 1],
|
420 | "render": [Function render 0],
|
421 | }
|
422 | */
|
423 |
|
424 | prettyFormat(val);
|
425 | /*
|
426 | Object {
|
427 | "onClick": [Function onClick],
|
428 | "render": [Function render],
|
429 | }
|
430 | */
|
431 | ```
|
432 |
|
433 | This plugin **ignores** the `printFunctionName` option. That limitation of the original `print` interface is a reason to use the improved `serialize` interface, described above.
|
434 |
|
435 | ```js
|
436 | prettyFormat(val, {
|
437 | plugins: [pluginOld],
|
438 | printFunctionName: false,
|
439 | });
|
440 | /*
|
441 | Object {
|
442 | "onClick": [Function onClick 1],
|
443 | "render": [Function render 0],
|
444 | }
|
445 | */
|
446 |
|
447 | prettyFormat(val, {
|
448 | printFunctionName: false,
|
449 | });
|
450 | /*
|
451 | Object {
|
452 | "onClick": [Function],
|
453 | "render": [Function],
|
454 | }
|
455 | */
|
456 | ```
|