README.md 12.4 KB
Newer Older
Spark's avatar
Spark committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
# pretty-format

Stringify any JavaScript value.

- Serialize built-in JavaScript types.
- Serialize application-specific data types with built-in or user-defined plugins.

## Installation

```sh
$ yarn add pretty-format
```

## Usage

```js
const prettyFormat = require('pretty-format'); // CommonJS
```

```js
import prettyFormat from 'pretty-format'; // ES2015 modules
```

```js
const val = {object: {}};
val.circularReference = val;
val[Symbol('foo')] = 'foo';
val.map = new Map([['prop', 'value']]);
val.array = [-0, Infinity, NaN];

console.log(prettyFormat(val));
/*
Object {
  "array": Array [
    -0,
    Infinity,
    NaN,
  ],
  "circularReference": [Circular],
  "map": Map {
    "prop" => "value",
  },
  "object": Object {},
  Symbol(foo): "foo",
}
*/
```

## Usage with options

```js
function onClick() {}

console.log(prettyFormat(onClick));
/*
[Function onClick]
*/

const options = {
  printFunctionName: false,
};
console.log(prettyFormat(onClick, options));
/*
[Function]
*/
```

<!-- prettier-ignore -->
| key                 | type      | default    | description                                             |
| :------------------ | :-------- | :--------- | :------------------------------------------------------ |
| `callToJSON`        | `boolean` | `true`     | call `toJSON` method (if it exists) on objects          |
| `escapeRegex`       | `boolean` | `false`    | escape special characters in regular expressions        |
| `escapeString`      | `boolean` | `true`     | escape special characters in strings                    |
| `highlight`         | `boolean` | `false`    | highlight syntax with colors in terminal (some plugins) |
| `indent`            | `number`  | `2`        | spaces in each level of indentation                     |
| `maxDepth`          | `number`  | `Infinity` | levels to print in arrays, objects, elements, and so on |
| `min`               | `boolean` | `false`    | minimize added space: no indentation nor line breaks    |
| `plugins`           | `array`   | `[]`       | plugins to serialize application-specific data types    |
| `printFunctionName` | `boolean` | `true`     | include or omit the name of a function                  |
| `theme`             | `object`  |            | colors to highlight syntax in terminal                  |

