Run only the tests your change touches with Vitest --changed

By

Tagged: AI, JavaScript

Use vitest --changed and vitest related to run only the test files affected by your edit, locally, in a pre-commit hook, in CI, and from a coding agent.

A test suite with a few hundred files takes seconds to run, while a big one can take minutes.

That’s fine once before a merge, but a coding agent runs the tests after every edit. If it reruns everything each time, most of those minutes go to tests that can’t possibly have changed.

Vitest can work out which test files depend on the files you touched and run only those. That’s what vitest --changed and vitest related do.

If you’re new to Vitest, start with Vitest: an introduction. Here I assume you already have a project with Vitest installed and a passing test suite.

I ran everything below on Vitest 5.1.0 and Node.js 22.

The example project

We’ll use a small shop library with six modules and one test file for each. Here’s the layout:

shop/
  package.json
  src/
    cart.ts       cart.test.ts
    discount.ts   discount.test.ts
    format.ts     format.test.ts
    price.ts      price.test.ts
    receipt.ts    receipt.test.ts
    shipping.ts   shipping.test.ts

price.ts converts euros to cents and adds VAT:

export function toCents(amount: number): number {
  return Math.round(amount * 100)
}

export function applyTax(cents: number, rate: number): number {
  return Math.round(cents * (1 + rate))
}

The other modules build on it. discount.ts imports toCents, cart.ts imports price.ts and discount.ts, and receipt.ts imports cart.ts and format.ts:

import { cartTotal, type Item } from './cart'
import { formatPrice } from './format'

export function receiptLine(items: Item[], coupon = ''): string {
  return `Total: ${formatPrice(cartTotal(items, coupon))}`
}

shipping.ts and format.ts don’t import anything.

Each test file imports only the module next to it. Here’s cart.test.ts:

import { expect, test } from 'vitest'
import { cartTotal } from './cart'

const items = [
  { name: 'Notebook', price: 12.5, quantity: 2 },
  { name: 'Pen', price: 1.2, quantity: 3 },
]

test('sums items and adds VAT', () => {
  expect(cartTotal(items)).toBe(3489)
})

test('applies the coupon before VAT', () => {
  expect(cartTotal(items, 'WELCOME5')).toBe(2879)
})

The project is a git repository with everything committed. Later on we’ll add a few more test files for the edge cases, so some outputs further down count 10 or 11 test files.

A full run executes all six files:

npx vitest --run
 RUN  v5.1.0 /Users/flavio/dev/shop

 ✓ src/discount.test.ts (2 tests) 2ms
 ✓ src/shipping.test.ts (2 tests) 2ms
 ✓ src/cart.test.ts (2 tests) 2ms
 ✓ src/price.test.ts (2 tests) 2ms
 ✓ src/format.test.ts (1 test) 11ms
 ✓ src/receipt.test.ts (1 test) 11ms

 Test Files  6 passed (6)
      Tests  10 passed (10)
   Start at  15:07:56
   Duration  114ms (import 33%, tests 30%, transform 24%, worker 12%)

Run the tests for your uncommitted changes

With a clean working tree, --changed has nothing to do:

npx vitest --run --changed
 RUN  v5.1.0 /Users/flavio/dev/shop

No changed files found, exiting with code 0

Let’s edit price.ts and guard toCents against floating point rounding:

export function toCents(amount: number): number {
  return Math.round(amount * 100 + Number.EPSILON)
}

Now git diff --stat shows one file:

 src/price.ts | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

And --changed runs four test files out of six:

 RUN  v5.1.0 /Users/flavio/dev/shop

 ✓ src/discount.test.ts (2 tests) 2ms
 ✓ src/price.test.ts (2 tests) 2ms
 ✓ src/cart.test.ts (2 tests) 2ms
 ✓ src/receipt.test.ts (1 test) 11ms

 Test Files  4 passed (4)
   Affected  4 of 6 test files (related to 1 changed file)
      Tests  7 passed (7)
   Start at  15:08:01
   Duration  111ms (import 42%, tests 35%, worker 17%, transform 5%, environment 1%)

