Skip to content
Back to skills

Vitest Knowledge Patch

ASecurity

Vitest

  • 25 stars
  • 0 votes
  • 0 copies
  • 6 views
  • Added May 27, 2026
developmenttypescriptnodeexpresstestinggitapidatabase

Works with

  • cli
  • api

Security analysis

A100/100

Pro scans all 7 files and shows the line behind each finding

Scanned December 1, 2026

npx -y skills add Nevaberry/nevaberry-plugins --skill vitest-knowledge-patch --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of Vitest Knowledge Patch?

Add the live security badge to your README. It updates with every re-scan.

Security grade badge for Vitest Knowledge Patch
[![Security: A — Skills Directory](https://www.skillsdirectory.com/api/skills/nevaberry-vitest-knowledge-patch/badge)](https://www.skillsdirectory.com/skills/nevaberry-vitest-knowledge-patch)

More formats (shields.io, HTML) on the badges page. Keep it an A: scan every change in CI with Pro.

Download with Pro
SKILL.md
---
name: vitest-knowledge-patch
description: Vitest
version: "5.1.2"
license: MIT
metadata:
  author: Nevaberry
---


# Vitest Knowledge Patch

Load this skill when migrating Vitest projects or working with Browser Mode,
test APIs, project configuration, coverage, reporters, and experimental features.
Use the topic references for examples and version-specific behavior.

| Reference | Topics |
| --- | --- |
| [Browser Mode](references/browser-mode.md) | Providers, instances, locators, screenshots, traces, browser mocks, rendering |
| [Experimental Features](references/experimental-features.md) | Native execution, module caches, telemetry, import budgets, change providers |
| [Migration and Configuration](references/migration-and-configuration.md) | Requirements, imports, config discovery, scheduling, CLI selection, watching |
| [Projects and Coverage](references/projects-and-coverage.md) | Project discovery and inheritance, coverage providers, exclusions, thresholds, HTML |
| [Reporters and Integrations](references/reporters-and-integrations.md) | Reporter output, annotations, UI, diagnostics, programmatic APIs, VS Code |
| [Test APIs](references/test-apis.md) | Assertions, fixtures, hooks, mocks, timers, snapshots, retries, tags |

## Breaking changes and deprecations

### Runtime, imports, and configuration

- Vitest 5 requires Node.js 22+ and Vite 6.4+.
- Vitest 5 removes `@vitest/browser-webdriverio`. Migrate headless browser
  projects to the Playwright provider.
- Vitest bundles runner and assertion code into the main package and stops
  publishing `@vitest/runner`. Import test and assertion APIs from `vitest`.
- Config discovery searches the current root without walking up parents.
  From a child package, pass a shared config explicitly:
  `vitest run --config ../vitest.config.ts`.
- Inline projects inherit root config and share its Vite server by default.
  Remove redundant `extends: true` and check for duplicated inherited plugins.
- Replace sequential test and suite options with `{ concurrent: false }`.
  This also works for a top-level test when `test.sequence.concurrent` is enabled.

### Mocks, assertions, and snapshots

- Mock call history clears before each test. Set `test.clearMocks: false` if
  tests depend on calls recorded during suite setup or earlier tests.
- Put `vi.mock` and `vi.hoisted` at module scope. Vitest 5 errors on hoistable
  calls inside tests, hooks, or other nested scopes.
- Migrate deprecated `toBeCalled*` spy aliases to `toHaveBeenCalled*`.
- Unawaited asynchronous assertions fail the test. An `expect.poll` timeout
  also fails when its callback remains pending at the deadline.
- Vitest 5 rejects snapshot assertions in `test.fails`. As of 5.0.3, a
  `test.fails` test that fails as expected skips retries.
- Redirect mock targets must be in Vite's filesystem allowlist. Move an
  outside target into an allowed directory or add its directory to `server.fs.allow`.

### Browser matching and worker limits

- `test.browser.locators.exact` is enabled by default. For substring matching,
  use an explicit option such as `page.getByText('Save', { exact: false })`.
- Use `toHaveTextContent('Saved')` for exact text and
  `toMatchTextContent('Saved')` for a substring.
- Browser locators are structured objects. Update integrations that treat
  locators as selector strings.
- Browser instances run as workers and count toward `maxWorkers`. Upgrading
  can reduce simultaneous browsers, including with default settings.

### Cache, reports, and coverage migration

- Move `fsModuleCache` from `test.experimental` to `test.fsModuleCache`.
  Vitest 5.0.4 enables it by default; set `test.fsModuleCache` to `false` to disable it.
- Replace the removed `basic` reporter with `default` and `summary: false`.
- Root-only `test.attachmentsDir` defaults to `.vitest/attachments/`, including
  Browser Mode failure screenshots. Blob reports and `--merge-reports` default
  to `.vitest/blob/`; JSON, JUnit, and HTML output defaults under `.vitest/`.
- Use distinct `test.coverage.reportsDirectory` paths for concurrent runs:
  Vitest fails if they target the same report directory.

## Selecting, listing, and rerunning tests

`vitest list` parses test files statically by default. Use
`vitest list --no-static-parse` for tests generated at runtime. As of 5.0.1,
the list command exits with status 1 if collection fails.

- Use `vitest run --last-failed` for tests that failed in the previous run.
- Use `vitest run --since-last-run` for tests affected by changes since that run.
- `vitest run --changed` tracks project files and mocks, prints affected and
  total test counts, runs selected tests' setup files, and handles deleted imports.
- As of 5.1.2, `vitest related` rejects `--changed`.
- Git-based change detection and source-location filter errors fail the run.
- Use `vitest run --repeats=2` for repeats and `vitest run -p unit` to select a project.
- Suite and test names are joined with ` > ` for `-t` matching:
  `vitest run -t 'checkout > pays by card'`.

For files outside the import graph, use `test.watchTriggerPatterns`.
Its `testsToRun` callback receives the changed file and the regex match.

## Tags and annotations

Declare tags under `test.tags` with a `name`, optional `description`, and shared
test options such as `timeout` or `retry`. Tests can inherit several tags' options.

```ts
test('queries the database', { tags: ['db', 'flaky'] }, async () => { /* assertions */ })
```

Filter with `vitest run --tags-filter='db and !flaky'`. Expressions support
`and`/`&&`, `or`/`||`, `not`/`!`, parentheses, and `*` wildcards.
Repeated `--tags-filter` flags combine with AND; use `tag:` in the UI filter field.

Unknown tags throw unless `test.strictTags: false`. Conflicting tag options
resolve in specified order, with unprioritized tags merging first and lower numeric
`priority` values taking precedence. Explicit test options override tag defaults.
Use `vitest --list-tags` or `vitest --list-tags=json` to inspect configured tags.

Use the test context's `annotate(message, type)` or
`annotate(message, { body: file })`. Await completion when later work depends on it;
otherwise Vitest waits for pending annotations before the test finishes.
The CLI prints failed tests' annotations; `verbose` also shows passing tests' annotations.
UI and HTML annotations appear at call sites in the test file and omit calls from other files.
JUnit and TAP formats omit attachments. Custom reporters receive `onTestAnnotate`.

## Fixtures, hooks, and cancellation

Use `[fixture, { scope: 'file' }]` in `test.extend` for one initialization per
file that uses the fixture, or `{ scope: 'worker' }` for one per worker.
Disable isolation to reuse a worker-scoped fixture across test files.

`test.extend(name, value)` adds a constant; `test.extend(name, options, factory)`
infers a scoped fixture from the factory's return value. Omit options for test scope.
Callbacks registered with `onCleanup` run when the fixture's scope ends.

Register `beforeEach` and `afterEach` on the extended test for typed fixtures.
`beforeAll`, `afterAll`, and `aroundAll` can access file- and worker-scoped fixtures;
this context replaces the former undocumented `Suite` argument to the first two hooks.
An `aroundEach` or `aroundAll` hook must invoke its first argument to run the test or suite.

Failed fixture setup is not cached, so a later request can attempt setup again.
A hook's registered cleanup still runs if a later hook fails.
`maxConcurrency` covers per-test setup and teardown as well as the test.

Pass the test context's `signal` to cancellable work. Timeout, `--bail` after a
failure, and Ctrl+C abort it. Cancelling a run aborts all running tests' signals,
including concurrent tests. In 5.1.1 each attempt gets a fresh signal, and local
`expect.assertions()` and `expect.hasAssertions()` counts restart on each retry.

## Browser testing and visual diagnostics

Configure multiple setups with `test.browser.instances`, with `provider` on
`test.browser` and instance-specific `launch`, `setupFiles`, and `provide` settings.
`--browser` requires a `test.browser` config block. Global setup runs once for
a browser project with multiple instances.

Use `page.frameLocator()` with an iframe locator under Playwright, and
`page.elementLocator()` to scope locators to an external renderer's DOM root.
`toBeInViewport({ ratio })` requires a minimum visible fraction; omit `ratio`
to test intersection. Locators expose `length` for match-count assertions.

`toMatchScreenshot` captures a whole `page` or a locator's element. A missing
baseline is created on the first run, which fails for review. Review and commit
the PNG, then use `vitest --update` after intentional changes.
Configure references with `test.browser.expect.toMatchScreenshot.screenshotDirectory`.
Playwright screenshots default to `screenshotOptions.animations: 'disabled'` and
accept locators in `screenshotOptions.mask` to cover dynamic content.

Set `test.browser.trace` to `'on'`, `'on-first-retry'`, `'on-all-retries'`, or
`'retain-on-failure'`; CLI capture uses `vitest --browser.trace=on`.
Use `page.mark(name)` or `locator.mark(name)` for markers and
`page.mark(name, callback)` for action groups. `vi.defineHelper()` attributes trace
entries to the helper's call site and trims helper frames from assertion failures.
The stable Browser Mode trace viewer defaults to failed tests and captures ARIA snapshots.
The `pointer` API and Node trace timelines are experimental.

Browser module mocks use an import map; as of 5.1.2 they support assets and
runtime-computed `import()` specifiers. Setup-file mocks register before the test
file imports. Browser actions and `expect.element()` advance an enabled fake clock.

## Mocks, timers, and snapshot updates

With explicit resource management support, `using mock = vi.fn()` restores the
mock on block exit; `vi.spyOn` supports the same disposal. A disposable from
`vi.doMock` unregisters that mock for subsequent imports when its scope ends.
Use `vi.when()` for conditional mock results and `thenResolve(value)` with a resolved
value for promise-returning mocks. Put linked packages' manual mocks in root `__mocks__`.

After `vi.useFakeTimers()`, `vi.setTimerTickMode('nextTimer')` advances automatically
to scheduled timers; `'manual'` returns to explicit advancement. Fake timers also
cover imports from `node:timers` and `node:timers/promises`.
Use `vi.useFakeTimers({ toNotFake: ['Date'] })` to leave a specified API real.
`vi.setSystemTime()` controls `Temporal` without first enabling fake timers and
accepts `Temporal.Instant` and `Temporal.ZonedDateTime` directly.

Use `vitest --update=new` for missing snapshots, `vitest --update=all` to refresh
snapshots and remove obsolete ones, or `test.update: 'none'` to disable writes.
Interactive review allows inspection of individual failed snapshots before updates.
As of 5.1.2, snapshots newly created by a failed retry attempt are removed.

## Projects, coverage, and experimental execution

Keep `test.coverage`, `test.reporters`, and `test.resolveSnapshotPath` in the root
config; `defineProject()` type-checks supported project options. Project names must
be unique. `test.sequence.groupOrder` runs groups in ascending numeric order;
projects with the same value run together. Projects inherit the root `watch` setting.

The default `v8` coverage provider needs profiler access; V8-based environments
such as Cloudflare Workers lack it. Use `'istanbul'` for instrumentation coverage
where V8 profiling is unavailable. V8 coverage also tracks `node:child_process`
and `node:worker_threads` contexts.

`vitest run --coverage.enabled --coverage.changed` runs all tests and limits coverage
output to changed files. `test.coverage.thresholds.perFile` accepts an object;
an `autoUpdate` callback also receives the previous threshold.

Set `test.experimental.viteModuleRunner: false` for native imports of tests,
sources, and setup files, bypassing Vite transforms, plugins, aliases, and
`import.meta.env`. Use `v8` coverage. Node.js 22.18+ or 23.6+ strips TypeScript
types; native-loader `vi.mock` and `vi.hoisted` support requires Node.js 22.15+.
See the experimental reference for pool support, loader constraints, cache keys,
OpenTelemetry setup, and import-duration budgets.

Files in this skill

  • SKILL.md6.8 KB
  • references/browser-mode.md6.2 KB
  • references/matchers-mocking.md3.4 KB
  • references/migration-v4.md5.2 KB
  • references/projects-config.md3.9 KB
  • references/test-fixtures-hooks.md3.9 KB
  • references/test-organization.md4.5 KB

Attribution

Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.

View all in development →

Comments

Loading comments…

Newsletter

Get the weekly list of safe new skills, and the ones we pulled.