vitest-dev / vitest-dev/vitest

Ability to detect --update flag during testing of snapshots

Open
#6,979 4 comments 3 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

p2-nice-to-have
Dominant language
TypeScript
Stars
17.1k
Forks
2k
Avg merge
1d 22h
Merged PRs (30d)
94

Description

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

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the test-context documentation and the .toMatchFileSnapshot() behavior, then trace how vitest run ... --update is represented during a test. Use the snapshot test command from the issue to verify that the test context exposes whether snapshot updating is enabled, and confirm the value differs between normal and --update runs.

Written by the indexing model from the issue text.

Assessment

Tech stack
typescript
Domain
testing-qa
Issue type
Feature
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.