vitest
vitest copied to clipboard
Ability to detect --update flag during testing of snapshots
Clear and concise description of the problem
I am using .toMatchFileSnapshot()
(the single snapshot file was getting out of hand), however, I would like to be able to make sure any unused snapshots are getting cleaned up. (e.g. if a previous test using a snapshot was deleted / has had its name changed, this will result in a file in source control needing to be cleaned up since there's a one to one mapping between these snapshot files and tests)
Suggested solution
Add an updatingSnapshots
boolean to the test context.
Alternative
Pass in an additional environment variable
$ UPDATE_SNAPSHOTS=true npx vitest run 'snapshots.test' --update
...
afterAll(() => {
// ⬇️ It would be better if this came from the context - at the moment, as far as
// I can see, there's no way to detect if the --update flag was used
const updateSnapshots = Boolean(process.env.UPDATE_SNAPSHOTS);
const unusedSnapshotFileNames = fs
.readdirSync(resolve(SNAPSHOTS_DIRECTORY_NAME))
.filter((file) => usedSnapshotFileNames.includes(file) === false);
if (updateSnapshots) {
for (const file of unusedSnapshotFileNames) {
fs.unlinkSync(resolve(SNAPSHOTS_DIRECTORY_NAME, file));
}
console.info(
`🚮 ${unusedSnapshotFileNames.length} unused snapshots deleted`,
);
} else {
throw new Error(
`Unused snapshots found: ${unusedSnapshotFileNames.join(', ')}`,
);
}
});
...
Additional context
No response
Validations
- [X] Follow our Code of Conduct
- [X] Read the Contributing Guidelines.
- [X] Read the docs.
- [X] Check that there isn't already an issue that request the same feature to avoid creating a duplicate.