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
319
320 |
x9
x9
x9
x9
x9
x9
x9
x9
x9
x9
x12
x12
x12
x12
x12
x12
x12
x15
x45
x15
x15
x15
x15
x15
x15
x15
x15
x21
x21
x21
x24
x24
x24
x24
x27
x27
x24
x21
x15
x15
x12
x12
x12
x12
x9
x18
x18
x21
x21
x21
x21
x21
x21
x21
x21
x21
x21
x21
x21
x21
x21
x21
x21
x21
x21
x21
x22
x66
x22
x22
x22
x18
x9
x18
x9
x9
x9
x9
x9
x21
x21
x21
x21
x30
x30
x24
x24
x24
x72
x24
x24
x24
x27
x27
x27
x27
x27
x27
x27
x27
x27
x27
x24
x24
x24
x24
x24
x24
x24
x24
x24
x21
x9
x9
x9
x12
x12
x12
x12
x13
x13
x13
x13
x12
x12 |
I
I
I
I
I
I
I
I
I
I
I
|
// Copyright 2018-2025 the Deno authors. MIT license.
// @ts-nocheck Deno.lint namespace does not pass type checking in Deno 1.x
import type { SnapshotOptions } from "./snapshot.ts";
import { AssertionError } from "@std/assert/assertion-error";
import { equal } from "@std/assert/equal";
import {
escapeStringForJs,
getIsUpdate,
getOptions,
getSnapshotNotMatchMessage,
LINT_SUPPORTED,
serialize,
} from "./_snapshot_utils.ts";
/**
* The options for {@linkcode assertInlineSnapshot}.
*
* @experimental **UNSTABLE**: New API, yet to be vetted.
*/
export interface InlineSnapshotOptions<T = unknown>
extends Pick<SnapshotOptions<T>, "msg" | "serializer"> {}
interface ErrorLocation {
lineNumber: number;
columnNumber: number;
}
interface SnapshotUpdateRequest {
fileName: string;
lineNumber: number;
columnNumber: number;
actualSnapshot: string;
}
// See https://v8.dev/docs/stack-trace-api
type V8Error = typeof Error & {
prepareStackTrace(error: Error, structuredStackTrace: CallSite[]): unknown;
};
// See https://v8.dev/docs/stack-trace-api
interface CallSite {
isEval(): boolean;
getFileName(): string | null;
getLineNumber(): number | null;
getColumnNumber(): number | null;
}
function makeSnapshotUpdater(
updateRequests: SnapshotUpdateRequest[],
): Deno.lint.Plugin {
return {
name: "snapshot-updater-plugin",
rules: {
"update-snapshot": {
create(context) {
const src = context.sourceCode.text;
// TODO(WWRS): Add \u2028 and \u2029 once Deno counts them as line breaks
const lineBreaks = [...src.matchAll(/\n|\r\n?/g)]
.map((m) => m.index);
const locationToSnapshot: Record<number, string> = {};
for (const updateRequest of updateRequests) {
const { lineNumber, columnNumber, actualSnapshot } = updateRequest;
// Since lineNumber is 1-indexed, subtract 1 to convert to 0-indexed.
// Then fetch the line break before this line, which is the (n-1)th break,
// or 0 if this is the top line (index 0).
const location = (lineBreaks[lineNumber - 2] ?? 0) + columnNumber;
locationToSnapshot[location] = actualSnapshot;
}
return {
// Fetching all functions lets us support createAssertInlineSnapshot
"CallExpression"(node: Deno.lint.CallExpression) {
const snapshot = locationToSnapshot[node.range[0]];
const argument = node.arguments[1];
if (snapshot === undefined || argument === undefined) return;
context.report({
node,
message: "",
fix(fixer) {
return fixer.replaceText(argument, snapshot);
},
});
},
};
},
},
},
};
}
const updateRequests: SnapshotUpdateRequest[] = [];
function updateSnapshots() {
if (updateRequests.length === 0) return;
if (!LINT_SUPPORTED) {
throw new Error(
"Deno versions before 2.2.0 do not support Deno.lint, which is required to update inline snapshots",
);
}
const pathsToUpdate = Map.groupBy(updateRequests, (r) => r.fileName);
for (const [path, updateRequests] of pathsToUpdate) {
const snapshotsUpdated = updateRequests.length;
const file = Deno.readTextFileSync(path);
const pluginRunResults = Deno.lint.runPlugin(
makeSnapshotUpdater(updateRequests),
"dummy.ts",
file,
);
const fixes = pluginRunResults.flatMap((v) => v.fix ?? []);
if (fixes.length !== snapshotsUpdated) {
throw new Error(
`assertInlineSnapshot expected to update ${snapshotsUpdated} ${
snapshotsUpdated === 1 ? "snapshot" : "snapshots"
} in ${path} but generated ${fixes.length}`,
);
}
// Apply the fixes in order
fixes.sort((a, b) => a.range[0] - b.range[0]);
let output = "";
let lastIndex = 0;
for (const fix of fixes) {
output += file.slice(lastIndex, fix.range[0]);
output += "`" + escapeStringForJs(fix.text ?? "") + "`";
lastIndex = fix.range[1];
}
output += file.slice(lastIndex);
Deno.writeTextFileSync(path, output);
}
const shouldFormat = !Deno.args.some((arg) => arg === "--no-format");
if (shouldFormat) {
const command = new Deno.Command(Deno.execPath(), {
args: ["fmt", ...pathsToUpdate.keys()],
});
const { stderr, success } = command.outputSync();
if (!success) {
throw new Error(
`assertInlineSnapshot errored while formatting ${path}:\n${
new TextDecoder().decode(stderr)
}`,
);
}
}
// deno-lint-ignore no-console
console.log(
`%c\n > ${updateRequests.length} ${
updateRequests.length === 1 ? "snapshot" : "snapshots"
} updated.`,
"color: green; font-weight: bold;",
);
}
globalThis.addEventListener("unload", () => {
updateSnapshots();
});
/**
* Make an assertion that `actual` matches `expectedSnapshot`. If they do not match,
* then throw.
*
* Type parameter can be specified to ensure values under comparison have the same type.
*
* @experimental **UNSTABLE**: New API, yet to be vetted.
*
* @example Usage
* ```ts no-assert
* import { assertInlineSnapshot } from "@std/testing/unstable-snapshot";
*
* Deno.test("snapshot", () => {
* assertInlineSnapshot<number>(2, `2`);
* });
* ```
* @typeParam T The type of the snapshot
* @param actual The actual value to compare
* @param expectedSnapshot The expected snapshot, or \`CREATE\` to create
* @param options The options
*/
export function assertInlineSnapshot<T>(
actual: T,
expectedSnapshot: string,
options?: InlineSnapshotOptions<T>,
): void;
/**
* Make an assertion that `actual` matches `expectedSnapshot`. If they do not match,
* then throw.
*
* Type parameter can be specified to ensure values under comparison have the same type.
*
* @experimental **UNSTABLE**: New API, yet to be vetted.
*
* @example Usage
* ```ts no-assert
* import { assertInlineSnapshot } from "@std/testing/unstable-snapshot";
*
* Deno.test("snapshot", () => {
* assertInlineSnapshot<number>(2, `2`);
* });
* ```
* @typeParam T The type of the snapshot
* @param actual The actual value to compare
* @param expectedSnapshot The expected snapshot, or \`CREATE\` to create
* @param message The optional assertion message
*/
export function assertInlineSnapshot<T>(
actual: T,
expectedSnapshot: string,
message?: string,
): void;
export function assertInlineSnapshot(
actual: unknown,
expectedSnapshot: string,
msgOrOpts?: string | InlineSnapshotOptions<unknown>,
): void {
const options = getOptions(msgOrOpts);
const serializer = options.serializer ?? serialize;
const actualSnapshot = serializer(actual);
// TODO(WWRS): dedent expectedSnapshot to allow snapshots to look nicer
if (equal(actualSnapshot, expectedSnapshot)) {
return;
}
if (getIsUpdate(options)) {
const origPrepareStackTrace = (Error as V8Error).prepareStackTrace;
try {
const stackCatcher = { stack: null as SnapshotUpdateRequest | null };
(Error as V8Error).prepareStackTrace = (
_err: Error,
stack: CallSite[],
): SnapshotUpdateRequest | null => {
const callerStackFrame = stack[0];
if (!callerStackFrame || callerStackFrame.isEval()) return null;
const fileName = callerStackFrame.getFileName();
const lineNumber = callerStackFrame.getLineNumber();
const columnNumber = callerStackFrame.getColumnNumber();
if (fileName === null || lineNumber === null || columnNumber === null) {
return null;
}
return {
fileName,
lineNumber,
columnNumber,
actualSnapshot,
};
};
// Capture the stack that comes after this function.
Error.captureStackTrace(stackCatcher, assertInlineSnapshot);
// Forcibly access the stack, and note it down
const request = stackCatcher.stack;
if (request !== null) {
updateRequests.push(request);
}
} finally {
(Error as V8Error).prepareStackTrace = origPrepareStackTrace;
}
} else {
throw new AssertionError(
getSnapshotNotMatchMessage(actualSnapshot, expectedSnapshot, options),
);
}
}
/**
* Create {@linkcode assertInlineSnapshot} function with the given options.
*
* The specified option becomes the default for returned {@linkcode assertInlineSnapshot}
*
* @experimental **UNSTABLE**: New API, yet to be vetted.
*
* @example Usage
* ```ts no-assert
* import { createAssertInlineSnapshot } from "@std/testing/unstable-snapshot";
*
* const assertInlineSnapshot = createAssertInlineSnapshot({
* serializer: JSON.stringify,
* });
*
* Deno.test("a snapshot test case", () => {
* assertInlineSnapshot(
* { foo: "Hello", bar: undefined },
* `{"foo":"Hello"}`
* );
* })
* ```
*
* @typeParam T The type of the snapshot
* @param options The options
* @param baseAssertSnapshot {@linkcode assertInlineSnapshot} function implementation. Default to the original {@linkcode assertInlineSnapshot}
* @returns {@linkcode assertInlineSnapshot} function with the given default options.
*/
export function createAssertInlineSnapshot<T>(
options: InlineSnapshotOptions<T>,
baseAssertSnapshot: typeof assertInlineSnapshot = assertInlineSnapshot,
): typeof assertInlineSnapshot {
return function (
actual: T,
expectedSnapshot: string,
messageOrOptions?: string | InlineSnapshotOptions<T>,
) {
const mergedOptions: InlineSnapshotOptions<T> = {
...options,
...(typeof messageOrOptions === "string"
? { msg: messageOrOptions }
: messageOrOptions),
};
baseAssertSnapshot(actual, expectedSnapshot, mergedOptions);
};
}
|