From 00a1943858cb662e44570c426636b958916e1320 Mon Sep 17 00:00:00 2001 From: Colin Ihrig Date: Thu, 9 Jan 2025 16:12:17 -0500 Subject: [PATCH] test_runner: add t.assert.fileSnapshot() This commit adds a t.assert.fileSnapshot() API to the test runner. This is similar to how snapshot tests work in core, as well as userland options such as toMatchFileSnapshot(). PR-URL: https://github.com/nodejs/node/pull/56459 Reviewed-By: Matteo Collina Reviewed-By: James M Snell Reviewed-By: Chemi Atlow Reviewed-By: Moshe Atlow --- doc/api/test.md | 37 ++++++ lib/internal/test_runner/snapshot.js | 115 +++++++++++++----- lib/internal/test_runner/test.js | 10 +- .../test-runner/snapshots/file-snapshots.js | 21 ++++ test/parallel/test-runner-assert.js | 2 +- .../test-runner-snapshot-file-tests.js | 82 +++++++++++++ 6 files changed, 235 insertions(+), 32 deletions(-) create mode 100644 test/fixtures/test-runner/snapshots/file-snapshots.js create mode 100644 test/parallel/test-runner-snapshot-file-tests.js diff --git a/doc/api/test.md b/doc/api/test.md index 32fb857709fe50..3b0c040d852334 100644 --- a/doc/api/test.md +++ b/doc/api/test.md @@ -3278,6 +3278,43 @@ test('test', (t) => { }); ``` +#### `context.assert.fileSnapshot(value, path[, options])` + + + +* `value` {any} A value to serialize to a string. If Node.js was started with + the [`--test-update-snapshots`][] flag, the serialized value is written to + `path`. Otherwise, the serialized value is compared to the contents of the + existing snapshot file. +* `path` {string} The file where the serialized `value` is written. +* `options` {Object} Optional configuration options. The following properties + are supported: + * `serializers` {Array} An array of synchronous functions used to serialize + `value` into a string. `value` is passed as the only argument to the first + serializer function. The return value of each serializer is passed as input + to the next serializer. Once all serializers have run, the resulting value + is coerced to a string. **Default:** If no serializers are provided, the + test runner's default serializers are used. + +This function serializes `value` and writes it to the file specified by `path`. + +```js +test('snapshot test with default serialization', (t) => { + t.assert.fileSnapshot({ value1: 1, value2: 2 }, './snapshots/snapshot.json'); +}); +``` + +This function differs from `context.assert.snapshot()` in the following ways: + +* The snapshot file path is explicitly provided by the user. +* Each snapshot file is limited to a single snapshot value. +* No additional escaping is performed by the test runner. + +These differences allow snapshot files to better support features such as syntax +highlighting. + #### `context.assert.snapshot(value[, options])`