-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy pathinlineSnapshot.ts
226 lines (194 loc) · 6.51 KB
/
inlineSnapshot.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
import type MagicString from 'magic-string'
import type { SnapshotEnvironment } from '../types'
import {
getCallLastIndex,
lineSplitRE,
offsetToLineNumber,
positionToOffset,
} from '../../../utils/src/index'
export interface InlineSnapshot {
snapshot: string
testId: string
file: string
line: number
column: number
}
export async function saveInlineSnapshots(
environment: SnapshotEnvironment,
snapshots: Array<InlineSnapshot>,
): Promise<void> {
const MagicString = (await import('magic-string')).default
const files = new Set(snapshots.map(i => i.file))
await Promise.all(
Array.from(files).map(async (file) => {
const snaps = snapshots.filter(i => i.file === file)
const code = await environment.readSnapshotFile(file) as string
const s = new MagicString(code)
for (const snap of snaps) {
const index = positionToOffset(code, snap.line, snap.column)
replaceInlineSnap(code, s, index, snap.snapshot)
}
const transformed = s.toString()
if (transformed !== code) {
await environment.saveSnapshotFile(file, transformed)
}
}),
)
}
const startObjectRegex
= /(?:toMatchInlineSnapshot|toThrowErrorMatchingInlineSnapshot)\s*\(\s*(?:\/\*[\s\S]*\*\/\s*|\/\/.*(?:[\n\r\u2028\u2029]\s*|[\t\v\f \xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF]))*\{/
function replaceObjectSnap(
code: string,
s: MagicString,
index: number,
newSnap: string,
) {
let _code = code.slice(index)
const startMatch = startObjectRegex.exec(_code)
if (!startMatch) {
return false
}
_code = _code.slice(startMatch.index)
let callEnd = getCallLastIndex(_code)
if (callEnd === null) {
return false
}
callEnd += index + startMatch.index
const shapeStart = index + startMatch.index + startMatch[0].length
const shapeEnd = getObjectShapeEndIndex(code, shapeStart)
const snap = `, ${prepareSnapString(newSnap, code, index)}`
if (shapeEnd === callEnd) {
// toMatchInlineSnapshot({ foo: expect.any(String) })
s.appendLeft(callEnd, snap)
}
else {
// toMatchInlineSnapshot({ foo: expect.any(String) }, ``)
s.overwrite(shapeEnd, callEnd, snap)
}
return true
}
function getObjectShapeEndIndex(code: string, index: number) {
let startBraces = 1
let endBraces = 0
while (startBraces !== endBraces && index < code.length) {
const s = code[index++]
if (s === '{') {
startBraces++
}
else if (s === '}') {
endBraces++
}
}
return index
}
function prepareSnapString(snap: string, source: string, index: number) {
const lineNumber = offsetToLineNumber(source, index)
const line = source.split(lineSplitRE)[lineNumber - 1]
const indent = line.match(/^\s*/)![0] || ''
const indentNext = indent.includes('\t') ? `${indent}\t` : `${indent} `
const lines = snap.trim().replace(/\\/g, '\\\\').split(/\n/g)
const isOneline = lines.length <= 1
const quote = '`'
if (isOneline) {
return `${quote}${lines
.join('\n')
.replace(/`/g, '\\`')
.replace(/\$\{/g, '\\${')}${quote}`
}
return `${quote}\n${lines
.map(i => (i ? indentNext + i : ''))
.join('\n')
.replace(/`/g, '\\`')
.replace(/\$\{/g, '\\${')}\n${indent}${quote}`
}
const toMatchInlineName = 'toMatchInlineSnapshot'
const toThrowErrorMatchingInlineName = 'toThrowErrorMatchingInlineSnapshot'
// on webkit, the line number is at the end of the method, not at the start
function getCodeStartingAtIndex(code: string, index: number) {
const indexInline = index - toMatchInlineName.length
if (code.slice(indexInline, index) === toMatchInlineName) {
return {
code: code.slice(indexInline),
index: indexInline,
}
}
const indexThrowInline = index - toThrowErrorMatchingInlineName.length
if (code.slice(index - indexThrowInline, index) === toThrowErrorMatchingInlineName) {
return {
code: code.slice(index - indexThrowInline),
index: index - indexThrowInline,
}
}
return {
code: code.slice(index),
index,
}
}
const startRegex
= /(?:toMatchInlineSnapshot|toThrowErrorMatchingInlineSnapshot)\s*\(\s*(?:\/\*[\s\S]*\*\/\s*|\/\/.*(?:[\n\r\u2028\u2029]\s*|[\t\v\f \xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF]))*[\w$]*(['"`)])/
export function replaceInlineSnap(
code: string,
s: MagicString,
currentIndex: number,
newSnap: string,
): boolean {
const { code: codeStartingAtIndex, index } = getCodeStartingAtIndex(code, currentIndex)
const startMatch = startRegex.exec(codeStartingAtIndex)
const firstKeywordMatch = /toMatchInlineSnapshot|toThrowErrorMatchingInlineSnapshot/.exec(
codeStartingAtIndex,
)
if (!startMatch || startMatch.index !== firstKeywordMatch?.index) {
return replaceObjectSnap(code, s, index, newSnap)
}
const quote = startMatch[1]
const startIndex = index + startMatch.index + startMatch[0].length
const snapString = prepareSnapString(newSnap, code, index)
if (quote === ')') {
s.appendRight(startIndex - 1, snapString)
return true
}
const quoteEndRE = new RegExp(`(?:^|[^\\\\])${quote}`)
const endMatch = quoteEndRE.exec(code.slice(startIndex))
if (!endMatch) {
return false
}
const endIndex = startIndex + endMatch.index! + endMatch[0].length
s.overwrite(startIndex - 1, endIndex, snapString)
return true
}
const INDENTATION_REGEX = /^([^\S\n]*)\S/m
export function stripSnapshotIndentation(inlineSnapshot: string): string {
// Find indentation if exists.
const match = inlineSnapshot.match(INDENTATION_REGEX)
if (!match || !match[1]) {
// No indentation.
return inlineSnapshot
}
const indentation = match[1]
const lines = inlineSnapshot.split(/\n/g)
if (lines.length <= 2) {
// Must be at least 3 lines.
return inlineSnapshot
}
if (lines[0].trim() !== '' || lines[lines.length - 1].trim() !== '') {
// If not blank first and last lines, abort.
return inlineSnapshot
}
for (let i = 1; i < lines.length - 1; i++) {
if (lines[i] !== '') {
if (lines[i].indexOf(indentation) !== 0) {
// All lines except first and last should either be blank or have the same
// indent as the first line (or more). If this isn't the case we don't
// want to touch the snapshot at all.
return inlineSnapshot
}
lines[i] = lines[i].substring(indentation.length)
}
}
// Last line is a special case because it won't have the same indent as others
// but may still have been given some indent to line up.
lines[lines.length - 1] = ''
// Return inline snapshot, now at indent 0.
inlineSnapshot = lines.join('\n')
return inlineSnapshot
}