Security News
ESLint is Now Language-Agnostic: Linting JSON, Markdown, and Beyond
ESLint has added JSON and Markdown linting support with new officially-supported plugins, expanding its versatility beyond JavaScript.
pretty-format
Advanced tools
The pretty-format npm package is a JavaScript library that allows you to serialize any JavaScript value into a string with a human-readable format. It is particularly useful for snapshot testing, where you want to compare the expected and actual output of your test cases.
Pretty-printing of basic JavaScript types
This feature allows you to convert basic JavaScript types like objects, arrays, strings, numbers, etc., into a nicely formatted string.
const prettyFormat = require('pretty-format');
const value = { foo: 'bar', baz: 42 };
console.log(prettyFormat(value));
Customizing output with plugins
pretty-format supports plugins that can be used to customize the output for specific types of values, such as React elements.
const prettyFormat = require('pretty-format');
const ReactElementPlugin = require('pretty-format/plugins/ReactElement');
const reactElement = <div>Hello World</div>;
console.log(prettyFormat(reactElement, { plugins: [ReactElementPlugin] }));
Minimizing diff output
By using pretty-format in combination with a diffing library like jest-diff, you can minimize the output of diffs to make them easier to read and understand.
const prettyFormat = require('pretty-format');
const diff = require('jest-diff');
const oldValue = { a: 'old', b: 'values' };
const newValue = { a: 'new', b: 'values' };
const difference = diff(prettyFormat(oldValue), prettyFormat(newValue));
console.log(difference);
Chalk is a popular npm package for styling terminal strings. While it doesn't serialize objects, it can be used in conjunction with pretty-format to colorize the output, enhancing readability.
Util is a core Node.js module that provides a method called 'inspect' for printing objects in a readable format. It is similar to pretty-format but is built into Node.js and does not support plugins.
js-beautify is an npm package that can format HTML, CSS, and JavaScript code. It is more focused on formatting code rather than serializing arbitrary JavaScript values like pretty-format.
Stringify any JavaScript value.
$ yarn add pretty-format
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",
}
*/
function onClick() {}
console.log(prettyFormat(onClick));
/*
[Function onClick]
*/
const options = {
printFunctionName: false,
};
console.log(prettyFormat(onClick, options));
/*
[Function]
*/
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
const DEFAULT_THEME = {
comment: 'gray',
content: 'reset',
prop: 'yellow',
tag: 'cyan',
value: 'green',
};
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>
*/
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"]
}
}
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)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.
The improved interface is available in version 21 or later.
Write serialize
to return a string, given the arguments:
val
which “passed the test”config
object: derived from options
indentation
string: concatenate to indent
from config
depth
number: compare to maxDepth
from config
refs
array: find circular references in objectsprinter
callback function: serialize childrenkey | 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
:
tag
)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
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.
// 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"}]}
*/
The original interface is adequate for plugins:
highlight
or min
depth
or refs
in recursive traversal, andWrite print
to return a string, given the arguments:
val
which “passed the test”printer(valChild)
callback function: serialize childrenindenter(lines)
callback function: indent lines at the next levelconfig
object: derived from options
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
:
tag
)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'
)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],
}
*/
25.1.0
[babel-plugin-jest-hoist]
Show codeframe on static hoisting issues (#8865)[babel-plugin-jest-hoist]
Add BigInt
to ALLOWED_IDENTIFIERS
(#8382)[babel-preset-jest]
Add @babel/plugin-syntax-bigint
(#8382)[expect]
Add BigInt
support to toBeGreaterThan
, toBeGreaterThanOrEqual
, toBeLessThan
and toBeLessThanOrEqual
(#8382)[expect, jest-matcher-utils]
Display change counts in annotation lines (#9035)[expect, jest-snapshot]
Support custom inline snapshot matchers (#9278)[jest-config]
Throw the full error message and stack when a Jest preset is missing a dependency (#8924)[jest-config]
[BREAKING] Set default display name color based on runner (#8689)[jest-config]
Merge preset globals with project globals (#9027)[jest-config]
Support .cjs
config files (#9291)[jest-config]
[BREAKING] Support .mjs
config files (#9431)[jest-core]
Support reporters as default exports (#9161)[jest-core]
Support --findRelatedTests
paths case insensitivity on Windows (#8961)[jest-diff]
Add options for colors and symbols (#8841)[jest-diff]
[BREAKING] Export as ECMAScript module (#8873)[jest-diff]
Add includeChangeCounts
and rename Indicator
options (#8881)[jest-diff]
Add changeColor
and patchColor
options (#8911)[jest-diff]
Add trailingSpaceFormatter
option and replace cyan with commonColor
(#8927)[jest-diff]
Add firstOrLastEmptyLineReplacement
option and export 3 diffLines
functions (#8955)[jest-environment]
Add optional getVmContext
next to runScript
(#9252 & #9428)[jest-environment-jsdom]
Add fakeTimersLolex
(#8925)[jest-environment-node]
Add fakeTimersLolex
(#8925)[jest-environment-node]
Add queueMicrotask
(#9140)[jest-environment-node]
Implement getVmContext
(#9252 & #9428)[@jest/fake-timers]
Add Lolex as implementation of fake timers (#8897)[jest-get-type]
Add BigInt
support. (#8382)[jest-matcher-utils]
Add BigInt
support to ensureNumbers
ensureActualIsNumber
, ensureExpectedIsNumber
(#8382)[jest-matcher-utils]
Ignore highlighting matched asymmetricMatcher in diffs (#9257)[jest-reporters]
Export utils for path formatting (#9162)[jest-reporters]
Provides global coverage thresholds as watermarks for istanbul (#9416)[jest-runner]
Warn if a worker had to be force exited (#8206)[jest-runtime]
[BREAKING] Do not export ScriptTransformer
- it can be imported from @jest/transform
instead (#9256)[jest-runtime]
Use JestEnvironment.getVmContext
and vm.compileFunction
if available to avoid the module wrapper (#9252 & #9428)[jest-snapshot]
Display change counts in annotation lines (#8982)[jest-snapshot]
[BREAKING] Improve report when the matcher has properties (#9104)[jest-snapshot]
Improve colors when snapshots are updatable (#9132)[jest-snapshot]
Ignore indentation for most serialized objects (#9203)[jest-transform]
Create createTranspilingRequire
function for easy transpiling modules (#9194)[jest-transform]
[BREAKING] Return transformed code as a string, do not wrap in vm.Script
(#9253)[@jest/test-result]
Create method to create empty TestResult
(#8867)[jest-worker]
[BREAKING] Return a promise from end()
, resolving with the information whether workers exited gracefully (#8206)[jest-reporters]
Transform file paths into hyperlinks (#8980)[expect]
Display expectedDiff
more carefully in toBeCloseTo
(#8389)[expect]
Avoid incorrect difference for subset when toMatchObject
fails (#9005)[expect]
Consider all RegExp flags for equality (#9167)[expect]
[BREAKING] Consider primitives different from wrappers instantiated with new
(#9167)[expect]
Prevent maintaining RegExp state between multiple tests (#9289)[expect]
Fix subsetEquality false circular reference detection (#9322)[jest-config]
Use half of the available cores when watchAll
mode is enabled (#9117)[jest-config]
Fix Jest multi project runner still cannot handle exactly one project (#8894)[jest-console]
Add missing console.group
calls to NullConsole
(#9024)[jest-core]
Don't include unref'd timers in --detectOpenHandles results (#8941)[jest-core]
Limit number of workers when creating haste maps in projects (#9259)[jest-diff]
Do not inverse format if line consists of one change (#8903)[jest-diff]
Rename some new options and change their default values (#9077)[jest-environment-node]
Fix TextEncoder.encode
not referencing same global Uint8Array
constructor (#9261)[jest-fake-timers]
getTimerCount
will not include cancelled immediates (#8764)[jest-fake-timers]
Support util.promisify
on setTimeout
(#9180)[jest-jasmine2, jest-circus]
Improve error message format for Node's assert.fail (#9262)[jest-leak-detector]
[BREAKING] Use weak-napi
instead of weak
package (#8686)[jest-mock]
Fix for mockReturnValue overriding mockImplementationOnce (#8398)[jest-reporters]
Make node-notifier an optional dependency (#8918)[jest-reporters]
Make all arguments to methods on BaseReporter
optional (#9159)[jest-resolve]
: Set MODULE_NOT_FOUND as error code when module is not resolved from paths (#8487)[jest-resolve-dependencies]
Handle dynamic dependencies correctly even when using module maps (#9303)[jest-snapshot]
Remove only the added newlines in multiline snapshots (#8859)[jest-snapshot]
Distinguish empty string from external snapshot not written (#8880)[jest-snapshot]
[BREAKING] Distinguish empty string from internal snapshot not written (#8898)[jest-snapshot]
[BREAKING] Remove report
method and throw matcher errors (#9049)[jest-snapshot]
Omit irrelevant received
properties when property matchers fail (#9198)[jest-transform]
Properly cache transformed files across tests (#8890)[jest-transform]
Don't fail the test suite when a generated source map is invalid (#9058)[jest-types]
[BREAKING] Use less null | undefined
in config types (#9200)[jest-util]
Allow querying process.domain (#9136)[pretty-format]
Correctly detect memoized elements (#9196)[pretty-format]
Fix pretty-format to respect displayName on forwardRef (#9422)[*]
[BREAKING] Drop support for Node 6 (#8455)[*]
Add Node 12 to CI (#8411)[*]
[BREAKING] Upgrade to Micromatch v4 (#8852)[babel-plugin-jest-hoist]
[BREAKING] Use ESM exports (#8874)[docs]
Add alias and optional boolean value to coverage
CLI Reference (#8996)[docs]
Fix broken link pointing to legacy JS file in "Snapshot Testing".[docs]
Add setupFilesAfterEnv
and jest.setTimeout
example (#8971)[expect]
Test that toStrictEqual
is equivalent to Node's assert.deepStrictEqual
(#9167)[jest]
[BREAKING] Use ESM exports (#8874)[jest-cli]
[BREAKING] Use ESM exports (#8874)[jest-cli]
[BREAKING] Remove re-exports from @jest/core
(#8874)[jest-diff]
Remove the need to export splitLines0
function (#9151)[jest-environment-jsdom]
[BREAKING] Upgrade JSDOM from v11 to v15 (#8851)[jest-haste-map]
Upgrade to fsevents@2
(#9215)[jest-reporters]
[BREAKING] Upgrade Istanbul dependencies, which are used for code coverage (#9192)[jest-util]
[BREAKING] Remove deprecated exports (#8863)[jest-validate]
[BREAKING] Use ESM exports (#8874)[jest-types]
Mark InitialOptions
as Partial
(#8848)[jest-config]
Refactor normalize
to be more type safe (#8848)FAQs
Stringify any JavaScript value.
The npm package pretty-format receives a total of 83,165,758 weekly downloads. As such, pretty-format popularity was classified as popular.
We found that pretty-format demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 3 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
ESLint has added JSON and Markdown linting support with new officially-supported plugins, expanding its versatility beyond JavaScript.
Security News
Members Hub is conducting large-scale campaigns to artificially boost Discord server metrics, undermining community trust and platform integrity.
Security News
NIST has failed to meet its self-imposed deadline of clearing the NVD's backlog by the end of the fiscal year. Meanwhile, CVE's awaiting analysis have increased by 33% since June.