Look at the Affected line in the output. It tells you how many files Vitest picked and why.

format.test.ts and shipping.test.ts were skipped. Neither of them reaches price.ts through its imports, so an edit to price.ts can’t change their result.

Notice the --run flag too. Without it, Vitest starts in watch mode when you run it in an interactive terminal.

Adding --run makes Vitest run once and exit. That’s what we want in a script, a hook, CI, or a coding agent.

How Vitest finds the changed files

Without an argument, --changed asks git for every file that differs from HEAD. Under the hood it runs two commands:

git diff --cached --name-only
git ls-files --other --modified --exclude-standard

The first one lists staged files. The second one lists modified files that aren’t staged yet and new files git doesn’t track, skipping anything in .gitignore.

So a brand new test file counts as changed, even before you git add it. If we add an untracked src/tax.test.ts that imports price.ts, --changed runs just that file:

 ✓ src/tax.test.ts (1 test) 1ms

 Test Files  1 passed (1)
   Affected  1 of 11 test files (related to 1 changed file)

How Vitest picks the test files

Knowing the changed files is half the job. Vitest also needs to know which test files depend on them.

It gets that from the module graph. Vitest runs on Vite, and Vite transforms every test file before running it.

While transforming a file, Vite records every import it finds, then does the same for each imported module. The result is a graph with a node per file and an edge per import.

To decide what to run, Vitest walks that graph starting from each test file. If the walk reaches a changed file, the test file runs, otherwise Vitest skips it.

Here’s the graph of the shop project, and what happens when price.ts changes:

1/2The shop module graph
The shop module graphEach test file imports its module. cart.ts imports price.ts and discount.ts, discount.ts imports price.ts, and receipt.ts imports cart.ts and format.ts. shipping.ts and format.ts import nothing.price.test.tsprice.tsdiscount.test.tsdiscount.tscart.test.tscart.tsreceipt.test.tsreceipt.tsformat.test.tsformat.tsshipping.test.tsshipping.ts
2/2price.ts changes
price.ts changesprice.ts is edited. price.test.ts, discount.test.ts, cart.test.ts and receipt.test.ts reach it through their imports and run. format.test.ts and shipping.test.ts never reach it and are skipped.price.test.tsrunsprice.tschangeddiscount.test.tsrunsdiscount.tscart.test.tsrunscart.tsreceipt.test.tsrunsreceipt.tsformat.test.tsskippedformat.tsshipping.test.tsskippedshipping.ts

receipt.test.ts never mentions prices. It still runs because it imports receipt.ts, which imports cart.ts, which imports price.ts.

That indirect path is what makes the module graph so useful. A plain grep for price in the test files would miss it.

You can also inspect the same graph in the Vitest UI. Install @vitest/ui, run npx vitest --ui, pick a test file, and open its Module Graph tab:

The Vitest UI with src/receipt.test.ts selected and the Module Graph tab open. The graph shows receipt.test.ts connected to receipt.ts, which connects to cart.ts and format.ts, and cart.ts connects to price.ts and discount.ts.

Preview the selection without running anything

vitest list accepts --changed too. Add --filesOnly and it prints the test files it would run, then exits:

npx vitest list --changed --filesOnly
src/cart.test.ts
src/discount.test.ts
src/price.test.ts
src/receipt.test.ts

I like using this as a quick sanity check to see what Vitest thinks depends on a file before trusting the selection.

Compare against a commit or a branch

Uncommitted changes are only part of the story. After you commit, the working tree is clean again and plain --changed finds nothing:

git commit -am "Guard toCents against float rounding"
npx vitest --run --changed
No changed files found, exiting with code 0

We can pass a git revision to compare against instead. HEAD~1 means “the previous commit”:

npx vitest --run --changed HEAD~1
 RUN  v5.1.0 /Users/flavio/dev/shop

 ✓ src/cart.test.ts (2 tests) 2ms
 ✓ src/discount.test.ts (2 tests) 2ms
 ✓ src/price.test.ts (2 tests) 2ms
 ✓ src/receipt.test.ts (1 test) 11ms

 Test Files  4 passed (4)
   Affected  4 of 6 test files (related to 1 changed file)
      Tests  7 passed (7)
   Start at  15:08:18
   Duration  110ms (import 42%, tests 33%, worker 21%, transform 4%, environment 1%)

