Sub topic 10
Focusing, Skipping, and Filtering Tests
A test suite grows quickly. When one test fails, you usually want to run that test alone, set a few others aside, and get back to the full run once the fix is done. Vitest gives you two ways to do this. You can edit the test code with modifiers such as .only, .skip, and .todo, or you can leave the code alone and narrow the run with command-line filters.
This chapter assumes you can write tests with describe, test, and it, run Vitest in watch mode and single-run mode, and use basic expect matchers.
Two Ways to Narrow a Run
Modifiers live in your test files. They change what runs every time the file executes, so they can end up committed by mistake. CLI filters live in the command you type. They affect only the current run and leave no trace in the code.
| Approach | Where it lives | Scope | Risk |
|---|---|---|---|
| `.only` | Test file | Tests within that file | Committed by accident, silently hides tests |
| `.skip`, `.skipIf`, `.runIf` | Test file | One test or one suite | Skipped tests become permanent |
| `.todo` | Test file | A placeholder with no body | Low; shows up in the report |
| File filter (`vitest math`) | Command line | Which files run | None |
| `-t` name filter | Command line | Which tests run, by name | None |
| Watch-mode keys (`p`, `t`, `f`) | Interactive session | Current session | None |
A good rule of thumb is to use CLI filters while debugging and modifiers only when the code itself should record the decision, such as a test that cannot run on Windows.
Focusing with .only
Add .only to a test, an it, or a describe. Vitest then runs only the focused tests in that file and reports the rest as skipped.
// cart.test.js
import { describe, test, expect } from 'vitest'
function total(items) {
return items.reduce((sum, item) => sum + item.price * item.qty, 0)
}
describe('total', () => {
test('returns 0 for an empty cart', () => {
expect(total([])).toBe(0)
})
test.only('multiplies price by quantity', () => {
expect(total([{ price: 5, qty: 3 }])).toBe(15)
})
test('adds several items', () => {
expect(total([{ price: 1, qty: 1 }, { price: 2, qty: 2 }])).toBe(5)
})
})
describe.only('total with discounts', () => {
test('ignores items with zero quantity', () => {
expect(total([{ price: 9, qty: 0 }])).toBe(0)
})
})In this file, two tests run: multiplies price by quantity and every test inside total with discounts. The other two are skipped.
Gotcha: .only is scoped to a file
.only affects only the file it appears in. Other test files still run in full. If you have 40 test files and put .only in one of them, you still get output from the other 39. To truly run one test, combine .only with a file filter:
npx vitest run cartGotcha: .only fails in CI
A forgotten .only is dangerous. The suite still passes, but most of it never ran. Vitest guards against this with the allowOnly option. It defaults to true locally and to false when the CI environment variable is set. With allowOnly set to false, a file containing .only makes the run fail instead of passing quietly.
CI=true npx vitest runSkipping Tests
Static skips with .skip
.skip marks a test or suite as skipped. The test body is never executed, but the test still appears in the report as skipped, so it stays visible.
import { describe, test, expect } from 'vitest'
describe.skip('legacy exporter', () => {
test('writes CSV', () => {
expect(true).toBe(false)
})
})
test.skip('flaky network check', () => {
expect(1).toBe(2)
})Neither failing assertion runs, so the file passes with two skipped tests.
Conditional skips with skipIf and runIf
When the reason for skipping is a fact about the environment, state that fact in code. test.skipIf(condition) skips when the condition is truthy. test.runIf(condition) runs only when it is truthy. Both also exist on describe.
import { describe, test, expect } from 'vitest'
import path from 'node:path'
const isWindows = process.platform === 'win32'
test.skipIf(isWindows)('joins POSIX paths with a slash', () => {
expect(path.join('a', 'b')).toBe('a/b')
})
describe.runIf(process.env.INTEGRATION === '1')('integration', () => {
test('talks to a real service', () => {
expect(process.env.INTEGRATION).toBe('1')
})
})The condition is evaluated when the file is collected, before any beforeAll or beforeEach hook runs. Values that are only set inside a hook are not available yet.
Skipping from inside a test
Sometimes you only know at run time that a test cannot proceed. The test context passed to each test function has a skip method:
import { test, expect } from 'vitest'
test('reads optional fixture', (context) => {
const fixture = process.env.FIXTURE_PATH
if (!fixture) {
context.skip()
}
expect(fixture.length).toBeGreaterThan(0)
})context.skip() stops the test and marks it skipped. Code after the call does not run, which is why fixture.length never throws here.
Placeholders with .todo
test.todo records a test you plan to write. It takes a name and no function. Vitest lists it as a todo in the report, separate from skipped tests.
import { describe, test } from 'vitest'
describe('refunds', () => {
test.todo('refunds the full amount within 30 days')
test.todo('refuses refunds for gift cards')
})Use .todo rather than an empty test. An empty test passes, which suggests a behavior is covered when it is not. A todo is honest about the gap.
Filtering from the Command Line
Filtering by file
Any positional argument to vitest is a filter on test file paths. Vitest runs every test file whose path contains that text.
npx vitest run cart # cart.test.js, shopping-cart.test.js, cart/utils.test.js
npx vitest run src/api/ # every test file under src/api/
npx vitest run cart auth # files matching either filterThe match is a plain substring, not a glob, so cart also matches discart.test.js if you have one.
Filtering by test name with -t
-t (long form --testNamePattern) takes a regular expression and runs only tests whose full name matches it. The full name is the names of all enclosing describe blocks plus the test name, joined by spaces.
npx vitest run -t "multiplies price"
npx vitest run -t "^total with discounts"
npx vitest run cart -t "empty cart"For the earlier file, the full names include total returns 0 for an empty cart and total with discounts ignores items with zero quantity. The pattern ^total with matches only the second suite, while total matches everything.
Vitest still loads and collects every matching file, but it reports tests that do not match the pattern as skipped. Combining a file filter with -t avoids loading files you don't need.
Filtering by line number
In Vitest 3 and later, you can point at a test by its line number. The file name must be specific enough to identify one file:
npx vitest run src/cart.test.js:11This is handy when your editor or a failure message gives you a line number.
Running tests related to changes
Two options choose tests from the module graph instead of from names:
npx vitest run --changed # tests affected by uncommitted git changes
npx vitest related src/cart.js # tests that import src/cart.js, directly or notBoth rely on Vitest tracing imports. Code loaded in a way Vitest cannot see, such as a path built at run time, is not traced.
When a filter matches nothing
If no test files match, Vitest prints "No test files found" and exits with code 1. That is usually what you want, because a typo in a filter should not pass. Scripts that run Vitest on a list that may be empty, such as pre-commit hooks, can add --passWithNoTests.
Filtering in Watch Mode
In watch mode (npx vitest), single keys change the filter without restarting:
| Key | Action |
|---|---|
| `p` | Filter by file name |
| `t` | Filter by test name pattern |
| `f` | Rerun only failed tests |
| `a` | Rerun all tests |
| `h` | Show all shortcuts |
A typical debugging loop is to press p, type the file name, press t, type part of the test name, then edit code until it passes. Press a before you finish to make sure nothing else broke.
Common Mistakes
- Committing
.only. The suite looks green while most tests are skipped. KeepallowOnlyat its CI default and add a lint rule if your team uses ESLint with a Vitest plugin. - Permanent
.skip. A skipped test rots. Add a comment with the reason and an issue link, or delete the test. - Expecting
-tto match only the test name. It matches the full name includingdescribetitles, so^addswill not matchtotal adds several items. - Unescaped regex characters in
-t. A name liketotal (with tax)needs escaping:-t "total \(with tax\)". - Using
skipIfwith values set in hooks. The condition is evaluated during collection, before hooks run.
Exercise
A file orders.test.js contains describe('orders', ...) with tests named creates an order and cancels an order. A second file users.test.js has a test marked test.only. You run npx vitest run. Which tests run? Then write a command that runs only cancels an order, without editing any file.
Show answer
.only is scoped to its file, so both tests in orders.test.js run, plus only the focused test in users.test.js. If CI is set, the run fails because allowOnly defaults to false there. To run only the cancel test, use npx vitest run orders -t "orders cancels an order". The pattern cancels would also work because it is a substring regex.
Exercise
You have a test that needs the DATABASE_URL environment variable, and you want it reported as skipped, not failed, when the variable is missing. Write it two ways: once with a modifier evaluated at collection time, and once by skipping from inside the test.
Show answer
Modifier: test.skipIf(!process.env.DATABASE_URL)('connects', () => { expect(process.env.DATABASE_URL).toMatch(/^postgres/) }). Inside the test: test('connects', (context) => { if (!process.env.DATABASE_URL) context.skip(); expect(process.env.DATABASE_URL).toMatch(/^postgres/) }). Use the first form when the condition is known up front. Use the second when it depends on something computed during the test.
Exercise
A teammate replaces three unwritten tests with test('handles refunds', () => {}). Why is test.todo better here?
Show answer
An empty test body passes, so the report counts refund handling as tested when nothing is checked. test.todo('handles refunds') takes no body and appears as a todo in the report, which makes the missing coverage visible.