# pretty-format 中文文档

规范地址：https://npmcn.com/package/pretty-format/

版本：30\.5\.1
npm 元数据更新时间：2026-09-01T07:58:05.401Z
中文译文更新时间：2026-11-04T13:35:12.193Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/pretty-format
原文对照：https://npmcn.com/package/pretty-format/?lang=original
项目主页：https://github.com/jestjs/jest#readme
源码仓库：https://github.com/jestjs/jest

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：61.3 kB，6 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- Node.js 要求：^18\.14\.0 \|\| ^20\.0\.0 \|\| ^22\.0\.0 \|\| \>=24\.0\.0
- 运行依赖：4 个
- 首次发布：2015-03-08T04:52:08.223Z
- 最新版本发布：2026-09-01T07:58:05.173Z
- 近 30 天下载量：918698082（2026-10-05 至 2026-11-03，npm 官方下载统计）
- 已发布版本数：253（近 12 个月 5 个）

## 中文简介

字符串化任何JavaScript值。

## 安装

```sh
npm install pretty-format
```

也可以使用：`pnpm add pretty-format`、`yarn add pretty-format`、`bun add pretty-format`

## README

# 格式

字符串化任何JavaScript值。

-   序列化内置JavaScript类型。
-   使用内置或用户定义的插件序列化特定于应用程序的数据类型。

## 安装

```sh
$ yarn add pretty-format
```

## 用法

```js
const {format: prettyFormat} = require('pretty-format'); // CommonJS
```

```js
import {format as prettyFormat} from 'pretty-format'; // ES2015 modules
```

```js
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",
}
*/
```

## 与选项一起使用

```js
function onClick() {}

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

const options = {
  printFunctionName: false,
};
console.log(prettyFormat(onClick, options));
/*
[Function]
*/
```

| 关键 | 类型 | 默认的 | 描述 |
| :-- | :-- | :-- | :-- |
| `callToJSON` | `boolean` | `true` | 呼叫 `toJSON` 方法（如果存在） |
| `compareKeys` | `function|null` | `undefined` | 排序对象键时使用的比较函数， `null` 可以用来跳过排序吗 |
| `escapeRegex` | `boolean` | `false` | 正则表达式中的特殊字符转义 |
| `escapeString` | `boolean` | `true` | 转义字符串中的特殊字符 |
| `highlight` | `boolean` | `false` | 在终端用颜色高亮语法（一些插件） |
| `indent` | `number` | `2` | 每层缩进中的空格 |
| `maxDepth` | `number` | `Infinity` | 要在数组、对象、元素等中打印的级别 |
| `maxWidth` | `number` | `Infinity` | 要在数组、集合等中打印的元素数目 |
| `min` | `boolean` | `false` | 尽量减少增加的空间：没有缩进和换行 |
| `plugins` | `array` | `[]` | 用于序列化应用程序特定数据类型的插件 |
| `printBasicPrototype` | `boolean` | `false` | 打印普通对象和数组的原型 |
| `printFunctionName` | `boolean` | `true` | 包括或省略函数名 |
| `theme` | `object` |  | 在终端中突出显示语法的颜色 |

的属性值 `theme` 来自 [ansi-styles颜色](https://github.com/chalk/ansi-styles#colors)

```js
const DEFAULT_THEME = {
  comment: 'gray',
  content: 'reset',
  prop: 'yellow',
  tag: 'cyan',
  value: 'green',
};
```

## 插件用法

这个 `pretty-format` 包提供了一些内置插件，包括：

-   `ReactElement` 的元素 `react`
-   `ReactTestComponent` 的测试对象 `react-test-renderer` (弃用)

```js
// CommonJS
const React = require('react');
const renderer = require('react-test-renderer');
const {format: prettyFormat, plugins} = require('pretty-format');

const {ReactElement, ReactTestComponent} = plugins;
```

```js
// 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;
```

```js
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>
*/
```

## 笑话用法

对于快照测试，Jest使用 `pretty-format` 与选项，包括一些内置的插件。为此，插件也被称为 **快照序列化器**。

要序列化特定于应用程序的数据类型，可以将模块添加到 `devDependencies` 一个项目，然后：

在一个 **个人** 测试文件中，可以添加如下模块。它位于Jest配置中的任何模块之前。

```js
import serializer from 'my-serializer-module';
expect.addSnapshotSerializer(serializer);

// tests which have `expect(value).toMatchSnapshot()` assertions
```

为 **所有** 测试文件，您可以在Jest配置中指定模块。它们位于React、HTML和Immutable.js数据类型的内置插件之前。例如，在a `package.json` 文件:

```json
{
  "jest": {
    "snapshotSerializers": ["my-serializer-module"]
  }
}
```

## 编写插件

插件是一个JavaScript对象。

如果 `options` 有一个 `plugins` 数组：用于第一个插件 `test(val)` 方法返回真值 `prettyFormat(val, options)` 返回下列任一操作的结果：

-   `serialize(val, …)` 方法 **改进的** 接口(可在 **版本21** 或更高版本)
-   `print(val, …)` 方法 **原始** 接口（如果插件没有） `serialize` 方法)

