vitest icon indicating copy to clipboard operation
vitest copied to clipboard

Ability to detect --update flag during testing of snapshots

Open Josh-a-e opened this issue 2 months ago • 2 comments

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

Josh-a-e avatar Nov 28 '24 12:11 Josh-a-e