29.7.0 • Published 2 months ago

pretty-format v29.7.0

Weekly downloads
21,587,985
License
MIT
Repository
github
Last release
2 months ago

pretty-format

Stringify any JavaScript value.

  • Supports all built-in JavaScript types
    • primitive types: Boolean, null, Number, String, Symbol, undefined
    • other non-collection types: Date, Error, Function, RegExp
    • collection types:
      • arguments, Array, ArrayBuffer, DataView, Float32Array, Float64Array, Int8Array, Int16Array, Int32Array, Uint8Array, Uint8ClampedArray, Uint16Array, Uint32Array,
      • Map, Set, WeakMap, WeakSet
      • Object
  • Blazingly fast
    • similar performance to JSON.stringify in v8
    • significantly faster than util.format in Node.js
  • Serialize application-specific data types with built-in or user-defined plugins

Installation

$ yarn add pretty-format

Usage

const prettyFormat = require('pretty-format'); // CommonJS
import prettyFormat from 'pretty-format'; // ES2015 modules
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

function onClick() {}

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

const options = {
  printFunctionName: false,
};
console.log(prettyFormat(onClick, options));
/*
[Function]
*/
keytypedefaultdescription
callToJSONbooleantruecall toJSON method (if it exists) on objects
escapeRegexbooleanfalseescape special characters in regular expressions
highlightbooleanfalsehighlight syntax with colors in terminal (some plugins)
indentnumber2spaces in each level of indentation
maxDepthnumberInfinitylevels to print in arrays, objects, elements, and so on
minbooleanfalseminimize added space: no indentation nor line breaks
pluginsarray[]plugins to serialize application-specific data types
printFunctionNamebooleantrueinclude or omit the name of a function
themeobjectcolors to highlight syntax in terminal

Property values of theme are from ansi-styles colors

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
// CommonJS
const prettyFormat = require('pretty-format');
const ReactElement = prettyFormat.plugins.ReactElement;
const ReactTestComponent = prettyFormat.plugins.ReactTestComponent;

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

import React from 'react';
import renderer from 'react-test-renderer';
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.

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:

{
  "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:

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

keytypedescription
callToJSONbooleancall toJSON method (if it exists) on objects
colorsObjectescape codes for colors to highlight syntax
escapeRegexbooleanescape special characters in regular expressions
indentstringspaces in each level of indentation
maxDepthnumberlevels to print in arrays, objects, elements, and so on
minbooleanminimize added space: no indentation nor line breaks
pluginsarrayplugins to serialize application-specific data types
printFunctionNamebooleaninclude or omit the name of a function
spacingInnerstrongspacing to separate items in a list
spacingOuterstrongspacing 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 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. Of course, pretty-format does not need a plugin to serialize arrays :)

// 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) +
          ']';
  },
};
const val = {
  filter: 'completed',
  items: [
    {
      text: 'Write test',
      completed: true,
    },
    {
      text: 'Write serialize',
      completed: true,
    },
  ],
};
console.log(
  prettyFormat(val, {
    plugins: [plugin],
  }),
);
/*
Object {
  "filter": "completed",
  "items": Array [
    Object {
      "completed": true,
      "text": "Write test",
    },
    Object {
      "completed": true,
      "text": "Write serialize",
    },
  ],
}
*/
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",
        },
    ],
}
*/
console.log(
  prettyFormat(val, {
    maxDepth: 1,
    plugins: [plugin],
  }),
);
/*
Object {
  "filter": "completed",
  "items": [Array],
}
*/
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 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.

const plugin = {
  print(val) {
    return `[Function ${val.name || 'anonymous'} ${val.length}]`;
  },
  test(val) {
    return typeof val === 'function';
  },
};
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.

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

