Launch Week Day 3: Introducing Organization Notifications in Socket.Learn More
Socket
Book a DemoSign in
Socket

jest-serializer-ansi-escapes

Package Overview
Dependencies
Maintainers
1
Versions
7
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

jest-serializer-ansi-escapes - npm Package Compare versions

Comparing version
2.0.1
to
3.0.0
+3
index.d.ts
declare const ansiEscapesSerializer: import("pretty-format").NewPlugin;
export = ansiEscapesSerializer;
const prettyAnsi = require("pretty-ansi");
const escape = "\u001b";
const ansiEscapesSerializer = {
serialize(text, config, indentation, depth, refs, printer) {
return printer(prettyAnsi(text), config, indentation, depth, refs);
},
test(val) {
return typeof val === "string" && val.includes(escape);
},
};
module.exports = ansiEscapesSerializer;
+28
-34
{
"name": "jest-serializer-ansi-escapes",
"version": "3.0.0",
"description": "Jest snapshot serializer for ANSI escape sequences",
"version": "2.0.1",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/mrazauskas/jest-serializer-ansi-escapes.git"
},
"keywords": [

@@ -17,38 +12,37 @@ "ansi",

"serializer",
"testing",
"cursor",
"colors",
"cli",
"console",
"terminal"
"testing"
],
"main": "src/index.js",
"types": "src/index.d.ts",
"repository": {
"type": "git",
"url": "git+https://github.com/mrazauskas/jest-serializer-ansi-escapes.git"
},
"license": "MIT",
"funding": "https://github.com/sponsors/mrazauskas",
"type": "commonjs",
"main": "index.js",
"types": "index.d.ts",
"files": [
"src/*.js",
"src/*.d.ts"
"index.d.ts",
"index.js"
],
"scripts": {
"lint": "yarn lint:eslint && yarn lint:prettier",
"lint:eslint": "eslint . --ext js",
"lint:prettier": "prettier . --write",
"test": "jest"
"check": "dprint check",
"format": "dprint fmt",
"lint": "eslint . --config eslint.config.json --ext js",
"test": "jest",
"test:coverage": "npm run test -- --coverage --coverageProvider v8"
},
"dependencies": {
"pretty-ansi": "2.0.0"
},
"devDependencies": {
"@babel/core": "7.18.5",
"@babel/preset-env": "7.18.2",
"ansi-escapes": "4.3.2",
"ansi-styles": "5.2.0",
"babel-jest": "28.1.1",
"eslint": "8.18.0",
"eslint-config-prettier": "8.5.0",
"eslint-plugin-jest": "26.5.3",
"jest": "28.1.1",
"prettier": "2.6.2",
"pretty-format": "28.1.1"
"dprint": "0.45.0",
"eslint": "8.56.0",
"eslint-plugin-jest": "27.9.0",
"jest": "29.7.0",
"pretty-format": "29.7.0"
},
"engines": {
"node": ">=14"
},
"packageManager": "yarn@3.2.1"
"node": ">=16"
}
}
+36
-26
# jest-serializer-ansi-escapes
> Jest snapshot serializer for ANSI escape sequences.
[![version][version-badge]][version-url]
[![license][license-badge]][license-url]
[![packagephobia][packagephobia-badge]][packagephobia-url]
[![coverage][coverage-badge]][coverage-url]
[![version](https://img.shields.io/npm/v/jest-serializer-ansi-escapes)](https://npmjs.com/package/jest-serializer-ansi-escapes)
[![license](https://img.shields.io/github/license/mrazauskas/jest-serializer-ansi-escapes)](https://github.com/mrazauskas/jest-serializer-ansi-escapes/blob/main/LICENSE.md)
[![coverage](https://img.shields.io/codecov/c/github/mrazauskas/jest-serializer-ansi-escapes/main)](https://app.codecov.io/gh/mrazauskas/jest-serializer-ansi-escapes)
Jest snapshot serializer for ANSI escape sequences.
This snapshot serializer turns [ANSI escape sequences](https://en.wikipedia.org/wiki/ANSI_escape_code) into human readable text. It implements serialization of color, style and cursor control escapes and works with vanilla sequences as well as the output from libraries like `chalk`, `colors`, `ansi-escapes`, `ansi-styles` or `terminal-kit`.
---
This snapshot serializer converts [ANSI escape sequences](https://en.wikipedia.org/wiki/ANSI_escape_code) into human readable text. It supports color, style and cursor control escapes and works with vanilla sequences as well as the output from libraries like `chalk`, `colors`, `ansi-escapes`, `ansi-styles` or `terminal-kit`.
For example, the following test:

@@ -15,3 +18,3 @@

// ansiEscapes.test.js
import ansiEscapesSerializer from 'jest-serializer-ansi-escapes';
import ansiEscapesSerializer from "jest-serializer-ansi-escapes";

@@ -23,11 +26,11 @@ expect.addSnapshotSerializer(ansiEscapesSerializer);

jest
.spyOn(process.stdout, 'write')
.spyOn(process.stdout, "write")
.mockImplementation((chunk) => output.push(chunk));
test('ansi escapes', () => {
process.stdout.write('\u001b[1;2mLoading...\u001b[0m');
process.stdout.write('\u001b[2K\u001b[G');
process.stdout.write('\u001b[3;32mSuccess!\u001b[0m');
test("ansi escapes", () => {
process.stdout.write("\u001b[1;2mLoading...\u001b[0m");
process.stdout.write("\u001b[2K\u001b[G");
process.stdout.write("\u001b[3;32mSuccess!\u001b[0m");
expect(output.join('')).toMatchSnapshot();
expect(output.join("")).toMatchSnapshot();
});

@@ -50,5 +53,3 @@ ```

```bash
yarn add --dev jest-serializer-ansi-escapes
# or
npm install --save-dev jest-serializer-ansi-escapes
npm add -D jest-serializer-ansi-escapes
```

@@ -61,3 +62,3 @@

```js
import ansiEscapesSerializer from 'jest-serializer-ansi-escapes';
import ansiEscapesSerializer from "jest-serializer-ansi-escapes";

@@ -71,3 +72,3 @@ expect.addSnapshotSerializer(ansiEscapesSerializer);

module.exports = {
snapshotSerializers: ['jest-serializer-ansi-escapes'],
snapshotSerializers: ["jest-serializer-ansi-escapes"],
};

@@ -78,9 +79,9 @@ ```

A Jest snapshot serializer is a plugin of Pretty Format, hence this serializer can be also used directly with [`pretty-format`](https://github.com/facebook/jest/tree/main/packages/pretty-format) library:
A Jest snapshot serializer is a plugin of Pretty Format, hence this serializer can be also used directly with [`pretty-format`](https://github.com/jestjs/jest/tree/main/packages/pretty-format) library:
```js
import { format as prettyFormat } from 'pretty-format';
import ansiEscapesSerializer from 'jest-serializer-ansi-escapes';
import { format as prettyFormat } from "pretty-format";
import ansiEscapesSerializer from "jest-serializer-ansi-escapes";
const sequence = '\u001b[26G';
const sequence = "\u001b[26G";

@@ -91,3 +92,3 @@ const formattedSequence = prettyFormat(sequence, {

console.log(formattedSequence); // '<moveCursorToColumn26>'
console.log(formattedSequence); // <moveCursorToColumn26>
```

@@ -99,10 +100,19 @@

Keep in mind that the escape sequences are not validated. Unrecognized sequence will print as `'<ESC>[a1b2c3'`, or as `'<?>'` in case this is a color or style sequence.
Keep in mind that the escape sequences are not validated. Unrecognized sequence will print as `<ESC>[a1b2c3`, or as `<?>` in case this is a color or style sequence.
## Contributing
## Related
Something is missing for your project? Just open an issue or send a PR.
[`pretty-ansi`](https://github.com/mrazauskas/pretty-ansi) — Convert ANSI escape sequences to human readable text.
## License
[MIT](https://github.com/mrazauskas/jest-serializer-ansi-escapes/blob/main/LICENSE.md)
[MIT][license-url]
[version-badge]: https://badgen.net/npm/v/jest-serializer-ansi-escapes
[version-url]: https://npmjs.com/package/jest-serializer-ansi-escapes
[license-badge]: https://badgen.net/github/license/mrazauskas/jest-serializer-ansi-escapes
[license-url]: https://github.com/mrazauskas/jest-serializer-ansi-escapes/blob/main/LICENSE.md
[packagephobia-badge]: https://badgen.net/packagephobia/install/jest-serializer-ansi-escapes
[packagephobia-url]: https://packagephobia.com/result?p=jest-serializer-ansi-escapes
[coverage-badge]: https://badgen.net/codacy/coverage/af1dd8dbbb384a3abb7371ac75b5ac85
[coverage-url]: https://app.codacy.com/gh/mrazauskas/jest-serializer-ansi-escapes/coverage/dashboard
const escape = "\u001b";
const colorText = new Map([
["0", "/"],
["1", "bold"],
["2", "dim"],
["3", "italic"],
["4", "underline"],
["7", "inverse"],
["8", "hidden"],
["9", "strikethrough"],
["22", "/intensity"],
["23", "/italic"],
["24", "/underline"],
["27", "/inverse"],
["28", "/hidden"],
["29", "/strikethrough"],
["30", "black"],
["31", "red"],
["32", "green"],
["33", "yellow"],
["34", "blue"],
["35", "magenta"],
["36", "cyan"],
["37", "white"],
["39", "/color"],
["40", "backgroundBlack"],
["41", "backgroundRed"],
["42", "backgroundGreen"],
["43", "backgroundYellow"],
["44", "backgroundBlue"],
["45", "backgroundMagenta"],
["46", "backgroundCyan"],
["47", "backgroundWhite"],
["49", "/background"],
["53", "overline"],
["55", "/overline"],
["90", "gray"],
["91", "brightRed"],
["92", "brightGreen"],
["93", "brightYellow"],
["94", "brightBlue"],
["95", "brightMagenta"],
["96", "brightCyan"],
["97", "brightWhite"],
["100", "backgroundGray"],
["101", "backgroundBrightRed"],
["102", "backgroundBrightGreen"],
["103", "backgroundBrightYellow"],
["104", "backgroundBrightBlue"],
["105", "backgroundBrightMagenta"],
["106", "backgroundBrightCyan"],
["107", "backgroundBrightWhite"],
]);
const commandText = new Map([
["A", ["moveCursorUpBy", "Row"]],
["B", ["moveCursorDownBy", "Row"]],
["C", ["moveCursorRightBy", "Column"]],
["D", ["moveCursorLeftBy", "Column"]],
["E", ["moveCursorDownBy", "Row", "ToColumn1"]],
["F", ["moveCursorUpBy", "Row", "ToColumn1"]],
["G", ["moveCursorTo", ["Column"]]],
["H", ["moveCursorTo", ["Row", "Column"]]],
["S", ["scrollUpBy", "Row"]],
["T", ["scrollDownBy", "Row"]],
["f", ["moveCursorTo", ["Row", "Column"]]],
]);
/**
* @param {string} sequenceText
* @returns {string}
*/
function colorOrStyleSequenceReplacer(sequenceText) {
/** @type {Array<string>} */
const replacement = [];
const colorParameters = sequenceText.match(/\d{1,3}/g) || ["0"];
colorParameters.forEach((colorParameter) => {
replacement.push(colorText.get(colorParameter) || "?");
});
return `<${replacement.join(", ")}>`;
}
/**
* @param {string} sequenceText
* @returns {string}
*/
function moveCursorByReplacer(sequenceText) {
/** @type {Array<string>} */
const replacement = [];
sequenceText = sequenceText.trimEnd();
const parameterValue = sequenceText.match(/\[(\d*)/)[1];
const [command, parameterName, tailText] = commandText.get(
sequenceText.slice(-1)
);
replacement.push(command, parameterValue || 1, parameterName);
replacement.push(parameterValue > 1 ? "s" : "");
replacement.push(tailText);
return `<${replacement.join("")}>\n`;
}
/**
* @param {string} sequenceText
* @returns {string}
*/
function moveCursorToReplacer(sequenceText) {
/** @type {Array<string>} */
const replacement = [];
sequenceText = sequenceText.trimEnd();
const parameterValues = sequenceText.match(/\[(\d*;?\d*)/)[1].split(";");
const [command, parameterNames] = commandText.get(sequenceText.slice(-1));
replacement.push(command);
parameterNames.forEach((parameterName) => {
replacement.push(parameterName, parameterValues.shift() || 1);
});
return `<${replacement.join("")}>\n`;
}
/**
* @param {string} text
* @returns {string}
*/
function serializeAnsi(text) {
return text
.replace(/\u001b\[(\d*;?)*m/g, colorOrStyleSequenceReplacer)
.replace(/.(?=\u001b)/g, (match) => `${match}\n`)
.replace(
/\u001b\[2J\n?\u001b\[(3J\n?\u001b\[H|0f)\n?/g,
"<clearTerminal>\n"
)
.replace(/\u001b\[\d*[A-FST]\n?/g, moveCursorByReplacer)
.replace(/\u001b\[\d*G\n?/g, moveCursorToReplacer)
.replace(/\u001b\[\d*;?\d*[Hf]\n?/g, moveCursorToReplacer)
.replace(/\u001b\[0?J\n?/g, "<eraseScreenDown>\n")
.replace(/\u001b\[1J\n?/g, "<eraseScreenUp>\n")
.replace(/\u001b\[2J\n?/g, "<eraseScreen>\n")
.replace(/\u001b\[3J\n?/g, "<eraseScreenAndDeleteBuffer>\n")
.replace(/\u001b\[0?K\n?/g, "<eraseLineEnd>\n")
.replace(/\u001b\[1K\n?/g, "<eraseLineStart>\n")
.replace(/\u001b\[2K\n?/g, "<eraseLine>\n")
.replace(/\u001b\[6n\n?/g, "<getCursorPosition>\n")
.replace(/\u001b(\[s|7)\n?/g, "<saveCursorPosition>\n")
.replace(/\u001b(\[u|8)\n?/g, "<restoreCursorPosition>\n")
.replace(/\u001b\[\?25h\n?/g, "<showCursor>\n")
.replace(/\u001b\[\?25l\n?/g, "<hideCursor>\n")
.replace(escape, "<ESC>");
}
/** @type {import('pretty-format').NewPlugin} */
const ansiEscapesSerializer = {
serialize(text, config, indentation, depth, refs, printer) {
return printer(serializeAnsi(text), config, indentation, depth, refs);
},
test(val) {
return typeof val === "string" && val.includes(escape);
},
};
module.exports = { ansiEscapesSerializer };
declare const ansiEscapesSerializer: import("pretty-format").NewPlugin;
export = ansiEscapesSerializer;
const { ansiEscapesSerializer } = require("./ansiEscapesSerializer");
module.exports = ansiEscapesSerializer;