Run only the tests your change touches with Vitest --changed Vitest 5.1.0's `--changed` and `related` flags run only the test files that depend on edited source files, cutting a six-file shop project's full run of 6 test files and 10 tests down to 4 test files and 7 tests after a single edit to `price.ts`, as demonstrated by Flavio on Node.js 22. The author recommends the flags for local runs, pre-commit hooks, CI, and coding agents that rerun tests after every edit, since a large suite can take minutes per run. With a clean working tree, `vitest --run --changed` reports "No changed files found, exiting with code 0. Run only the tests your change touches with Vitest --changed By Flavio https://flaviocopes.com/about/ Tagged: AI https://flaviocopes.com/tags/ai/ , JavaScript https://flaviocopes.com/tags/js/ 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 https://flaviocopes.com/vitest/ . 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 : js 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 : js 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: 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: 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: js 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 : 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: js 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: python 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: js export async function greet lang: string : Promise