Property values of `theme` are from [ansi-styles colors](https://github.com/chalk/ansi-styles#colors)

```js
const DEFAULT_THEME = {
  comment: 'gray',
  content: 'reset',
  prop: 'yellow',
  tag: 'cyan',
  value: 'green',
};
```

## Usage with plugins

The `pretty-format` package provides some built-in plugins, including:

- `ReactElement` for elements from `react`
- `ReactTestComponent` for test objects from `react-test-renderer`

```js
// CommonJS
const React = require('react');
const renderer = require('react-test-renderer');
const prettyFormat = require('pretty-format');
const ReactElement = prettyFormat.plugins.ReactElement;
const ReactTestComponent = prettyFormat.plugins.ReactTestComponent;
```

```js
import React from 'react';
import renderer from 'react-test-renderer';
// ES2015 modules and destructuring assignment
import prettyFormat from 'pretty-format';
const {ReactElement, ReactTestComponent} = prettyFormat.plugins;
```

```js
const onClick = () => {};
const element = React.createElement('button', {onClick}, 'Hello World');

const formatted1 = prettyFormat(element, {
  plugins: [ReactElement],
  printFunctionName: false,
});
const formatted2 = prettyFormat(renderer.create(element).toJSON(), {
  plugins: [ReactTestComponent],
  printFunctionName: false,
});
/*
<button
  onClick=[Function]
>
  Hello World
</button>
*/
```

## Usage in Jest

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**.

To serialize application-specific data types, you can add modules to `devDependencies` of a project, and then:

In an **individual** test file, you can add a module as follows. It precedes any modules from Jest configuration.

```js
import serializer from 'my-serializer-module';
expect.addSnapshotSerializer(serializer);

// tests which have `expect(value).toMatchSnapshot()` assertions
```

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:

```json
{
  "jest": {
    "snapshotSerializers": ["my-serializer-module"]
  }
}
```

## Writing plugins

A plugin is a JavaScript object.

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:

- `serialize(val, …)` method of the **improved** interface (available in **version 21** or later)
- `print(val, …)` method of the **original** interface (if plugin does not have `serialize` method)

### test

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:

- `TypeError: Cannot read property 'whatever' of null`
- `TypeError: Cannot read property 'whatever' of undefined`

For example, `test` method of built-in `ReactElement` plugin:

```js
const elementSymbol = Symbol.for('react.element');
const test = val => val && val.$$typeof === elementSymbol;
```

Pay attention to efficiency in `test` because `pretty-format` calls it often.

### serialize

The **improved** interface is available in **version 21** or later.

Write `serialize` to return a string, given the arguments:

- `val` which “passed the test”
- unchanging `config` object: derived from `options`
- current `indentation` string: concatenate to `indent` from `config`
- current `depth` number: compare to `maxDepth` from `config`
- current `refs` array: find circular references in objects
- `printer` callback function: serialize children

### config

<!-- prettier-ignore -->
| key                 | type      | description                                             |
| :------------------ | :-------- | :------------------------------------------------------ |
| `callToJSON`        | `boolean` | call `toJSON` method (if it exists) on objects          |
| `colors`            | `Object`  | escape codes for colors to highlight syntax             |
| `escapeRegex`       | `boolean` | escape special characters in regular expressions        |
| `escapeString`      | `boolean` | escape special characters in strings                    |
| `indent`            | `string`  | spaces in each level of indentation                     |
| `maxDepth`          | `number`  | levels to print in arrays, objects, elements, and so on |
| `min`               | `boolean` | minimize added space: no indentation nor line breaks    |
| `plugins`           | `array`   | plugins to serialize application-specific data types    |
| `printFunctionName` | `boolean` | include or omit the name of a function                  |
| `spacingInner`      | `strong`  | spacing to separate items in a list                     |
| `spacingOuter`      | `strong`  | spacing to enclose a list of items                      |

Each property of `colors` in `config` corresponds to a property of `theme` in `options`:

- the key is the same (for example, `tag`)
- 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'`)

Some properties in `config` are derived from `min` in `options`:

- `spacingInner` and `spacingOuter` are **newline** if `min` is `false`
- `spacingInner` is **space** and `spacingOuter` is **empty string** if `min` is `true`

### Example of serialize and test

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.

```js
// We reused more code when we factored out a function for child items
// that is independent of depth, name, and enclosing punctuation (see below).
const SEPARATOR = ',';
function serializeItems(items, config, indentation, depth, refs, printer) {
  if (items.length === 0) {
    return '';
  }
  const indentationItems = indentation + config.indent;
  return (
    config.spacingOuter +
    items
      .map(
        item =>
          indentationItems +
          printer(item, config, indentationItems, depth, refs), // callback
      )
      .join(SEPARATOR + config.spacingInner) +
    (config.min ? '' : SEPARATOR) + // following the last item
    config.spacingOuter +
    indentation
  );
}

const plugin = {
  test(val) {
    return Array.isArray(val);
  },
  serialize(array, config, indentation, depth, refs, printer) {
    const name = array.constructor.name;
    return ++depth > config.maxDepth
      ? '[' + name + ']'
      : (config.min ? '' : name + ' ') +
          '[' +
          serializeItems(array, config, indentation, depth, refs, printer) +
          ']';
  },
};
```

```js
const val = {
  filter: 'completed',
  items: [
    {
      text: 'Write test',
      completed: true,
    },
    {
      text: 'Write serialize',
      completed: true,
    },
  ],
};
```

```js
console.log(
  prettyFormat(val, {
    plugins: [plugin],
  }),
);
/*
Object {
  "filter": "completed",
  "items": Array [
    Object {
      "completed": true,
      "text": "Write test",
    },
    Object {
      "completed": true,
      "text": "Write serialize",
    },
  ],
}
*/
```

```js
console.log(
  prettyFormat(val, {
    indent: 4,
    plugins: [plugin],
  }),
);
/*
Object {
    "filter": "completed",
    "items": Array [
        Object {
            "completed": true,
            "text": "Write test",
        },
        Object {
            "completed": true,
            "text": "Write serialize",
        },
    ],
}
*/
```

```js
console.log(
  prettyFormat(val, {
    maxDepth: 1,
    plugins: [plugin],
  }),
);
/*
Object {
  "filter": "completed",
  "items": [Array],
}
*/
```

```js
console.log(
  prettyFormat(val, {
    min: true,
    plugins: [plugin],
  }),
);
/*
{"filter": "completed", "items": [{"completed": true, "text": "Write test"}, {"completed": true, "text": "Write serialize"}]}
*/
```

### print

The **original** interface is adequate for plugins:

- that **do not** depend on options other than `highlight` or `min`
- that **do not** depend on `depth` or `refs` in recursive traversal, and
- if values either
  - do **not** require indentation, or
  - do **not** occur as children of JavaScript data structures (for example, array)

Write `print` to return a string, given the arguments:

- `val` which “passed the test”
- current `printer(valChild)` callback function: serialize children
- current `indenter(lines)` callback function: indent lines at the next level
- unchanging `config` object: derived from `options`
- unchanging `colors` object: derived from `options`

The 3 properties of `config` are `min` in `options` and:

- `spacing` and `edgeSpacing` are **newline** if `min` is `false`
- `spacing` is **space** and `edgeSpacing` is **empty string** if `min` is `true`

Each property of `colors` corresponds to a property of `theme` in `options`:

- the key is the same (for example, `tag`)
- 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'`)

### Example of print and test

This plugin prints functions with the **number of named arguments** excluding rest argument.

```js
const plugin = {
  print(val) {
    return `[Function ${val.name || 'anonymous'} ${val.length}]`;
  },
  test(val) {
    return typeof val === 'function';
  },
};
```

```js
const val = {
  onClick(event) {},
  render() {},
};

prettyFormat(val, {
  plugins: [plugin],
});
/*
Object {
  "onClick": [Function onClick 1],
  "render": [Function render 0],
}
*/

prettyFormat(val);
/*
Object {
  "onClick": [Function onClick],
  "render": [Function render],
}
*/
```

This plugin **ignores** the `printFunctionName` option. That limitation of the original `print` interface is a reason to use the improved `serialize` interface, described above.

```js
prettyFormat(val, {
  plugins: [pluginOld],
  printFunctionName: false,
});
/*
Object {
  "onClick": [Function onClick 1],
  "render": [Function render 0],
}
*/

prettyFormat(val, {
  printFunctionName: false,
});
/*
Object {
  "onClick": [Function],
  "render": [Function],
}
*/
```