Socket
Socket
Sign inDemoInstall

pretty-format

Package Overview
Dependencies
Maintainers
5
Versions
237
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

pretty-format - npm Package Compare versions

Comparing version 21.0.0-alpha.2 to 21.0.0-beta.1

83

build/plugins/html_element.js

@@ -13,4 +13,11 @@ 'use strict';Object.defineProperty(exports, "__esModule", { value: true });exports.serialize = exports.test = undefined;

var _escape_html = require('./lib/escape_html');var _escape_html2 = _interopRequireDefault(_escape_html);
var _markup = require('./lib/markup');function _interopRequireDefault(obj) {return obj && obj.__esModule ? obj : { default: obj };}
var _markup = require('./lib/markup'); /**
* Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
*/

@@ -36,31 +43,19 @@

const ELEMENT_NODE = 1;
const TEXT_NODE = 3;
const COMMENT_NODE = 8;
const ELEMENT_REGEXP = /^(HTML|SVG)\w*?Element$/;
const HTML_ELEMENT_REGEXP = /(HTML\w*?Element)|Text|Comment/; /**
* Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
*/const test = exports.test = val => val !== undefined && val !== null && (val.nodeType === 1 || val.nodeType === 3 || val.nodeType === 8) && val.constructor !== undefined && val.constructor.name !== undefined && HTML_ELEMENT_REGEXP.test(val.constructor.name);
const testNode = (nodeType, name) =>
nodeType === ELEMENT_NODE && ELEMENT_REGEXP.test(name) ||
nodeType === TEXT_NODE && name === 'Text' ||
nodeType === COMMENT_NODE && name === 'Comment';
// Return empty string if children is empty.
function printChildren(children, config, indentation, depth, refs, printer) {
const colors = config.colors;
return children.
map(
node =>
typeof node === 'string' ?
colors.content.open + (0, _escape_html2.default)(node) + colors.content.close :
printer(node, config, indentation, depth, refs)).
const test = exports.test = val =>
val &&
val.constructor &&
val.constructor.name &&
testNode(val.nodeType, val.constructor.name);
filter(value => value.trim().length).
map(value => config.spacingOuter + indentation + value).
join('');
}
const getType = element => element.tagName.toLowerCase();
// Convert array of attribute objects to keys array and props object.

@@ -74,3 +69,3 @@ const keysMapper = attribute => attribute.name;

const serialize = exports.serialize = (
element,
node,
config,

@@ -82,30 +77,20 @@ indentation,

{
if (element.nodeType === 3) {
return element.data.
split('\n').
map(text => text.trimLeft()).
filter(text => text.length).
join(' ');
if (node.nodeType === TEXT_NODE) {
return (0, _markup.printText)(node.data, config);
}
const colors = config.colors;
if (element.nodeType === 8) {
return (
colors.comment.open +
'<!-- ' +
element.data.trim() +
' -->' +
colors.comment.close);
if (node.nodeType === COMMENT_NODE) {
return (0, _markup.printComment)(node.data, config);
}
const type = node.tagName.toLowerCase();
if (++depth > config.maxDepth) {
return (0, _markup.printElementAsLeaf)(getType(element), config);
return (0, _markup.printElementAsLeaf)(type, config);
}
return (0, _markup.printElement)(
getType(element),
type,
(0, _markup.printProps)(
Array.prototype.map.call(element.attributes, keysMapper).sort(),
Array.prototype.reduce.call(element.attributes, propsReducer, {}),
Array.prototype.map.call(node.attributes, keysMapper).sort(),
Array.prototype.reduce.call(node.attributes, propsReducer, {}),
config,

@@ -117,4 +102,4 @@ indentation + config.indent,

printChildren(
Array.prototype.slice.call(element.childNodes),
(0, _markup.printChildren)(
Array.prototype.slice.call(node.childNodes),
config,

@@ -121,0 +106,0 @@ indentation + config.indent,

@@ -1,2 +0,2 @@

'use strict';Object.defineProperty(exports, "__esModule", { value: true });exports.printElementAsLeaf = exports.printElement = exports.printChildren = exports.printProps = undefined;
'use strict';Object.defineProperty(exports, "__esModule", { value: true });exports.printElementAsLeaf = exports.printElement = exports.printComment = exports.printText = exports.printChildren = exports.printProps = undefined;

@@ -68,3 +68,2 @@

{
const colors = config.colors;
return children.

@@ -76,3 +75,3 @@ map(

typeof child === 'string' ?
colors.content.open + (0, _escape_html2.default)(child) + colors.content.close :
printText(child, config) :
printer(child, config, indentation, depth, refs))).

@@ -83,2 +82,18 @@

const printText = exports.printText = (text, config) => {
const contentColor = config.colors.content;
return contentColor.open + (0, _escape_html2.default)(text) + contentColor.close;
};
const printComment = exports.printComment = (comment, config) => {
const commentColor = config.colors.comment;
return (
commentColor.open +
'<!--' +
(0, _escape_html2.default)(comment) +
'-->' +
commentColor.close);
};
// Separate the functions to format props, children, and element,

@@ -85,0 +100,0 @@ // so a plugin could override a particular function, if needed.

{
"name": "pretty-format",
"version": "21.0.0-alpha.2",
"version": "21.0.0-beta.1",
"repository": {

@@ -5,0 +5,0 @@ "type": "git",

@@ -148,24 +148,307 @@ # pretty-format

### Plugins
## Usage in Jest
Pretty format also supports adding plugins:
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.
```js
const fooPlugin = {
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:
```json
{
"jest": {
"snapshotSerializers": ["my-serializer-module"]
}
}
```
## Writing plugins
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)
### test
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:
```js
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.
### serialize
The **improved** interface is available in **version 21** or later.
Write `serialize` to return a string, given the arguments:
* `val` which “passed the test”
* unchanging `config` object: derived from `options`
* current `indentation` string: concatenate to `indent` from `config`
* current `depth` number: compare to `maxDepth` from `config`
* current `refs` array: find circular references in objects
* `printer` callback function: serialize children
### config
| key | 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 |
| `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`:
* the key is the same (for example, `tag`)
* 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'`)
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`
### Example of serialize and test
This plugin is a pattern you can apply to serialize composite data types. Of course, `pretty-format` does not need a plugin to serialize arrays :)
```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 val && val.hasOwnProperty('foo');
return Array.isArray(val);
},
print(val, print, indent) {
return 'Foo: ' + print(val.foo);
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 obj = {foo: {bar: {}}};
```js
const val = {
filter: 'completed',
items: [
{
text: 'Write test',
completed: true,
},
{
text: 'Write serialize',
completed: true,
},
],
};
```
prettyFormat(obj, {
plugins: [fooPlugin],
```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"}]}
*/
```
### print
The **original** interface is adequate for plugins:
* that **do not** depend on options other than `highlight` or `min`
* that **do not** depend on `depth` or `refs` in recursive traversal, and
* if values either
* do **not** require indentation, or
* do **not** occur as children of JavaScript data structures (for example, array)
Write `print` to return a string, given the arguments:
* `val` which “passed the test”
* current `printer(valChild)` callback function: serialize children
* current `indenter(lines)` callback function: indent lines at the next level
* unchanging `config` object: derived from `options`
* unchanging `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`:
* the key is the same (for example, `tag`)
* 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'`)
### Example of print and test
This plugin prints functions with the **number of named arguments** excluding rest argument.
```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],
});
// Foo: Object {
// "bar": Object {}
// }
/*
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.
```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],
}
*/
```

Sorry, the diff of this file is too big to display

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc