-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy pathutils.ts
318 lines (268 loc) · 8.43 KB
/
utils.ts
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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import type { OptionsReceived as PrettyFormatOptions } from '@vitest/pretty-format'
import type { SnapshotData, SnapshotStateOptions } from '../types'
import type { SnapshotEnvironment } from '../types/environment'
import { format as prettyFormat } from '@vitest/pretty-format'
import naturalCompare from 'natural-compare'
import { isObject } from '../../../utils/src/index'
import { getSerializers } from './plugins'
// TODO: rewrite and clean up
export function testNameToKey(testName: string, count: number): string {
return `${testName} ${count}`
}
export function keyToTestName(key: string): string {
if (!/ \d+$/.test(key)) {
throw new Error('Snapshot keys must end with a number.')
}
return key.replace(/ \d+$/, '')
}
export function getSnapshotData(
content: string | null,
options: SnapshotStateOptions,
): {
data: SnapshotData
dirty: boolean
} {
const update = options.updateSnapshot
const data = Object.create(null)
let snapshotContents = ''
let dirty = false
if (content != null) {
try {
snapshotContents = content
// eslint-disable-next-line no-new-func
const populate = new Function('exports', snapshotContents)
populate(data)
}
catch {}
}
// const validationResult = validateSnapshotVersion(snapshotContents)
const isInvalid = snapshotContents // && validationResult
// if (update === 'none' && isInvalid)
// throw validationResult
if ((update === 'all' || update === 'new') && isInvalid) {
dirty = true
}
return { data, dirty }
}
// Add extra line breaks at beginning and end of multiline snapshot
// to make the content easier to read.
export function addExtraLineBreaks(string: string): string {
return string.includes('\n') ? `\n${string}\n` : string
}
// Remove extra line breaks at beginning and end of multiline snapshot.
// Instead of trim, which can remove additional newlines or spaces
// at beginning or end of the content from a custom serializer.
export function removeExtraLineBreaks(string: string): string {
return string.length > 2 && string.startsWith('\n') && string.endsWith('\n')
? string.slice(1, -1)
: string
}
// export const removeLinesBeforeExternalMatcherTrap = (stack: string): string => {
// const lines = stack.split('\n')
// for (let i = 0; i < lines.length; i += 1) {
// // It's a function name specified in `packages/expect/src/index.ts`
// // for external custom matchers.
// if (lines[i].includes('__EXTERNAL_MATCHER_TRAP__'))
// return lines.slice(i + 1).join('\n')
// }
// return stack
// }
const escapeRegex = true
const printFunctionName = false
export function serialize(
val: unknown,
indent = 2,
formatOverrides: PrettyFormatOptions = {},
): string {
return normalizeNewlines(
prettyFormat(val, {
escapeRegex,
indent,
plugins: getSerializers(),
printFunctionName,
...formatOverrides,
}),
)
}
export function minify(val: unknown): string {
return prettyFormat(val, {
escapeRegex,
min: true,
plugins: getSerializers(),
printFunctionName,
})
}
// Remove double quote marks and unescape double quotes and backslashes.
export function deserializeString(stringified: string): string {
return stringified.slice(1, -1).replace(/\\("|\\)/g, '$1')
}
export function escapeBacktickString(str: string): string {
return str.replace(/`|\\|\$\{/g, '\\$&')
}
function printBacktickString(str: string): string {
return `\`${escapeBacktickString(str)}\``
}
export function normalizeNewlines(string: string): string {
return string.replace(/\r\n|\r/g, '\n')
}
export async function saveSnapshotFile(
environment: SnapshotEnvironment,
snapshotData: SnapshotData,
snapshotPath: string,
): Promise<void> {
const snapshots = Object.keys(snapshotData)
.sort(naturalCompare)
.map(
key =>
`exports[${printBacktickString(key)}] = ${printBacktickString(
normalizeNewlines(snapshotData[key]),
)};`,
)
const content = `${environment.getHeader()}\n\n${snapshots.join('\n\n')}\n`
const oldContent = await environment.readSnapshotFile(snapshotPath)
const skipWriting = oldContent != null && oldContent === content
if (skipWriting) {
return
}
await environment.saveSnapshotFile(snapshotPath, content)
}
export async function saveSnapshotFileRaw(
environment: SnapshotEnvironment,
content: string,
snapshotPath: string,
): Promise<void> {
const oldContent = await environment.readSnapshotFile(snapshotPath)
const skipWriting = oldContent != null && oldContent === content
if (skipWriting) {
return
}
await environment.saveSnapshotFile(snapshotPath, content)
}
export function prepareExpected(expected?: string): string | undefined {
function findStartIndent() {
// Attempts to find indentation for objects.
// Matches the ending tag of the object.
const matchObject = /^( +)\}\s+$/m.exec(expected || '')
const objectIndent = matchObject?.[1]?.length
if (objectIndent) {
return objectIndent
}
// Attempts to find indentation for texts.
// Matches the quote of first line.
const matchText = /^\n( +)"/.exec(expected || '')
return matchText?.[1]?.length || 0
}
const startIndent = findStartIndent()
let expectedTrimmed = expected?.trim()
if (startIndent) {
expectedTrimmed = expectedTrimmed
?.replace(new RegExp(`^${' '.repeat(startIndent)}`, 'gm'), '')
.replace(/ +\}$/, '}')
}
return expectedTrimmed
}
function deepMergeArray(target: any[] = [], source: any[] = []) {
const mergedOutput = Array.from(target)
source.forEach((sourceElement, index) => {
const targetElement = mergedOutput[index]
if (Array.isArray(target[index])) {
mergedOutput[index] = deepMergeArray(target[index], sourceElement)
}
else if (isObject(targetElement)) {
mergedOutput[index] = deepMergeSnapshot(target[index], sourceElement)
}
else {
// Source does not exist in target or target is primitive and cannot be deep merged
mergedOutput[index] = sourceElement
}
})
return mergedOutput
}
/**
* Deep merge, but considers asymmetric matchers. Unlike base util's deep merge,
* will merge any object-like instance.
* Compatible with Jest's snapshot matcher. Should not be used outside of snapshot.
*
* @example
* ```ts
* toMatchSnapshot({
* name: expect.stringContaining('text')
* })
* ```
*/
export function deepMergeSnapshot(target: any, source: any): any {
if (isObject(target) && isObject(source)) {
const mergedOutput = { ...target }
Object.keys(source).forEach((key) => {
if (isObject(source[key]) && !source[key].$$typeof) {
if (!(key in target)) {
Object.assign(mergedOutput, { [key]: source[key] })
}
else {
mergedOutput[key] = deepMergeSnapshot(target[key], source[key])
}
}
else if (Array.isArray(source[key])) {
mergedOutput[key] = deepMergeArray(target[key], source[key])
}
else {
Object.assign(mergedOutput, { [key]: source[key] })
}
})
return mergedOutput
}
else if (Array.isArray(target) && Array.isArray(source)) {
return deepMergeArray(target, source)
}
return target
}
export class DefaultMap<K, V> extends Map<K, V> {
constructor(
private defaultFn: (key: K) => V,
entries?: Iterable<readonly [K, V]>,
) {
super(entries)
}
override get(key: K): V {
if (!this.has(key)) {
this.set(key, this.defaultFn(key))
}
return super.get(key)!
}
}
export class CounterMap<K> extends DefaultMap<K, number> {
constructor() {
super(() => 0)
}
// compat for jest-image-snapshot https://github.com/vitest-dev/vitest/issues/7322
// `valueOf` and `Snapshot.added` setter allows
// snapshotState.added = snapshotState.added + 1
// to function as
// snapshotState.added.total_ = snapshotState.added.total() + 1
_total: number | undefined
valueOf(): number {
return this._total = this.total()
}
increment(key: K): void {
if (typeof this._total !== 'undefined') {
this._total++
}
this.set(key, this.get(key) + 1)
}
total(): number {
if (typeof this._total !== 'undefined') {
return this._total
}
let total = 0
for (const x of this.values()) {
total += x
}
return total
}
}