The argument can be anything git understands as a revision: HEAD~3, a commit hash, a tag, a local branch like main, or a remote branch like origin/main.

With a revision, Vitest runs this command and adds the staged, unstaged and untracked files on top:

git diff --name-only HEAD~1...HEAD

Those three dots matter. A...HEAD means “what changed on my side since the point where I branched off A”.

Any commits that landed on A after you branched are left out.

Let’s see that on a feature branch. We create free-shipping, commit a change to shipping.ts and its test, and leave an uncommitted edit in format.ts that switches the locale to it-IT:

git switch -c free-shipping
git commit -am "Free shipping for light parcels in Italy"
npx vitest --run --changed origin/main
 RUN  v5.1.0 /Users/flavio/dev/shop

 ✓ src/shipping.test.ts (2 tests) 2ms
 ❯ src/format.test.ts (1 test | 1 failed) 13ms
   × formats cents as euros 13ms
 ❯ src/receipt.test.ts (1 test | 1 failed) 13ms
   × prints the formatted total 12ms

⎯⎯⎯⎯⎯⎯⎯ Failed Tests 2 ⎯⎯⎯⎯⎯⎯⎯

 FAIL  src/format.test.ts > formats cents as euros
AssertionError: expected '19,99 €' to be '€19.99' // Object.is equality

Expected: "€19.99"
Received: "19,99 €"

Three files changed (shipping.ts, shipping.test.ts and format.ts), and three test files ran. The locale change broke receipt.test.ts too, through its import of format.ts:

 Test Files  2 failed | 1 passed (3)
   Affected  3 of 6 test files (related to 3 changed files)
      Tests  2 failed | 2 passed (4)

Now we revert format.ts, while a teammate pushes a change to discount.ts on main. After a git fetch, the history looks like this:

* cbbaefe Bump welcome coupon
| * 1e3746f Free shipping for light parcels in Italy
|/
* bb4c41c Guard toCents against float rounding
* 85ee44e Shop utilities with tests

A two-dot diff against origin/main includes the teammate’s file:

git diff --name-only origin/main
src/discount.ts
src/shipping.test.ts
src/shipping.ts

Vitest uses the three-dot form, so it only sees our branch’s changes:

 ✓ src/shipping.test.ts (2 tests) 2ms
 Test Files  1 passed (1)
   Affected  1 of 6 test files (related to 2 changed files)

That’s what you want on a pull request. You test what the branch changes, not what other people merged in the meantime.

If the revision doesn’t exist, Vitest prints git’s error and exits with code 1:

Command `git diff --name-only -z HEAD~1...HEAD` failed:
fatal: ambiguous argument 'HEAD~1...HEAD': unknown revision or path not in the working tree.

That one came from a repository with a single commit, where HEAD~1 doesn’t exist yet.

What triggers a full run

Some files affect every test, and the import graph can’t show it. When one of them changes, Vitest runs the whole suite.

The forceRerunTriggers option lists them as globs. The default is:

['**/package.json', '**/{vitest,vite}.config.*']

Edit package.json and every file runs, with no Affected line in the summary:

npm pkg set description="Shop utilities"
npx vitest --run --changed
 Test Files  6 passed (6)
      Tests  10 passed (10)

Vitest also runs everything when one of these changes:

  • the config file, or any file the config imports
  • a file listed in globalSetup
  • a file listed in setupFiles, or anything those files import

To check the global setup case, let’s add a global-setup.ts file and point globalSetup at it. One edit to that file selects every test:

 Test Files  10 passed (10)
   Affected  10 of 10 test files (related to 1 changed file)

You can add your own triggers too. Say your tests read fixtures from a fixtures folder.

Add that pattern to vitest.config.ts, and keep the defaults in the list because setting forceRerunTriggers replaces them:

import { defineConfig } from 'vitest/config'

