You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

README.md 13 KiB

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