prettyFormat(val, {
  printFunctionName: false,
});
/*
Object {
  "onClick": [Function],
  "render": [Function],
}
*/
jest-diffjest-message-utiljest-matcher-utilsjest-validatejest-jasmine2jest-configjest-snapshotjest-leak-detectorjest-each@jest/core@types/jest@testing-library/domjest-circus@wouterds/react-native-tvos42-expo@storybook/addon-storyshotsarchetype-librarycoursefinderpwc-expoeasy-select-rnonepiecefgonpieca-test-gatewaysola-react-nativereact-native-bluetooth2killi8n-react-native-fast-imagesod-gatewayreact-native-for-sanbotrn-send-sms@rock-kit/ui-test-queriesspecify-importsbabel-specify-imports@icanpm/api-master@oneplanetcrowd/developerstesting-playgroundreact-native-wk-viewstandard-report-templatereact-native-template-rfbaseairscanairscan-example@yokita/stp-commonreact-native-esc-pos-sahaab@borisovart/atol-kkt-moduledeneme323112react-native-webpack-toolkit@ntt_app/react-native-custom-notificationreact-native-custom-text-hwjames@toptal/apollo-gatewayreact-native-savvreact-native-covid-sdkgql_din_modjest-circus-allure-environment-custom-handlerbitgetreact-native-thanh-toast-library@thanhnguyen14797/react-native-thanh-toast-librarytrustwise-react-native@daimond113/prettier-eslintvite-plugin-custom-index@olivervorasai/sliderreact-native-printer-brothersrn-pdf-reader-offlinereact-native-shekhar-bridge-test@service-exchange/devtoolsreact-native-wegowilscanner@khalitovadel/abstract-repository@oiti/documentoscopy-react-native@mink-opn/build-tokensquoc-testrn-0.45-fork-oreoreact-native-slider-kf@saaspe/componentsplginveggies-tsexpand-react-bridgeopea-bootstraapluminos-ui-corereact-native-macosreact-nativereact-native-windowssklif-ui-kitsklif-api@everything-registry/sub-chunk-2471jawwy-sdkjawwy_gamification_release@314oner_npm/universal-components-libraryreact-native-sphereuisphereuijawwy_libraryreact-native-credit-card-pkgp149-tablesklif-uireact-native-jawwy_samplereact-native-chenaardskcorenewdts-jestes-react-bridgeepm-npm-tscenzyme-async-helpersenzyme-async-helpers-react15react-native-responsive-size
30.0.0-alpha.3

2 months ago

30.0.0-alpha.2

5 months ago

30.0.0-alpha.1

6 months ago

29.7.0

7 months ago

29.6.3

8 months ago

29.6.0

10 months ago

29.6.1

10 months ago

29.6.2

9 months ago

29.4.1

1 year ago

29.4.2

1 year ago

29.4.3

1 year ago

29.4.0

1 year ago

29.5.0

1 year ago

29.2.0

2 years ago

29.2.1

2 years ago

29.3.1

1 year ago

29.0.1

2 years ago

29.0.2

2 years ago

29.0.3

2 years ago

29.0.0

2 years ago

29.1.0

2 years ago

29.1.2

2 years ago

28.1.3

2 years ago

28.1.1

2 years ago

29.0.0-alpha.6

2 years ago

29.0.0-alpha.4

2 years ago

29.0.0-alpha.3

2 years ago

29.0.0-alpha.0

2 years ago

29.0.0-alpha.1

2 years ago

28.1.0

2 years ago

28.0.0

2 years ago

28.0.1

2 years ago

28.0.2

2 years ago

28.0.0-alpha.8

2 years ago

28.0.0-alpha.7

2 years ago

28.0.0-alpha.9

2 years ago

28.0.0-alpha.6

2 years ago

27.5.0

2 years ago

27.5.1

2 years ago

27.4.6

2 years ago

27.4.1

2 years ago

27.4.2

2 years ago

28.0.0-alpha.4

2 years ago

28.0.0-alpha.3

2 years ago

28.0.0-alpha.5

2 years ago

28.0.0-alpha.0

2 years ago

28.0.0-alpha.2

2 years ago

28.0.0-alpha.1

2 years ago

27.4.0

2 years ago

27.3.0

3 years ago

27.3.1

3 years ago

27.2.5

3 years ago

27.2.4

3 years ago

27.2.3

3 years ago

27.2.2

3 years ago

27.2.0

3 years ago

27.1.1

3 years ago

27.1.0

3 years ago

27.0.6

3 years ago

27.0.2

3 years ago

27.0.1

3 years ago

27.0.0

3 years ago

27.0.0-next.9

3 years ago

27.0.0-next.11

3 years ago

27.0.0-next.10

3 years ago

27.0.0-next.8

3 years ago

27.0.0-next.7

3 years ago

27.0.0-next.6

3 years ago

27.0.0-next.5

3 years ago

27.0.0-next.3

3 years ago

27.0.0-next.1

3 years ago

27.0.0-next.0

3 years ago

26.6.2

3 years ago

26.6.1

3 years ago

26.6.0

4 years ago

26.5.2

4 years ago

26.5.0

4 years ago

26.4.2

4 years ago

26.4.0

4 years ago

26.3.0

4 years ago

26.2.0

4 years ago

26.1.0

4 years ago

26.0.1

4 years ago

26.0.1-alpha.0

4 years ago

26.0.0

4 years ago

26.0.0-alpha.2

4 years ago

26.0.0-alpha.1

4 years ago

26.0.0-alpha.0

4 years ago

25.5.0

4 years ago

25.4.0

4 years ago

25.3.0

4 years ago

25.2.6

4 years ago

25.2.5

4 years ago

25.2.1-alpha.1

4 years ago

25.2.1-alpha.2

4 years ago

25.2.3

4 years ago

25.2.1

4 years ago

25.2.0-alpha.86