export default defineConfig({
  test: {
    forceRerunTriggers: ['**/package.json', '**/{vitest,vite}.config.*', '**/fixtures/**'],
  },
})

With that config, adding a new fixtures/rates.json makes --changed run all the tests.

Here’s the full decision flow Vitest follows when you pass --changed:

How --changed decides what to runVitest collects changed files from git. If none changed it exits. If a changed file matches forceRerunTriggers, the config, global setup or setup files, it runs every test. Otherwise it walks the module graph and runs only the test files that reach a changed file.noyesyesnoyesnoCollect changedfiles from gitAny changed files?Exit with code 0MatchesforceRerunTriggers,config, globalSetupor setupFiles?Run every test fileWalk the modulegraphfrom each test fileAny test filereachesa changed file?Run those test filesNo affected testfiles found

Snapshots and mocks

Two cases get special handling, and both work the way you’d hope.

A snapshot file isn’t imported by anything, but Vitest knows which test owns it. Edit src/__snapshots__/receipt-snapshot.test.ts.snap by hand, and --changed still picks the test that writes it:

src/receipt-snapshot.test.ts

Mocks are taken into account too. This test replaces format.ts with a mock:

import { expect, test, vi } from 'vitest'
import { receiptLine } from './receipt'

vi.mock('./format', () => ({ formatPrice: () => '€0.00' }))

test('uses the mocked formatter', () => {
  expect(receiptLine([])).toBe('Total: €0.00')
})

It never loads the real format.ts, so an edit there can’t change its result. vitest list --changed --filesOnly leaves it out after a change to format.ts:

src/format.test.ts
src/receipt-snapshot.test.ts
src/receipt.test.ts

It still runs when cart.ts or price.ts change, because those are real imports.

What the module graph can’t see

The graph only knows about imports Vite can find in the source. Anything a test depends on in another way is invisible, and a change there selects nothing.

Files read with fs

This module reads a JSON file in two ways:

import { readFileSync } from 'node:fs'
import rates from '../data/rates.json'

export function importedRate(country: string): number {
  return rates[country as keyof typeof rates]
}

export function fsRate(country: string): number {
  const fromDisk = JSON.parse(readFileSync('data/rates-fs.json', 'utf8'))
  return fromDisk[country]
}

Changing data/rates.json selects src/rates.test.ts, because it’s an import. Changing data/rates-fs.json selects nothing:

 RUN  v5.1.0 /Users/flavio/dev/shop

No affected test files found, exiting with code 0

The test would fail if the file broke, but --changed never runs it. The same goes for templates, SQL files, .env values, or anything else read at runtime.

To avoid missing those changes, add those folders to forceRerunTriggers, or switch to an import when the file is JSON.

Dynamic imports with a computed path

A template literal inside import() is fine. Vite expands it into the files that can match:

const { greeting } = await import(`./locales/${lang}.ts`)

An edit to src/locales/it.ts selected src/greet.test.ts.

A path built in a variable is different:

export async function greet(lang: string): Promise<string> {
  const file = './locales/' + lang + '.ts'
  const { greeting } = await import(/* @vite-ignore */ file)
  return greeting
}

Vite can’t know where that goes, so the same edit to it.ts selected no test at all.

Vitest 5.1 has an experimental way around this. With --experimental.recordDependencies, every run records the modules each test file loaded, and --changed uses those records instead of the static graph.

Any test file without a record always runs. We can try it in two steps:

npx vitest --run --experimental.recordDependencies
npx vitest --run --changed --experimental.recordDependencies

After one recorded run, the edit to it.ts selected the right test:

 ✓ src/greet.test.ts (1 test) 3ms
   Affected  1 of 10 test files (related to 1 changed file)

Keep in mind that it records modules, not file reads, so the readFileSync case is still invisible.

Everything outside the repository

--changed only compares files tracked in git. Ignored files are out of reach too, since git ls-files --exclude-standard skips them.

It also can’t see changes outside the repository, like:

  • a dependency updated without touching package.json
  • a changed environment variable
  • a database schema change
  • an external API your tests call

