/
utils.ts
236 lines (197 loc) · 6.53 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
/**
* 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 fs, { promises as fsp } from 'fs'
import path from 'pathe'
import naturalCompare from 'natural-compare'
import type { OptionsReceived as PrettyFormatOptions } from 'pretty-format'
import {
format as prettyFormat,
} from 'pretty-format'
import type { SnapshotData, SnapshotUpdateState } from '../../../types'
import { isObject } from '../../../utils'
import { getSerializers } from './plugins'
// TODO: rewrite and clean up
export const SNAPSHOT_VERSION = '1'
const writeSnapshotVersion = () => `// Vitest Snapshot v${SNAPSHOT_VERSION}`
export const testNameToKey = (testName: string, count: number): string =>
`${testName} ${count}`
export const keyToTestName = (key: string): string => {
if (!/ \d+$/.test(key))
throw new Error('Snapshot keys must end with a number.')
return key.replace(/ \d+$/, '')
}
export const getSnapshotData = (
snapshotPath: string,
update: SnapshotUpdateState,
): {
data: SnapshotData
dirty: boolean
} => {
const data = Object.create(null)
let snapshotContents = ''
let dirty = false
if (fs.existsSync(snapshotPath)) {
try {
snapshotContents = fs.readFileSync(snapshotPath, 'utf8')
// 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 const addExtraLineBreaks = (string: string): string =>
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 const removeExtraLineBreaks = (string: string): string =>
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 ensureDirectoryExists(filePath: string): void {
try {
fs.mkdirSync(path.join(path.dirname(filePath)), { recursive: true })
}
catch { }
}
function normalizeNewlines(string: string) {
return string.replace(/\r\n|\r/g, '\n')
}
export async function saveSnapshotFile(
snapshotData: SnapshotData,
snapshotPath: string,
) {
const snapshots = Object.keys(snapshotData)
.sort(naturalCompare)
.map(
key => `exports[${printBacktickString(key)}] = ${printBacktickString(normalizeNewlines(snapshotData[key]))};`,
)
ensureDirectoryExists(snapshotPath)
await fsp.writeFile(
snapshotPath,
`${writeSnapshotVersion()}\n\n${snapshots.join('\n\n')}\n`,
'utf-8',
)
}
export function prepareExpected(expected?: string) {
function findStartIndent() {
const match = /^( +)[}|"]/m.exec(expected || '')
return match?.[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
}