格式
字符串化任何JavaScript值。
- 序列化内置JavaScript类型。
- 使用内置或用户定义的插件序列化特定于应用程序的数据类型。
安装
$ 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]
*/
| 关键 | 类型 | 默认的 | 描述 |
|---|---|---|---|
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颜色
const DEFAULT_THEME = {
comment: 'gray',
content: 'reset',
prop: 'yellow',
tag: 'cyan',
value: 'green',
};
插件用法
这个 pretty-format 包提供了一些内置插件,包括:
ReactElement的元素reactReactTestComponent的测试对象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>
*/
笑话用法
对于快照测试,Jest使用 pretty-format 与选项,包括一些内置的插件。为此,插件也被称为 快照序列化器。
要序列化特定于应用程序的数据类型,可以将模块添加到 devDependencies 一个项目,然后:
在一个 个人 测试文件中,可以添加如下模块。它位于Jest配置中的任何模块之前。
import serializer from 'my-serializer-module';
expect.addSnapshotSerializer(serializer);
// tests which have `expect(value).toMatchSnapshot()` assertions
为 所有 测试文件,您可以在Jest配置中指定模块。它们位于React、HTML和Immutable.js数据类型的内置插件之前。例如,在a package.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 nullTypeError: Cannot read property 'whatever' of undefined
例如, test 内置法 ReactElement 插件:
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 的颜色值theme(例如,'cyan')
中的一些属性 config 来源于 min 在 options:
spacingInner和spacingOuter是 换行符 如果min是falsespacingInner是 空间 和spacingOuter是 空字符串 如果min是true
序列化和测试的示例
这个插件是一个模式,您可以应用它来序列化复合数据类型。注: pretty-format 不需要插件来序列化数组。
// 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"}]}
*/
打印
这个 原始 接口是足够的插件:
- 那 不 依赖于其他选项
highlight或min - 那 不 取决于
depth或refs在递归遍历中,和 - If值任选其一
- 做。 不 要求缩进,或
- 做。 不 作为JavaScript数据结构(例如,数组)的子元素出现
写 print 给定参数,返回一个字符串:
val“通过了考验”- 当前的
printer(valChild)回调函数:序列化子函数 - 当前的
indenter(lines)回调函数:在下一层缩进行 - 不变的
config对象:来源于options - 不变的
colors对象:来源于options
的三个性质 config 是 min 在 options 和:
spacing和edgeSpacing是 换行符 如果min是falsespacing是 空间 和edgeSpacing是 空字符串 如果min是true
的每个性质 colors 对应于的性质 theme 在 options:
- 关键是一样的(例如,
tag) - 的值
colors是一个对象open和close其值为转义码的属性 ansi-styles 的颜色值theme(例如,'cyan')
打印和测试的示例
这个插件使用 命名参数的数量 不包括rest参数。
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],
}
*/
这个插件 忽略了 这个 printFunctionName 选择。原来的限制 print 界面是使用改进的一个原因 serialize 接口,如上所述。
prettyFormat(val, {
plugins: [pluginOld],
printFunctionName: false,
});
/*
Object {
"onClick": [Function onClick 1],
"render": [Function render 0],
}
*/
prettyFormat(val, {
printFunctionName: false,
});
/*
Object {
"onClick": [Function],
"render": [Function],
}
*/