MCPcopy Create free account
hub / github.com/denoland/std / updateSnapshots

Function updateSnapshots

testing/unstable_snapshot.ts:95–161  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

93const updateRequests: SnapshotUpdateRequest[] = [];
94
95function updateSnapshots() {
96 if (updateRequests.length === 0) return;
97
98 if (!LINT_SUPPORTED) {
99 throw new Error(
100 "Deno versions before 2.2.0 do not support Deno.lint, which is required to update inline snapshots",
101 );
102 }
103
104 const pathsToUpdate = Map.groupBy(updateRequests, (r) => r.fileName);
105
106 for (const [path, updateRequests] of pathsToUpdate) {
107 const snapshotsUpdated = updateRequests.length;
108
109 const file = Deno.readTextFileSync(path);
110 const pluginRunResults = Deno.lint.runPlugin(
111 makeSnapshotUpdater(updateRequests),
112 "dummy.ts",
113 file,
114 );
115
116 const fixes = pluginRunResults.flatMap((v) => v.fix ?? []);
117 if (fixes.length !== snapshotsUpdated) {
118 throw new Error(
119 `assertInlineSnapshot expected to update ${snapshotsUpdated} ${
120 snapshotsUpdated === 1 ? "snapshot" : "snapshots"
121 } in ${path} but generated ${fixes.length}`,
122 );
123 }
124
125 // Apply the fixes in order
126 fixes.sort((a, b) => a.range[0] - b.range[0]);
127 let output = "";
128 let lastIndex = 0;
129 for (const fix of fixes) {
130 output += file.slice(lastIndex, fix.range[0]);
131 output += "`" + escapeStringForJs(fix.text ?? "") + "`";
132 lastIndex = fix.range[1];
133 }
134 output += file.slice(lastIndex);
135
136 Deno.writeTextFileSync(path, output);
137 }
138
139 const shouldFormat = !Deno.args.some((arg) => arg === "--no-format");
140 if (shouldFormat) {
141 const command = new Deno.Command(Deno.execPath(), {
142 args: ["fmt", ...pathsToUpdate.keys()],
143 });
144 const { stderr, success } = command.outputSync();
145 if (!success) {
146 throw new Error(
147 `assertInlineSnapshot errored while formatting ${path}:\n${
148 new TextDecoder().decode(stderr)
149 }`,
150 );
151 }
152 }

Callers 1

Calls 5

escapeStringForJsFunction · 0.90
groupByMethod · 0.80
keysMethod · 0.80
makeSnapshotUpdaterFunction · 0.70
sliceMethod · 0.45

Tested by

no test coverage detected