{"id":21466550,"url":"https://github.com/permafrost-dev/pretty-format-react","last_synced_at":"2026-03-11T18:03:18.404Z","repository":{"id":144711811,"uuid":"612500158","full_name":"permafrost-dev/pretty-format-react","owner":"permafrost-dev","description":"Stringify any JavaScript value. From the jest/pretty-format package.","archived":false,"fork":false,"pushed_at":"2025-06-14T08:30:03.000Z","size":48,"stargazers_count":0,"open_issues_count":2,"forks_count":0,"subscribers_count":2,"default_branch":"main","last_synced_at":"2025-06-14T09:30:13.203Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/permafrost-dev.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2023-03-11T05:55:36.000Z","updated_at":"2023-03-11T07:19:14.000Z","dependencies_parsed_at":"2025-05-28T06:42:49.419Z","dependency_job_id":null,"html_url":"https://github.com/permafrost-dev/pretty-format-react","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/permafrost-dev/pretty-format-react","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/permafrost-dev%2Fpretty-format-react","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/permafrost-dev%2Fpretty-format-react/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/permafrost-dev%2Fpretty-format-react/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/permafrost-dev%2Fpretty-format-react/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/permafrost-dev","download_url":"https://codeload.github.com/permafrost-dev/pretty-format-react/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/permafrost-dev%2Fpretty-format-react/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":259796313,"owners_count":22912689,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-11-23T08:14:29.657Z","updated_at":"2026-03-11T18:03:18.399Z","avatar_url":"https://github.com/permafrost-dev.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# pretty-format-react\n\nTaken from `jest/pretty-format` v29.4.3 and modified to work with React 18.\n\n---\n\nStringify any JavaScript value.\n\n- Serialize built-in JavaScript types.\n- Serialize application-specific data types with built-in or user-defined plugins.\n\n## Installation\n\n```sh\n$ yarn add pretty-format\n```\n\n## Usage\n\n```js\nconst {format: prettyFormat} = require('pretty-format'); // CommonJS\n```\n\n```js\nimport {format as prettyFormat} from 'pretty-format'; // ES2015 modules\n```\n\n```js\nconst val = {object: {}};\nval.circularReference = val;\nval[Symbol('foo')] = 'foo';\nval.map = new Map([['prop', 'value']]);\nval.array = [-0, Infinity, NaN];\n\nconsole.log(prettyFormat(val));\n/*\nObject {\n  \"array\": Array [\n    -0,\n    Infinity,\n    NaN,\n  ],\n  \"circularReference\": [Circular],\n  \"map\": Map {\n    \"prop\" =\u003e \"value\",\n  },\n  \"object\": Object {},\n  Symbol(foo): \"foo\",\n}\n*/\n```\n\n## Usage with options\n\n```js\nfunction onClick() {}\n\nconsole.log(prettyFormat(onClick));\n/*\n[Function onClick]\n*/\n\nconst options = {\n  printFunctionName: false,\n};\nconsole.log(prettyFormat(onClick, options));\n/*\n[Function]\n*/\n```\n\n\u003c!-- prettier-ignore --\u003e\n| key                   | type             | default     | description                                                                             |\n| :-------------------- | :--------------- | :---------- | :-------------------------------------------------------------------------------------- |\n| `callToJSON`          | `boolean`        | `true`      | call `toJSON` method (if it exists) on objects                                          |\n| `compareKeys`         | `function\\|null` | `undefined` | compare function used when sorting object keys, `null` can be used to skip over sorting |\n| `escapeRegex`         | `boolean`        | `false`     | escape special characters in regular expressions                                        |\n| `escapeString`        | `boolean`        | `true`      | escape special characters in strings                                                    |\n| `highlight`           | `boolean`        | `false`     | highlight syntax with colors in terminal (some plugins)                                 |\n| `indent`              | `number`         | `2`         | spaces in each level of indentation                                                     |\n| `maxDepth`            | `number`         | `Infinity`  | levels to print in arrays, objects, elements, and so on                                 |\n| `maxWidth`            | `number`         | `Infinity`  | number of elements to print in arrays, sets, and so on                                  |\n| `min`                 | `boolean`        | `false`     | minimize added space: no indentation nor line breaks                                    |\n| `plugins`             | `array`          | `[]`        | plugins to serialize application-specific data types                                    |\n| `printBasicPrototype` | `boolean`        | `false`     | print the prototype for plain objects and arrays                                        |\n| `printFunctionName`   | `boolean`        | `true`      | include or omit the name of a function                                                  |\n| `theme`               | `object`         |             | colors to highlight syntax in terminal                                                  |\n\nProperty values of `theme` are from [ansi-styles colors](https://github.com/chalk/ansi-styles#colors)\n\n```js\nconst DEFAULT_THEME = {\n  comment: 'gray',\n  content: 'reset',\n  prop: 'yellow',\n  tag: 'cyan',\n  value: 'green',\n};\n```\n\n## Usage with plugins\n\nThe `pretty-format` package provides some built-in plugins, including:\n\n- `ReactElement` for elements from `react`\n- `ReactTestComponent` for test objects from `react-test-renderer`\n\n```js\n// CommonJS\nconst React = require('react');\nconst renderer = require('react-test-renderer');\nconst {format: prettyFormat, plugins} = require('pretty-format');\n\nconst {ReactElement, ReactTestComponent} = plugins;\n```\n\n```js\n// ES2015 modules and destructuring assignment\nimport React from 'react';\nimport renderer from 'react-test-renderer';\nimport {plugins, format as prettyFormat} from 'pretty-format';\n\nconst {ReactElement, ReactTestComponent} = plugins;\n```\n\n```js\nconst onClick = () =\u003e {};\nconst element = React.createElement('button', {onClick}, 'Hello World');\n\nconst formatted1 = prettyFormat(element, {\n  plugins: [ReactElement],\n  printFunctionName: false,\n});\nconst formatted2 = prettyFormat(renderer.create(element).toJSON(), {\n  plugins: [ReactTestComponent],\n  printFunctionName: false,\n});\n/*\n\u003cbutton\n  onClick=[Function]\n\u003e\n  Hello World\n\u003c/button\u003e\n*/\n```\n\n## Usage in Jest\n\nFor 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**.\n\nTo serialize application-specific data types, you can add modules to `devDependencies` of a project, and then:\n\nIn an **individual** test file, you can add a module as follows. It precedes any modules from Jest configuration.\n\n```js\nimport serializer from 'my-serializer-module';\nexpect.addSnapshotSerializer(serializer);\n\n// tests which have `expect(value).toMatchSnapshot()` assertions\n```\n\nFor **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:\n\n```json\n{\n  \"jest\": {\n    \"snapshotSerializers\": [\"my-serializer-module\"]\n  }\n}\n```\n\n## Writing plugins\n\nA plugin is a JavaScript object.\n\nIf `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:\n\n- `serialize(val, …)` method of the **improved** interface (available in **version 21** or later)\n- `print(val, …)` method of the **original** interface (if plugin does not have `serialize` method)\n\n### test\n\nWrite `test` so it can receive `val` argument of any type. To serialize **objects** which have certain properties, then a guarded expression like `val != null \u0026\u0026 …` or more concise `val \u0026\u0026 …` prevents the following errors:\n\n- `TypeError: Cannot read property 'whatever' of null`\n- `TypeError: Cannot read property 'whatever' of undefined`\n\nFor example, `test` method of built-in `ReactElement` plugin:\n\n```js\nconst elementSymbol = Symbol.for('react.element');\nconst test = val =\u003e val \u0026\u0026 val.$$typeof === elementSymbol;\n```\n\nPay attention to efficiency in `test` because `pretty-format` calls it often.\n\n### serialize\n\nThe **improved** interface is available in **version 21** or later.\n\nWrite `serialize` to return a string, given the arguments:\n\n- `val` which “passed the test”\n- unchanging `config` object: derived from `options`\n- current `indentation` string: concatenate to `indent` from `config`\n- current `depth` number: compare to `maxDepth` from `config`\n- current `refs` array: find circular references in objects\n- `printer` callback function: serialize children\n\n### config\n\n\u003c!-- prettier-ignore --\u003e\n| key                 | type             | description                                                                             |\n| :------------------ | :--------------- | :-------------------------------------------------------------------------------------- |\n| `callToJSON`        | `boolean`        | call `toJSON` method (if it exists) on objects                                          |\n| `compareKeys`       | `function\\|null` | compare function used when sorting object keys, `null` can be used to skip over sorting |\n| `colors`            | `Object`         | escape codes for colors to highlight syntax                                             |\n| `escapeRegex`       | `boolean`        | escape special characters in regular expressions                                        |\n| `escapeString`      | `boolean`        | escape special characters in strings                                                    |\n| `indent`            | `string`         | spaces in each level of indentation                                                     |\n| `maxDepth`          | `number`         | levels to print in arrays, objects, elements, and so on                                 |\n| `min`               | `boolean`        | minimize added space: no indentation nor line breaks                                    |\n| `plugins`           | `array`          | plugins to serialize application-specific data types                                    |\n| `printFunctionName` | `boolean`        | include or omit the name of a function                                                  |\n| `spacingInner`      | `string`         | spacing to separate items in a list                                                     |\n| `spacingOuter`      | `string`         | spacing to enclose a list of items                                                      |\n\nEach property of `colors` in `config` corresponds to a property of `theme` in `options`:\n\n- the key is the same (for example, `tag`)\n- 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'`)\n\nSome properties in `config` are derived from `min` in `options`:\n\n- `spacingInner` and `spacingOuter` are **newline** if `min` is `false`\n- `spacingInner` is **space** and `spacingOuter` is **empty string** if `min` is `true`\n\n### Example of serialize and test\n\nThis plugin is a pattern you can apply to serialize composite data types. Side note: `pretty-format` does not need a plugin to serialize arrays.\n\n```js\n// We reused more code when we factored out a function for child items\n// that is independent of depth, name, and enclosing punctuation (see below).\nconst SEPARATOR = ',';\nfunction serializeItems(items, config, indentation, depth, refs, printer) {\n  if (items.length === 0) {\n    return '';\n  }\n  const indentationItems = indentation + config.indent;\n  return (\n    config.spacingOuter +\n    items\n      .map(\n        item =\u003e\n          indentationItems +\n          printer(item, config, indentationItems, depth, refs), // callback\n      )\n      .join(SEPARATOR + config.spacingInner) +\n    (config.min ? '' : SEPARATOR) + // following the last item\n    config.spacingOuter +\n    indentation\n  );\n}\n\nconst plugin = {\n  test(val) {\n    return Array.isArray(val);\n  },\n  serialize(array, config, indentation, depth, refs, printer) {\n    const name = array.constructor.name;\n    return ++depth \u003e config.maxDepth\n      ? `[${name}]`\n      : `${config.min ? '' : `${name} `}[${serializeItems(\n          array,\n          config,\n          indentation,\n          depth,\n          refs,\n          printer,\n        )}]`;\n  },\n};\n```\n\n```js\nconst val = {\n  filter: 'completed',\n  items: [\n    {\n      text: 'Write test',\n      completed: true,\n    },\n    {\n      text: 'Write serialize',\n      completed: true,\n    },\n  ],\n};\n```\n\n```js\nconsole.log(\n  prettyFormat(val, {\n    plugins: [plugin],\n  }),\n);\n/*\nObject {\n  \"filter\": \"completed\",\n  \"items\": Array [\n    Object {\n      \"completed\": true,\n      \"text\": \"Write test\",\n    },\n    Object {\n      \"completed\": true,\n      \"text\": \"Write serialize\",\n    },\n  ],\n}\n*/\n```\n\n```js\nconsole.log(\n  prettyFormat(val, {\n    indent: 4,\n    plugins: [plugin],\n  }),\n);\n/*\nObject {\n    \"filter\": \"completed\",\n    \"items\": Array [\n        Object {\n            \"completed\": true,\n            \"text\": \"Write test\",\n        },\n        Object {\n            \"completed\": true,\n            \"text\": \"Write serialize\",\n        },\n    ],\n}\n*/\n```\n\n```js\nconsole.log(\n  prettyFormat(val, {\n    maxDepth: 1,\n    plugins: [plugin],\n  }),\n);\n/*\nObject {\n  \"filter\": \"completed\",\n  \"items\": [Array],\n}\n*/\n```\n\n```js\nconsole.log(\n  prettyFormat(val, {\n    min: true,\n    plugins: [plugin],\n  }),\n);\n/*\n{\"filter\": \"completed\", \"items\": [{\"completed\": true, \"text\": \"Write test\"}, {\"completed\": true, \"text\": \"Write serialize\"}]}\n*/\n```\n\n### print\n\nThe **original** interface is adequate for plugins:\n\n- that **do not** depend on options other than `highlight` or `min`\n- that **do not** depend on `depth` or `refs` in recursive traversal, and\n- if values either\n  - do **not** require indentation, or\n  - do **not** occur as children of JavaScript data structures (for example, array)\n\nWrite `print` to return a string, given the arguments:\n\n- `val` which “passed the test”\n- current `printer(valChild)` callback function: serialize children\n- current `indenter(lines)` callback function: indent lines at the next level\n- unchanging `config` object: derived from `options`\n- unchanging `colors` object: derived from `options`\n\nThe 3 properties of `config` are `min` in `options` and:\n\n- `spacing` and `edgeSpacing` are **newline** if `min` is `false`\n- `spacing` is **space** and `edgeSpacing` is **empty string** if `min` is `true`\n\nEach property of `colors` corresponds to a property of `theme` in `options`:\n\n- the key is the same (for example, `tag`)\n- 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'`)\n\n### Example of print and test\n\nThis plugin prints functions with the **number of named arguments** excluding rest argument.\n\n```js\nconst plugin = {\n  print(val) {\n    return `[Function ${val.name || 'anonymous'} ${val.length}]`;\n  },\n  test(val) {\n    return typeof val === 'function';\n  },\n};\n```\n\n```js\nconst val = {\n  onClick(event) {},\n  render() {},\n};\n\nprettyFormat(val, {\n  plugins: [plugin],\n});\n/*\nObject {\n  \"onClick\": [Function onClick 1],\n  \"render\": [Function render 0],\n}\n*/\n\nprettyFormat(val);\n/*\nObject {\n  \"onClick\": [Function onClick],\n  \"render\": [Function render],\n}\n*/\n```\n\nThis plugin **ignores** the `printFunctionName` option. That limitation of the original `print` interface is a reason to use the improved `serialize` interface, described above.\n\n```js\nprettyFormat(val, {\n  plugins: [pluginOld],\n  printFunctionName: false,\n});\n/*\nObject {\n  \"onClick\": [Function onClick 1],\n  \"render\": [Function render 0],\n}\n*/\n\nprettyFormat(val, {\n  printFunctionName: false,\n});\n/*\nObject {\n  \"onClick\": [Function],\n  \"render\": [Function],\n}\n*/\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpermafrost-dev%2Fpretty-format-react","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fpermafrost-dev%2Fpretty-format-react","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpermafrost-dev%2Fpretty-format-react/lists"}