### 测试

写 `test` 所以它可以接收 `val` 任何类型的参数。序列化 **对象** 哪一个有一定的属性，那么一个谨慎的表达就像 `val != null && …` 或者更简洁一点 `val && …` 防止以下错误：

-   `TypeError: Cannot read property 'whatever' of null`
-   `TypeError: Cannot read property 'whatever' of undefined`

例如, `test` 内置法 `ReactElement` 插件:

```js
const elementSymbol = Symbol.for('react.element');
const test = val => val && val.$$typeof === elementSymbol;
```

注意效率 `test` 因为 `pretty-format` 经常打电话。

### 序列化

这个 **改进的** 接口在 **版本21** 或更高版本。

写 `serialize` 给定参数，返回一个字符串：

-   `val` “通过了考验”
-   不变的 `config` 对象：来源于 `options`
-   当前的 `indentation` 字符串：连接到 `indent` 从 `config`
-   当前的 `depth` 数字：与…相比 `maxDepth` 从 `config`
-   当前的 `refs` 数组：查找对象中的循环引用
-   `printer` 回调函数：序列化子函数

### 配置

| 关键 | 类型 | 描述 |
| :-- | :-- | :-- |
| `callToJSON` | `boolean` | 呼叫 `toJSON` 方法（如果存在） |
| `compareKeys` | `function|null` | 排序对象键时使用的比较函数， `null` 可以用来跳过排序吗 |
| `colors` | `Object` | 用于突出显示语法的颜色的转义码 |
| `escapeRegex` | `boolean` | 正则表达式中的特殊字符转义 |
| `escapeString` | `boolean` | 转义字符串中的特殊字符 |
| `indent` | `string` | 每层缩进中的空格 |
| `maxDepth` | `number` | 要在数组、对象、元素等中打印的级别 |
| `min` | `boolean` | 尽量减少增加的空间：没有缩进和换行 |
| `plugins` | `array` | 用于序列化应用程序特定数据类型的插件 |
| `printFunctionName` | `boolean` | 包括或省略函数名 |
| `spacingInner` | `string` | 分隔列表中项目的空格 |
| `spacingOuter` | `string` | 包含项目列表的空格 |

的每个性质 `colors` 在 `config` 对应于的性质 `theme` 在 `options`：