So I treat --changed as the fast feedback loop, and still run the full suite before a merge.

When no test is affected

When there’s nothing to run, --changed and vitest related both exit with code 0.

Vitest 5.1 turns on --passWithNoTests by default for both commands, so editing a README won’t fail your hook.

A plain filter that matches nothing behaves differently:

npx vitest --run src/nothing
echo $?
1

If you want --changed to fail when it finds no affected tests, turn the option off:

npx vitest --run --changed --no-passWithNoTests
No affected test files found, exiting with code 1

How much time it saves

The shop project is too small to benchmark. So I generated a second project with 400 modules and 400 test files, where ten of the modules import a shared money.ts.

Then I edited money.ts and ran both commands three times.

Here’s a full run:

 Test Files  400 passed (400)
      Tests  400 passed (400)
   Duration  4.57s (transform 50%, import 32%, worker 11%, tests 8%)

And here’s the --changed run:

 ✓ src/product-400.test.ts (1 test) 2ms
 ✓ src/product-200.test.ts (1 test) 2ms
 ✓ src/product-360.test.ts (1 test) 2ms
 ✓ src/product-120.test.ts (1 test) 2ms
 ✓ src/product-80.test.ts (1 test) 1ms
 ✓ src/product-240.test.ts (1 test) 2ms
 ✓ src/product-40.test.ts (1 test) 2ms
 ✓ src/product-160.test.ts (1 test) 2ms
 ✓ src/product-280.test.ts (1 test) 2ms
 ✓ src/product-320.test.ts (1 test) 1ms

 Test Files  10 passed (10)
   Affected  10 of 400 test files (related to 1 changed file)
      Tests  10 passed (10)

Here’s the wall clock time of each run, measured with time on an Apple Silicon Mac:

Runnpx vitest --runnpx vitest --run --changed
14.96s0.73s
24.99s0.67s
35.35s0.70s

These tests do almost nothing, so most of those 5 seconds go to Vitest transforming and loading 400 files. Real tests that hit a database or render components stretch the full run much more than the --changed one.

Even on this tiny benchmark, an agent that edits a file and tests it 30 times in a session saves 4 seconds on every run. On a slow suite, it saves minutes per run.

Watch mode does this already

If you keep npx vitest open in a terminal, you get the same idea for free. Watch mode runs everything once, then reruns only the tests affected by each file you save.

Here’s watch mode on the shop project after saving a change to discount.ts:

 PASS  Waiting for file changes...
       press h to show help, press q to quit
 RERUN  src/discount.ts

 ✓ src/cart.test.ts (2 tests) 2ms
 ✓ src/discount.test.ts (2 tests) 2ms
 ✓ src/checkout.test.ts (1 test) 1ms
 ✓ src/receipt.test.ts (1 test) 11ms
 ✓ src/receipt-snapshot.test.ts (1 test) 11ms

 Test Files  5 passed (5)
      Tests  7 passed (7)
   Start at  15:11:42
   Duration  87ms

The difference is where the list of changes comes from. Watch mode reacts to file saves while it runs, and it has no idea what happened before it started.

--changed asks git, runs once, and exits. That makes it the right tool for hooks, CI, and agent sessions, where nothing stays open between runs.

vitest related takes a list of source files and runs the tests that depend on them. It uses the same module graph as --changed, but you give it the files instead of asking git:

npx vitest related src/format.ts --run
 RUN  v5.1.0 /Users/flavio/dev/shop

 ✓ src/format.test.ts (1 test) 11ms
 ✓ src/receipt.test.ts (1 test) 11ms

 Test Files  2 passed (2)
   Affected  2 of 6 test files (related to src/format.ts)
      Tests  2 passed (2)
   Start at  15:08:07
   Duration  103ms (tests 61%, import 26%, worker 10%, transform 3%)

You can pass several files:

npx vitest related src/format.ts src/shipping.ts --run
 Test Files  3 passed (3)
   Affected  3 of 6 test files (related to 2 files)

That shape fits lint-staged, which runs a command with the staged files appended as arguments. Install it:

