From b91c14b58ecdf060897e1c9c4abcb6dca7a1f122 Mon Sep 17 00:00:00 2001 From: Carlos Espa Date: Wed, 12 Feb 2025 20:13:55 +0100 Subject: [PATCH] test: allow especial characters in snapshot keys Fixes: https://github.com/nodejs/node/issues/56836 --- lib/internal/test_runner/snapshot.js | 9 ++++++++- test/parallel/test-runner-snapshot-tests.js | 2 ++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/lib/internal/test_runner/snapshot.js b/lib/internal/test_runner/snapshot.js index 642e84b2f13b33..42d3f856dc73d5 100644 --- a/lib/internal/test_runner/snapshot.js +++ b/lib/internal/test_runner/snapshot.js @@ -77,7 +77,7 @@ class SnapshotFile { } setSnapshot(id, value) { - this.snapshots[templateEscape(id)] = value; + this.snapshots[keyEscape(id)] = value; } nextId(name) { @@ -290,6 +290,13 @@ function validateFunctionArray(fns, name) { } } +function keyEscape(str) { + let result = JSONStringify(str, null, 2).slice(1, -1); + result = StringPrototypeReplaceAll(result, '`', '\\`'); + result = StringPrototypeReplaceAll(result, '${', '\\${'); + return result; +} + function templateEscape(str) { let result = String(str); result = StringPrototypeReplaceAll(result, '\\', '\\\\'); diff --git a/test/parallel/test-runner-snapshot-tests.js b/test/parallel/test-runner-snapshot-tests.js index 011b1321e1e8c3..5bab589afd30b8 100644 --- a/test/parallel/test-runner-snapshot-tests.js +++ b/test/parallel/test-runner-snapshot-tests.js @@ -158,6 +158,8 @@ suite('SnapshotManager', () => { file.setSnapshot('foo`${x}` 1', 'test'); t.assert.strictEqual(file.getSnapshot('foo\\`\\${x}\\` 1'), 'test'); + file.setSnapshot('\r 1', 'test'); + t.assert.strictEqual(file.getSnapshot('\\r 1'), 'test'); }); test('throws if snapshot file cannot be resolved', (t) => {