-   关键是一样的(例如， `tag`）
-   的值 `colors` 是一个对象 `open` 和 `close` 其值为转义码的属性 [ansi-styles](https://github.com/chalk/ansi-styles) 的颜色值 `theme` (例如, `'cyan'`）

中的一些属性 `config` 来源于 `min` 在 `options`：

-   `spacingInner` 和 `spacingOuter` 是 **换行符** 如果 `min` 是 `false`
-   `spacingInner` 是 **空间** 和 `spacingOuter` 是 **空字符串** 如果 `min` 是 `true`

### 序列化和测试的示例

这个插件是一个模式，您可以应用它来序列化复合数据类型。注: `pretty-format` 不需要插件来序列化数组。

```js
// 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,
        )}]`;
  },
};
```

```js
const val = {
  filter: 'completed',
  items: [
    {
      text: 'Write test',
      completed: true,
    },
    {
      text: 'Write serialize',
      completed: true,
    },
  ],
};
```

```js
console.log(
  prettyFormat(val, {
    plugins: [plugin],
  }),
);
/*
Object {
  "filter": "completed",
  "items": Array [
    Object {
      "completed": true,
      "text": "Write test",
    },
    Object {
      "completed": true,
      "text": "Write serialize",
    },
  ],
}
*/
```

```js
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",
        },
    ],
}
*/
```

```js
console.log(
  prettyFormat(val, {
    maxDepth: 1,
    plugins: [plugin],
  }),
);
/*
Object {
  "filter": "completed",
  "items": [Array],
}
*/
```

```js
console.log(
  prettyFormat(val, {
    min: true,
    plugins: [plugin],
  }),
);
/*
{"filter": "completed", "items": [{"completed": true, "text": "Write test"}, {"completed": true, "text": "Write serialize"}]}
*/
```

### 打印

这个 **原始** 接口是足够的插件：

-   那 **不** 依赖于其他选项 `highlight` 或 `min`
-   那 **不** 取决于 `depth` 或 `refs` 在递归遍历中，和
-   If值任选其一
    -   做。 **不** 要求缩进，或
    -   做。 **不** 作为JavaScript数据结构（例如，数组）的子元素出现

写 `print` 给定参数，返回一个字符串：

-   `val` “通过了考验”
-   当前的 `printer(valChild)` 回调函数：序列化子函数
-   当前的 `indenter(lines)` 回调函数：在下一层缩进行
-   不变的 `config` 对象：来源于 `options`
-   不变的 `colors` 对象：来源于 `options`

的三个性质 `config` 是 `min` 在 `options` 和:

-   `spacing` 和 `edgeSpacing` 是 **换行符** 如果 `min` 是 `false`
-   `spacing` 是 **空间** 和 `edgeSpacing` 是 **空字符串** 如果 `min` 是 `true`

的每个性质 `colors` 对应于的性质 `theme` 在 `options`：

-   关键是一样的(例如， `tag`）
-   的值 `colors` 是一个对象 `open` 和 `close` 其值为转义码的属性 [ansi-styles](https://github.com/chalk/ansi-styles) 的颜色值 `theme` (例如, `'cyan'`）

### 打印和测试的示例

这个插件使用 **命名参数的数量** 不包括rest参数。

```js
const plugin = {
  print(val) {
    return `[Function ${val.name || 'anonymous'} ${val.length}]`;
  },
  test(val) {
    return typeof val === 'function';
  },
};
```

```js
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],
}
*/
```

这个插件 **忽略了** 这个 `printFunctionName` 选择。原来的限制 `print` 界面是使用改进的一个原因 `serialize` 接口，如上所述。

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

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

## 常见问题

### pretty-format 是什么？

字符串化任何JavaScript值。

### 如何安装 pretty-format？

在项目目录运行 npm install pretty-format，或使用 pnpm add / yarn add / bun add。

### pretty-format 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### pretty-format 支持 ESM 还是 CommonJS？

同时提供 ES Module 与 CommonJS 入口，import 和 require\(\) 都可以使用，打包工具会自动选择合适的版本。

### pretty-format 需要什么版本的 Node\.js？

package\.json 的 engines 字段要求 Node\.js ^18\.14\.0 \|\| ^20\.0\.0 \|\| ^22\.0\.0 \|\| \>=24\.0\.0。版本不符时 npm 默认只给出警告，开启 engine-strict 后会拒绝安装。

### pretty-format 可以商用吗？

pretty-format 使用 MIT 许可。宽松许可：允许商业使用、修改和再分发，通常只需在分发时保留原版权与许可声明。以上为概括，不构成法律意见，请以许可原文为准。

### pretty-format 的下载量有多少？

根据 npm 官方下载统计，pretty-format 在 2026/10/05 – 2026/11/03 这 30 天内被下载 918,698,082 次，日均约 30,623,269 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### pretty-format 还在维护吗？

最新版本 30\.5\.1 发布于 2026/09/01（2 个月前）；至今共发布 253 个版本，其中过去 12 个月发布了 5 个；首次发布于 2015/03/08。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

