-
-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
create-snapshot.js
103 lines (86 loc) · 2.62 KB
/
create-snapshot.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
"use strict";
const raw = require("jest-snapshot-serializer-raw").wrap;
const visualizeRange = require("./visualize-range.js");
const visualizeEndOfLine = require("./visualize-end-of-line.js");
const SEPARATOR_WIDTH = 80;
function printSeparator(description = "") {
const leftLength = Math.floor((SEPARATOR_WIDTH - description.length) / 2);
const rightLength = SEPARATOR_WIDTH - leftLength - description.length;
return "=".repeat(leftLength) + description + "=".repeat(rightLength);
}
function stringify(value) {
return value === Number.POSITIVE_INFINITY
? "Infinity"
: Array.isArray(value)
? `[${value.map((v) => JSON.stringify(v)).join(", ")}]`
: JSON.stringify(value);
}
function printOptions(options) {
const {
plugins,
filepath,
errors,
parser,
pluginSearchDirs,
...snapshotOptions
} = options;
if (pluginSearchDirs !== false) {
snapshotOptions.pluginSearchDirs = pluginSearchDirs;
}
const keys = Object.keys(snapshotOptions).sort();
return keys
.map((key) => `${key}: ${stringify(snapshotOptions[key])}`)
.join("\n");
}
function printWidthIndicator(printWidth, offset) {
if (!Number.isFinite(printWidth) || printWidth < 1) {
return "";
}
let before = "";
if (offset) {
before = " ".repeat(offset - 1) + "|";
}
return `${before}${" ".repeat(printWidth)}| printWidth`;
}
function createSnapshot(
formatResult,
{ parsers, formatOptions, CURSOR_PLACEHOLDER }
) {
let {
inputWithCursor: input,
outputWithCursor: output,
options,
} = formatResult;
let { rangeStart, rangeEnd, cursorOffset, printWidth } = options;
let codeOffset = 0;
if (typeof rangeStart === "number" || typeof rangeEnd === "number") {
if (typeof cursorOffset === "number") {
if (typeof rangeStart === "number" && rangeStart > cursorOffset) {
rangeStart += CURSOR_PLACEHOLDER.length;
}
if (typeof rangeEnd === "number" && rangeEnd > cursorOffset) {
rangeEnd += CURSOR_PLACEHOLDER.length;
}
}
input = visualizeRange(input, { rangeStart, rangeEnd });
codeOffset = input.match(/^>?\s+1 \|/)[0].length + 1;
}
if ("endOfLine" in formatOptions) {
input = visualizeEndOfLine(input);
output = visualizeEndOfLine(output);
}
const widthIndicator = printWidthIndicator(printWidth, codeOffset);
return raw(
[
printSeparator("options"),
printOptions({ ...options, parsers }),
...(widthIndicator ? [widthIndicator] : []),
printSeparator("input"),
input,
printSeparator("output"),
output,
printSeparator(),
].join("\n")
);
}
module.exports = createSnapshot;