4 years ago

25.2.0

4 years ago

25.1.0

4 years ago

25.0.0

5 years ago

24.9.0

5 years ago

24.8.0

5 years ago

24.7.0

5 years ago

24.6.0

5 years ago

24.5.0

5 years ago

24.4.0

5 years ago

24.3.1

5 years ago

24.3.0

5 years ago

24.2.0-alpha.0

5 years ago

24.0.0

5 years ago

24.0.0-alpha.16

5 years ago

24.0.0-alpha.15

5 years ago

24.0.0-alpha.13

5 years ago

24.0.0-alpha.12

5 years ago

24.0.0-alpha.11

5 years ago

24.0.0-alpha.10

5 years ago

24.0.0-alpha.9

5 years ago

24.0.0-alpha.8

5 years ago

24.0.0-alpha.7

5 years ago

24.0.0-alpha.6

5 years ago

24.0.0-alpha.5

5 years ago

24.0.0-alpha.4

5 years ago

24.0.0-alpha.2

5 years ago

24.0.0-alpha.1

5 years ago

24.0.0-alpha.0

6 years ago

23.6.0

6 years ago

23.5.0

6 years ago

23.2.0

6 years ago

23.0.1

6 years ago

23.0.0

6 years ago

23.0.0-charlie.4

6 years ago

23.0.0-charlie.3

6 years ago

23.0.0-charlie.2

6 years ago

23.0.0-charlie.1

6 years ago

23.0.0-charlie.0

6 years ago

23.0.0-beta.3r

6 years ago

23.0.0-alpha.3r

6 years ago

23.0.0-beta.2

6 years ago

23.0.0-beta.1

6 years ago

23.0.0-beta.0

6 years ago

23.0.0-alpha.7

6 years ago

23.0.0-alpha.6r

6 years ago

23.0.0-alpha.5r

6 years ago

23.0.0-alpha.5

6 years ago

23.0.0-alpha.4

6 years ago

23.0.0-alpha.2

6 years ago

22.4.3

6 years ago

22.4.0

6 years ago

22.1.0

6 years ago

22.0.6

6 years ago

22.0.5

6 years ago

22.0.3

6 years ago

22.0.2

6 years ago

22.0.1

6 years ago

22.0.0

6 years ago

21.3.0-beta.15

6 years ago

21.3.0-beta.14

6 years ago

21.3.0-beta.13

6 years ago

21.3.0-beta.12

6 years ago

21.3.0-beta.11

6 years ago

21.3.0-beta.10

6 years ago

21.3.0-beta.9

6 years ago

21.3.0-beta.8

6 years ago

21.3.0-beta.7

6 years ago

21.3.0-beta.6

6 years ago

21.3.0-beta.5

6 years ago

21.3.0-beta.4

6 years ago

21.3.0-beta.3

6 years ago

21.3.0-beta.2

7 years ago

21.3.0-beta.1

7 years ago

21.2.1

7 years ago

21.2.0

7 years ago

21.1.0

7 years ago

21.0.2

7 years ago

21.0.0

7 years ago

21.0.0-beta.1

7 years ago

21.0.0-alpha.2

7 years ago

21.0.0-alpha.1

7 years ago

20.1.0-echo.1

7 years ago

20.1.0-delta.5

7 years ago

20.1.0-delta.4

7 years ago

20.1.0-delta.3

7 years ago

20.1.0-delta.2

7 years ago

20.1.0-delta.1

7 years ago

20.1.0-chi.1

7 years ago

20.1.0-beta.1

7 years ago

20.1.0-alpha.3

7 years ago

20.1.0-alpha.2

7 years ago

20.1.0-alpha.1

7 years ago

20.0.3

7 years ago

20.0.2

7 years ago

20.0.1

7 years ago

20.0.0

7 years ago

19.0.0

7 years ago

18.1.0

7 years ago

18.0.0

7 years ago

4.3.1

7 years ago

4.3.0

7 years ago

4.2.3

7 years ago

4.2.2

7 years ago

4.2.1

8 years ago

4.2.0

8 years ago

4.1.0

8 years ago

4.0.0

8 years ago

3.8.0

8 years ago

3.7.0

8 years ago

3.6.0

8 years ago

3.5.3

8 years ago

3.5.2

8 years ago

3.5.1

8 years ago

3.5.0

8 years ago

3.4.3

8 years ago

3.4.2

8 years ago

3.4.1

8 years ago

3.4.0

8 years ago

3.3.2

8 years ago

3.3.1

8 years ago

3.3.0

8 years ago

3.2.0

8 years ago

3.1.0

8 years ago

3.0.0

8 years ago

2.1.0

8 years ago

2.0.0

8 years ago

1.2.0

9 years ago

1.1.1

9 years ago

1.1.0

9 years ago

1.0.0

9 years ago