Snapshot testing
Snapshot Testing is a powerful testing method used to capture and compare serialized representations of component output. When your UI or data structures change, snapshot testing helps you detect these changes promptly.
Basic usage
Rstest provides a simple snapshot testing API that allows you to easily create and use snapshots.
Creating snapshots
Inline snapshots
For simple values, you can use inline snapshots:
File snapshots
By default, Rstest stores all snapshots for the current test in .snap files with the format exports['testName index'] = ${snapshotContent}.
You can also use the toMatchFileSnapshot method to store snapshots in separate files, which makes them more readable.
Configuration options
Rstest provides various snapshot-related configuration options that allow you to customize snapshot behavior.
- update: Whether to update snapshots
- snapshotFormat: Snapshot formatting options
- resolveSnapshotPath: Custom snapshot file path resolution function
Updating snapshots
When test runs encounter snapshot mismatches, Rstest will mark the test as failed and output difference information.
If these changes are expected, you can update snapshots using the command line argument -u or the configuration option update.
Serialization output
Rstest supports adding custom serialization tools for snapshot testing via the addSnapshotSerializer method to handle specific types of data structures.
This is especially useful when your snapshots contain local paths, sensitive data, or other non-serializable objects.
Using path-serializer can convert local paths to paths relative to the project root, which is very useful in cross-platform testing.
Snapshot output path
Snapshot files are saved with the .snap extension by default, in the __snapshots__ folder in the same directory as the test file.
You can customize snapshot file paths through the resolveSnapshotPath configuration option.
Best practices
Keep snapshots concise
Snapshots should be readable and easy to understand, avoiding containing too much irrelevant information:
Use descriptive snapshot names
When using multiple snapshots, provide descriptive names for each snapshot:
Regularly review snapshots
As code evolves, snapshots may become outdated. Regularly reviewing and updating snapshots is necessary:
- Update relevant snapshots when refactoring UI
- Delete snapshots that are no longer needed
- Reasonably use inline snapshots for small-scale testing