From e76e07b4a0d016f234abe5dcdaceb1a4d0734f48 Mon Sep 17 00:00:00 2001 From: cjihrig Date: Wed, 1 Jan 2025 13:19:05 -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(). --- doc/api/test.md | 37 ++++++ lib/internal/test_runner/snapshot.js | 115 +++++++++++++----- lib/internal/test_runner/test.js | 1 + .../test-runner/snapshots/file-snapshots.js | 21 ++++ test/parallel/test-runner-assert.js | 2 +- .../test-runner-snapshot-file-tests.js | 82 +++++++++++++ 6 files changed, 229 insertions(+), 29 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 7deac4fae1efdf..774c20162b6a81 100644 --- a/doc/api/test.md +++ b/doc/api/test.md @@ -3255,6 +3255,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])`