npm install -D lint-staged

Then add the config to package.json:

{
  "lint-staged": {
    "*.ts": "vitest related --run"
  }
}

And call it from the git pre-commit hook in .git/hooks/pre-commit (or from Husky, if you use it):

#!/bin/sh
npx lint-staged

Make the hook executable with chmod +x .git/hooks/pre-commit.

Now let’s rename the WELCOME5 coupon in discount.ts, stage it, and try to commit. Two tests still expected the old code, so the hook stopped the commit:

✖ vitest related --run:

 RUN  v5.1.0 /Users/flavio/dev/shop

 ❯ src/discount.test.ts (2 tests | 1 failed) 5ms
   × WELCOME5 is worth 5 euros 3ms
 ❯ src/cart.test.ts (2 tests | 1 failed) 5ms
   × applies the coupon before VAT 3ms

 Test Files  2 failed | 3 passed (5)
   Affected  5 of 10 test files (related to src/discount.ts)
      Tests  2 failed | 5 passed (7)

cart.test.ts failed because cart.ts imports discount.ts. The hook caught it even though the cart code didn’t change.

related fits a hook better than --changed because lint-staged hands over only the staged files. Using --changed would also pull in unstaged edits and untracked files that aren’t part of the commit.

If you want your pre-commit hook to stay fast, stick with related. My post on git hooks for AI engineering covers what else you can run there.

Run only the affected tests on pull requests in CI

On a pull request, compare against the base branch. In GitHub Actions the base branch name is in github.base_ref:

name: Tests

on:
  pull_request:

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7
        with:
          fetch-depth: 0
      - uses: actions/setup-node@v7
        with:
          node-version: 22
      - run: npm ci
      - run: npx vitest --run --changed origin/${{ github.base_ref }}

fetch-depth: 0 is the key line here. By default actions/checkout makes a shallow clone with a single commit.

Without the git history, git can’t find the point where the branch split from main, and the three-dot diff fails.

Here’s the same failure locally, with a shallow clone that also fetches main at depth 1:

git clone --depth 1 --branch free-shipping file:///Users/flavio/dev/origin.git ci
cd ci
git fetch --depth 1 origin main:refs/remotes/origin/main
npx vitest --run --changed origin/main
 RUN  v5.1.0 /Users/flavio/dev/ci

Command `git diff --name-only -z origin/main...HEAD` failed:
fatal: origin/main...HEAD: no merge base

The run exits with code 1, so at least the job fails loudly. With the full history the same command ran the one affected test:

 ✓ src/shipping.test.ts (2 tests) 2ms
 Test Files  1 passed (1)
   Affected  1 of 6 test files (related to 2 changed files)

I still keep a full run in the pipeline. My advice is to run --changed on every pull request push, and run the full suite on pushes to main and before a release.

That catches anything the module graph can’t see, like files read with fs.

Tell your coding agent to use it

A coding agent runs whatever test command it finds in the project. We should give it a better one.

Vitest already helps a little. It detects when it runs inside an agent by checking environment variables like CLAUDECODE, CURSOR_AGENT, and CODEX_THREAD_ID.

When it sees one, it turns off watch mode and switches to the minimal reporter, which prints only the failures and the summary. Choosing which test files to run is still up to us.

Add a few lines to your project’s AGENTS.md:

## Tests

- After editing code, run `npx vitest --run --changed`. It runs only the tests affected by your uncommitted changes.
- To check specific files, run `npx vitest related <files> --run`.
- Before saying a task is done, run the full suite once with `npx vitest --run`.
- If you change files read at runtime (anything in `data/` or `fixtures/`), run the full suite, since `--changed` can't see them.

Put the commands in package.json too, so humans and agents type the same thing:

{
  "scripts": {
    "test": "vitest --run",
    "test:changed": "vitest --run --changed",
    "test:branch": "vitest --run --changed origin/main"
  }
}

That leaves you with three commands: npm run test:changed after each edit, npm run test:branch before pushing, and npm test once at the end.

Want me to talk about your product? You can sponsor this site.

Related posts about ai: