
Research
Security News
The Growing Risk of Malicious Browser Extensions
Socket researchers uncover how browser extensions in trusted stores are used to hijack sessions, redirect traffic, and manipulate user behavior.
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 {format: prettyFormat} = require('pretty-format'); // CommonJS
import {format as 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 |
compareKeys | function|null | undefined | compare function used when sorting object keys, null can be used to skip over sorting |
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 |
maxWidth | number | Infinity | number of elements to print in arrays, sets, and so on |
min | boolean | false | minimize added space: no indentation nor line breaks |
plugins | array | [] | plugins to serialize application-specific data types |
printBasicPrototype | boolean | false | print the prototype for plain objects and arrays |
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 React = require('react');
const renderer = require('react-test-renderer');
const {format: prettyFormat, plugins} = require('pretty-format');
const {ReactElement, ReactTestComponent} = plugins;
// ES2015 modules and destructuring assignment
import React from 'react';
import renderer from 'react-test-renderer';
import {plugins, format as prettyFormat} from 'pretty-format';
const {ReactElement, ReactTestComponent} = plugins;
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 |
compareKeys | function|null | compare function used when sorting object keys, null can be used to skip over sorting |
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 | string | spacing to separate items in a list |
spacingOuter | string | 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],
}
*/
30.0.0
[*]
Renamed globalsCleanupMode
to globalsCleanup
and --waitNextEventLoopTurnForUnhandledRejectionEvents
to --waitForUnhandledRejections
[expect]
Add ArrayOf
asymmetric matcher for validating array elements. (#15567)[babel-jest]
Add option excludeJestPreset
to allow opting out of babel-preset-jest
(#15164)[expect]
Revert #15038 to fix expect(fn).toHaveBeenCalledWith(expect.objectContaining(...))
when there are multiple calls (#15508)[jest-circus, jest-cli, jest-config]
Add waitNextEventLoopTurnForUnhandledRejectionEvents
flag to minimise performance impact of correct detection of unhandled promise rejections introduced in #14315 (#14681)[jest-circus]
Add a waitBeforeRetry
option to jest.retryTimes
(#14738)[jest-circus]
Add a retryImmediately
option to jest.retryTimes
(#14696)[jest-circus, jest-jasmine2]
Allow setupFilesAfterEnv
to export an async function (#10962)[jest-circus, jest-test-result]
Add startedAt
timestamp in TestCaseResultObject
within onTestCaseResult
(#15145)[jest-cli]
Export buildArgv
(#15310)[jest-config]
[BREAKING] Add mts
and cts
to default moduleFileExtensions
config (#14369)[jest-config]
[BREAKING] Update testMatch
and testRegex
default option for supporting mjs
, cjs
, mts
, and cts
(#14584)[jest-config]
Loads config file from provided path in package.json
(#14044)[jest-config]
Allow loading jest.config.cts
files (#14070)[jest-config]
Show rootDir
in error message when a preset
fails to load (#15194)[jest-config]
Support loading TS config files using esbuild-register
via docblock loader (#15190)[jest-config]
Allow passing TS config loader options via docblock comment (#15234)[jest-config]
If Node is running with type stripping enabled, do not require a TS loader (#15480)[@jest/core]
Group together open handles with the same stack trace (#13417, & #14789)[@jest/core]
Add perfStats
to surface test setup overhead (#14622)[@jest/core]
[BREAKING] Changed --filter
to accept an object with shape { filtered: Array<string> }
to match documentation (#13319)[@jest/core]
Support --outputFile
option for --listTests
(#14980)[@jest/core]
Stringify Errors properly with --json
flag (#15329)[@jest/core, @jest/test-sequencer]
[BREAKING] Exposes globalConfig
& contexts
to TestSequencer
(#14535, & #14543)[jest-each]
Introduce %$
option to add number of the test to its title (#14710)[@jest/environment]
[BREAKING] Remove deprecated jest.genMockFromModule()
(#15042)[@jest/environment]
[BREAKING] Remove unnecessary defensive code (#15045)[jest-environment-jsdom]
[BREAKING] Upgrade JSDOM to v22 (#13825)[@jest/environment-jsdom-abstract]
Introduce new package which abstracts over the jsdom
environment, allowing usage of custom versions of JSDOM (#14717)[jest-environment-node]
Update jest environment with dispose symbols Symbol
(#14888 & #14909)[expect, @jest/expect]
[BREAKING] Add type inference for function parameters in CalledWith
assertions (#15129)[@jest/expect-utils]
Properly compare all types of TypedArray
s (#15178)[@jest/fake-timers]
[BREAKING] Upgrade @sinonjs/fake-timers
to v13 (#14544 & #15470)[@jest/fake-timers]
Exposing new modern timers function advanceTimersToFrame()
which advances all timers by the needed milliseconds to execute callbacks currently scheduled with requestAnimationFrame
(#14598)[jest-matcher-utils]
Add SERIALIZABLE_PROPERTIES
to allow custom serialization of objects (#14893)[jest-mock]
Add support for the Explicit Resource Management proposal to use the using
keyword with jest.spyOn(object, methodName)
(#14895)[jest-reporters]
Add support for DEC mode 2026 (#15008)[jest-resolver]
Support file://
URLs as paths (#15154)[jest-resolve,jest-runtime,jest-resolve-dependencies]
Pass the conditions when resolving stub modules (#15489)[jest-runtime]
Exposing new modern timers function jest.advanceTimersToFrame()
from @jest/fake-timers
(#14598)[jest-runtime]
Support import.meta.filename
and import.meta.dirname
(available from Node 20.11) (#14854)[jest-runtime]
Support import.meta.resolve
(#14930)[jest-runtime]
[BREAKING] Make it mandatory to pass globalConfig
to the Runtime
constructor (#15044)[jest-runtime]
Add unstable_unmockModule
(#15080)[jest-runtime]
Add onGenerateMock
transformer callback for auto generated callbacks (#15433 & #15482)[jest-runtime]
[BREAKING] Use vm.compileFunction
over vm.Script
(#15461)[@jest/schemas]
Upgrade @sinclair/typebox
to v0.34 (#15450)[@jest/types]
test.each()
: Accept a readonly (as const
) table properly (#14565)[@jest/types]
Improve argument type inference passed to test
and describe
callback functions from each
tables (#14920)[jest-snapshot]
[BREAKING] Add support for Error causes in snapshots (#13965)[jest-snapshot]
Support Prettier 3 (#14566)[@jest/util-snapshot]
Extract utils used by tooling from jest-snapshot
into its own package (#15095)[pretty-format]
[BREAKING] Do not render empty string children (''
) in React plugin (#14470)[expect]
Show AggregateError
to display (#15346)[*]
Replace exit
with exit-x
(#15399)[babel-plugin-jest-hoist]
Use denylist
instead of the deprecated blacklist
for Babel 8 support (#14109)[babel-plugin-jest-hoist]
Do not rely on buggy Babel behaviour (#15415)[expect]
Check error instance type for toThrow/toThrowError
(#14576)[expect]
Improve diff for failing expect.objectContaining
(#15038)[expect]
Use Array.isArray
to check if an array is an Array
(#15101)[expect]
Fix Error cause
assertion errors (#15339)[jest-changed-files]
Print underlying errors when VCS commands fail (#15052)[jest-changed-files]
Abort sl root
call if output resembles a steam locomotive (#15053)[jest-circus]
[BREAKING] Prevent false test failures caused by promise rejections handled asynchronously (#14315)[jest-circus]
Replace recursive makeTestResults
implementation with iterative one (#14760)[jest-circus]
Omit expect.hasAssertions()
errors if a test already has errors (#14866)[jest-circus, jest-expect, jest-snapshot]
Pass test.failing
tests when containing failing snapshot matchers (#14313)[jest-circus]
Concurrent tests now emit jest circus events at the correct point and in the expected order. (#15381)[jest-cli]
[BREAKING] Validate CLI flags that require arguments receives them (#14783)[jest-config]
Make sure to respect runInBand
option (#14578)[jest-config]
Support testTimeout
in project config (#14697)[jest-config]
Support coverageReporters
in project config (#14697)[jest-config]
Allow reporters
in project config (#14768)[jest-config]
Allow Node16/NodeNext/Bundler moduleResolution
in project's tsconfig (#14739)[@jest/create-cache-key-function]
Correct the return type of createCacheKey
(#15159)[jest-each]
Allow $keypath
templates with null
or undefined
values (#14831)[@jest/expect-utils]
Fix comparison of DataView
(#14408)[@jest/expect-utils]
[BREAKING] exclude non-enumerable in object matching (#14670)[@jest/expect-utils]
Fix comparison of URL
(#14672)[@jest/expect-utils]
Check Symbol
properties in equality (#14688)[@jest/expect-utils]
Catch circular references within arrays when matching objects (#14894)[@jest/expect-utils]
Fix not addressing to Sets and Maps as objects without keys (#14873)[jest-haste-map]
Fix errors or clobbering with multiple hasteImplModulePath
s (#15522)[jest-leak-detector]
Make leak-detector more aggressive when running GC (#14526)[jest-runtime]
Properly handle re-exported native modules in ESM via CJS (#14589)[jest-runtime]
Refactor _importCoreModel
so required core module is consistent if modified while loading (#15077)[jest-schemas, jest-types]
[BREAKING] Fix type of testFailureExitCode
config option(#15232)[jest-util]
Make sure isInteractive
works in a browser (#14552)[pretty-format]
[BREAKING] Print ArrayBuffer
and DataView
correctly (#14290)[pretty-format]
Fixed a bug where "anonymous custom elements" were not being printed as expected. (#15138)[jest-cli]
When specifying paths on the command line, only match against the relative paths of the test files (#12519)
testPathPattern
configuration option to testPathPatterns
, which now takes a list of patterns instead of the regex.--testPathPattern
is now --testPathPatterns
testPathPatterns
when programmatically calling watch
must be specified as new TestPathPatterns(patterns)
, where TestPathPatterns
can be imported from @jest/pattern
[jest-reporters, jest-runner]
Unhandled errors without stack get correctly logged to console (#14619)[jest-util]
Always load mjs
files with import
(#15447)[jest-worker]
Properly handle a circular reference error when worker tries to send an assertion fails where either the expected or actual value is circular (#15191)[jest-worker]
Properly handle a BigInt when worker tries to send an assertion fails where either the expected or actual value is BigInt (#15191)[expect]
Resolve issue where ObjectContaining
matched non-object values. ([#15463])(https://github.com/jestjs/jest/pull/15463).
conditional/check
to ensure the argument passed to expect
is an object.ObjectContaining
behavior.invalid/wrong
test case assertions for ObjectContaining
.[jest-worker]
Addresses incorrect state on exit (#15610)[*]
[BREAKING] Bundle all of Jest's modules into index.js
(#12348, #14550 & #14661)[jest-haste-map]
Only spawn one process to check for watchman
installation (#14826)[jest-runner]
Better cleanup source-map-support
after test to resolve (minor) memory leak (#15233)[jest-circus, jest-environment-node, jest-repl, jest-runner, jest-util]
Cleanup global variables on environment teardown to reduce memory leaks (#15215 & #15636 & #15643)[jest-environment-jsdom, jest-environment-jsdom-abstract]
Increased version of jsdom to ^26.0.0
(#15325CVE-2024-37890)[*]
Increase version of micromatch
to ^4.0.7
(#15082)[*]
[BREAKING] Drop support for Node.js versions 14, 16, 19, 21 and 23 (#14460, #15118, #15623, #15640)[*]
[BREAKING] Drop support for typescript@4.3
, minimum version is now 5.4
(#14542, #15621)[*]
Depend on exact versions of monorepo dependencies instead of ^
range (#14553)[*]
[BREAKING] Add ESM wrapper for all of Jest's modules (#14661)[*]
[BREAKING] Upgrade to glob@10
(#14509)[*]
Use TypeError
over Error
where appropriate (#14799)[docs]
Fix typos in CHANGELOG.md
and packages/jest-validate/README.md
(#14640)[docs]
Don't use alias matchers in docs (#14631)[babel-jest, babel-preset-jest]
[BREAKING] Increase peer dependency of @babel/core
to ^7.11
(#14109)[babel-jest, @jest/transform]
Update babel-plugin-istanbul
to v6 (#15156)[babel-plugin-jest-hoist]
Move unnecessary dependencies
to devDependencies
(#15010)[expect]
[BREAKING] Remove .toBeCalled()
, .toBeCalledTimes()
, .toBeCalledWith()
, .lastCalledWith()
, .nthCalledWith()
, .toReturn()
, .toReturnTimes()
, .toReturnWith()
, .lastReturnedWith()
, .nthReturnedWith()
and .toThrowError()
matcher aliases (#14632)[jest-cli, jest-config, @jest/types]
[BREAKING] Remove deprecated --init
argument (#14490)[jest-config, @jest/core, jest-util]
Upgrade ci-info
(#14655)[jest-mock]
[BREAKING] Remove MockFunctionMetadataType
, MockFunctionMetadata
and SpyInstance
types (#14621)[@jest/reporters]
Upgrade istanbul-lib-source-maps
(#14924)[jest-schemas]
Upgrade @sinclair/typebox
(#14775)[jest-transform]
Upgrade write-file-atomic
(#14274)[jest-util]
Upgrade picomatch
to v4 (#14653 & #14885)[docs] Append to NODE_OPTIONS, not overwrite ([#14730](https://github.com/jestjs/jest/pull/14730))
[docs]
Updated .toHaveBeenCalled()
documentation to correctly reflect its functionality (#14842)[docs]
Link NestJS documentation on testing with Jest (#14940)[docs]
Revised documentation for .toHaveBeenCalled()
to accurately depict its functionality. (#14853)[docs]
Removed ExpressJS reference link from documentation due to dead link (#15270)[docs]
Correct broken links in docs (#15359)FAQs
Stringify any JavaScript value.
The npm package pretty-format receives a total of 105,379,531 weekly downloads. As such, pretty-format popularity was classified as popular.
We found that pretty-format demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 5 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.
Research
Security News
Socket researchers uncover how browser extensions in trusted stores are used to hijack sessions, redirect traffic, and manipulate user behavior.
Research
Security News
An in-depth analysis of credential stealers, crypto drainers, cryptojackers, and clipboard hijackers abusing open source package registries to compromise Web3 development environments.
Security News
pnpm 10.12.1 introduces a global virtual store for faster installs and new options for managing dependencies with version catalogs.