{"slug": "run-only-the-tests-your-change-touches-with-vitest-changed", "title": "Run only the tests your change touches with Vitest --changed", "summary": "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.", "body_md": "# Run only the tests your change touches with Vitest --changed\n\nBy [Flavio](https://flaviocopes.com/about/)\n\nTagged: [AI](https://flaviocopes.com/tags/ai/), [JavaScript](https://flaviocopes.com/tags/js/)\n\nUse 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.\n\nA test suite with a few hundred files takes seconds to run, while a big one can take minutes.\n\nThat’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.\n\nVitest 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.\n\nIf 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.\n\nI ran everything below on Vitest 5.1.0 and Node.js 22.\n\n## The example project\n\nWe’ll use a small shop library with six modules and one test file for each. Here’s the layout:\n\n```\nshop/\n  package.json\n  src/\n    cart.ts       cart.test.ts\n    discount.ts   discount.test.ts\n    format.ts     format.test.ts\n    price.ts      price.test.ts\n    receipt.ts    receipt.test.ts\n    shipping.ts   shipping.test.ts\n```\n\n`price.ts` converts euros to cents and adds VAT:\n\n```\nexport function toCents(amount: number): number {\n  return Math.round(amount * 100)\n}\n\nexport function applyTax(cents: number, rate: number): number {\n  return Math.round(cents * (1 + rate))\n}\n```\n\nThe 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`:\n\n``` js\nimport { cartTotal, type Item } from './cart'\nimport { formatPrice } from './format'\n\nexport function receiptLine(items: Item[], coupon = ''): string {\n  return `Total: ${formatPrice(cartTotal(items, coupon))}`\n}\n```\n\n`shipping.ts` and `format.ts` don’t import anything.\n\nEach test file imports only the module next to it. Here’s `cart.test.ts`:\n\n``` js\nimport { expect, test } from 'vitest'\nimport { cartTotal } from './cart'\n\nconst items = [\n  { name: 'Notebook', price: 12.5, quantity: 2 },\n  { name: 'Pen', price: 1.2, quantity: 3 },\n]\n\ntest('sums items and adds VAT', () => {\n  expect(cartTotal(items)).toBe(3489)\n})\n\ntest('applies the coupon before VAT', () => {\n  expect(cartTotal(items, 'WELCOME5')).toBe(2879)\n})\n```\n\nThe 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.\n\nA full run executes all six files:\n\n```\nnpx vitest --run\nRUN  v5.1.0 /Users/flavio/dev/shop\n\n ✓ src/discount.test.ts (2 tests) 2ms\n ✓ src/shipping.test.ts (2 tests) 2ms\n ✓ src/cart.test.ts (2 tests) 2ms\n ✓ src/price.test.ts (2 tests) 2ms\n ✓ src/format.test.ts (1 test) 11ms\n ✓ src/receipt.test.ts (1 test) 11ms\n\n Test Files  6 passed (6)\n      Tests  10 passed (10)\n   Start at  15:07:56\n   Duration  114ms (import 33%, tests 30%, transform 24%, worker 12%)\n```\n\n## Run the tests for your uncommitted changes\n\nWith a clean working tree, `--changed` has nothing to do:\n\n```\nnpx vitest --run --changed\nRUN  v5.1.0 /Users/flavio/dev/shop\n\nNo changed files found, exiting with code 0\n```\n\nLet’s edit `price.ts` and guard `toCents` against floating point rounding:\n\n```\nexport function toCents(amount: number): number {\n  return Math.round(amount * 100 + Number.EPSILON)\n}\n```\n\nNow `git diff --stat` shows one file:\n\n```\n src/price.ts | 2 +-\n 1 file changed, 1 insertion(+), 1 deletion(-)\n```\n\nAnd `--changed` runs four test files out of six:\n\n```\n RUN  v5.1.0 /Users/flavio/dev/shop\n\n ✓ src/discount.test.ts (2 tests) 2ms\n ✓ src/price.test.ts (2 tests) 2ms\n ✓ src/cart.test.ts (2 tests) 2ms\n ✓ src/receipt.test.ts (1 test) 11ms\n\n Test Files  4 passed (4)\n   Affected  4 of 6 test files (related to 1 changed file)\n      Tests  7 passed (7)\n   Start at  15:08:01\n   Duration  111ms (import 42%, tests 35%, worker 17%, transform 5%, environment 1%)\n```\n\nLook at the `Affected` line in the output. It tells you how many files Vitest picked and why.\n\n`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.\n\nNotice the `--run` flag too. Without it, Vitest starts in watch mode when you run it in an interactive terminal.\n\nAdding `--run` makes Vitest run once and exit. That’s what we want in a script, a hook, CI, or a coding agent.\n\n## How Vitest finds the changed files\n\nWithout an argument, `--changed` asks git for every file that differs from `HEAD`. Under the hood it runs two commands:\n\n```\ngit diff --cached --name-only\ngit ls-files --other --modified --exclude-standard\n```\n\nThe 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`.\n\nSo 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:\n\n```\n ✓ src/tax.test.ts (1 test) 1ms\n\n Test Files  1 passed (1)\n   Affected  1 of 11 test files (related to 1 changed file)\n```\n\n## How Vitest picks the test files\n\nKnowing the changed files is half the job. Vitest also needs to know which test files depend on them.\n\nIt gets that from the **module graph**. Vitest runs on Vite, and Vite transforms every test file before running it.\n\nWhile 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.\n\nTo 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.\n\nHere’s the graph of the shop project, and what happens when `price.ts` changes:\n\n`receipt.test.ts` never mentions prices. It still runs because it imports `receipt.ts`, which imports `cart.ts`, which imports `price.ts`.\n\nThat indirect path is what makes the module graph so useful. A plain grep for `price` in the test files would miss it.\n\nYou 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:\n\n### Preview the selection without running anything\n\n`vitest list` accepts `--changed` too. Add `--filesOnly` and it prints the test files it would run, then exits:\n\n```\nnpx vitest list --changed --filesOnly\nsrc/cart.test.ts\nsrc/discount.test.ts\nsrc/price.test.ts\nsrc/receipt.test.ts\n```\n\nI like using this as a quick sanity check to see what Vitest thinks depends on a file before trusting the selection.\n\n## Compare against a commit or a branch\n\nUncommitted changes are only part of the story. After you commit, the working tree is clean again and plain `--changed` finds nothing:\n\n```\ngit commit -am \"Guard toCents against float rounding\"\nnpx vitest --run --changed\nNo changed files found, exiting with code 0\n```\n\nWe can pass a git revision to compare against instead. `HEAD~1` means “the previous commit”:\n\n```\nnpx vitest --run --changed HEAD~1\nRUN  v5.1.0 /Users/flavio/dev/shop\n\n ✓ src/cart.test.ts (2 tests) 2ms\n ✓ src/discount.test.ts (2 tests) 2ms\n ✓ src/price.test.ts (2 tests) 2ms\n ✓ src/receipt.test.ts (1 test) 11ms\n\n Test Files  4 passed (4)\n   Affected  4 of 6 test files (related to 1 changed file)\n      Tests  7 passed (7)\n   Start at  15:08:18\n   Duration  110ms (import 42%, tests 33%, worker 21%, transform 4%, environment 1%)\n```\n\nThe 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`.\n\nWith a revision, Vitest runs this command and adds the staged, unstaged and untracked files on top:\n\n```\ngit diff --name-only HEAD~1...HEAD\n```\n\nThose three dots matter. `A...HEAD` means “what changed on my side since the point where I branched off `A`”.\n\nAny commits that landed on `A` after you branched are left out.\n\nLet’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`:\n\n```\ngit switch -c free-shipping\ngit commit -am \"Free shipping for light parcels in Italy\"\nnpx vitest --run --changed origin/main\nRUN  v5.1.0 /Users/flavio/dev/shop\n\n ✓ src/shipping.test.ts (2 tests) 2ms\n ❯ src/format.test.ts (1 test | 1 failed) 13ms\n   × formats cents as euros 13ms\n ❯ src/receipt.test.ts (1 test | 1 failed) 13ms\n   × prints the formatted total 12ms\n\n⎯⎯⎯⎯⎯⎯⎯ Failed Tests 2 ⎯⎯⎯⎯⎯⎯⎯\n\n FAIL  src/format.test.ts > formats cents as euros\nAssertionError: expected '19,99 €' to be '€19.99' // Object.is equality\n\nExpected: \"€19.99\"\nReceived: \"19,99 €\"\n```\n\nThree 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`:\n\n```\n Test Files  2 failed | 1 passed (3)\n   Affected  3 of 6 test files (related to 3 changed files)\n      Tests  2 failed | 2 passed (4)\n```\n\nNow we revert `format.ts`, while a teammate pushes a change to `discount.ts` on `main`. After a `git fetch`, the history looks like this:\n\n```\n* cbbaefe Bump welcome coupon\n| * 1e3746f Free shipping for light parcels in Italy\n|/\n* bb4c41c Guard toCents against float rounding\n* 85ee44e Shop utilities with tests\n```\n\nA two-dot diff against `origin/main` includes the teammate’s file:\n\n```\ngit diff --name-only origin/main\nsrc/discount.ts\nsrc/shipping.test.ts\nsrc/shipping.ts\n```\n\nVitest uses the three-dot form, so it only sees our branch’s changes:\n\n```\n ✓ src/shipping.test.ts (2 tests) 2ms\n Test Files  1 passed (1)\n   Affected  1 of 6 test files (related to 2 changed files)\n```\n\nThat’s what you want on a pull request. You test what the branch changes, not what other people merged in the meantime.\n\nIf the revision doesn’t exist, Vitest prints git’s error and exits with code 1:\n\n```\nCommand `git diff --name-only -z HEAD~1...HEAD` failed:\nfatal: ambiguous argument 'HEAD~1...HEAD': unknown revision or path not in the working tree.\n```\n\nThat one came from a repository with a single commit, where `HEAD~1` doesn’t exist yet.\n\n## What triggers a full run\n\nSome files affect every test, and the import graph can’t show it. When one of them changes, Vitest runs the whole suite.\n\nThe **`forceRerunTriggers`** option lists them as globs. The default is:\n\n```\n['**/package.json', '**/{vitest,vite}.config.*']\n```\n\nEdit `package.json` and every file runs, with no `Affected` line in the summary:\n\n```\nnpm pkg set description=\"Shop utilities\"\nnpx vitest --run --changed\nTest Files  6 passed (6)\n      Tests  10 passed (10)\n```\n\nVitest also runs everything when one of these changes:\n\n- the config file, or any file the config imports\n- a file listed in `globalSetup`\n- a file listed in `setupFiles` , or anything those files import\n\nTo 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:\n\n```\n Test Files  10 passed (10)\n   Affected  10 of 10 test files (related to 1 changed file)\n```\n\nYou can add your own triggers too. Say your tests read fixtures from a `fixtures` folder.\n\nAdd that pattern to `vitest.config.ts`, and keep the defaults in the list because setting `forceRerunTriggers` replaces them:\n\n``` js\nimport { defineConfig } from 'vitest/config'\n\nexport default defineConfig({\n  test: {\n    forceRerunTriggers: ['**/package.json', '**/{vitest,vite}.config.*', '**/fixtures/**'],\n  },\n})\n```\n\nWith that config, adding a new `fixtures/rates.json` makes `--changed` run all the tests.\n\nHere’s the full decision flow Vitest follows when you pass `--changed`:\n\n## Snapshots and mocks\n\nTwo cases get special handling, and both work the way you’d hope.\n\nA 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:\n\n```\nsrc/receipt-snapshot.test.ts\n```\n\nMocks are taken into account too. This test replaces `format.ts` with a mock:\n\n``` js\nimport { expect, test, vi } from 'vitest'\nimport { receiptLine } from './receipt'\n\nvi.mock('./format', () => ({ formatPrice: () => '€0.00' }))\n\ntest('uses the mocked formatter', () => {\n  expect(receiptLine([])).toBe('Total: €0.00')\n})\n```\n\nIt 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`:\n\n```\nsrc/format.test.ts\nsrc/receipt-snapshot.test.ts\nsrc/receipt.test.ts\n```\n\nIt still runs when `cart.ts` or `price.ts` change, because those are real imports.\n\n## What the module graph can’t see\n\nThe 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.\n\n### Files read with fs\n\nThis module reads a JSON file in two ways:\n\n``` python\nimport { readFileSync } from 'node:fs'\nimport rates from '../data/rates.json'\n\nexport function importedRate(country: string): number {\n  return rates[country as keyof typeof rates]\n}\n\nexport function fsRate(country: string): number {\n  const fromDisk = JSON.parse(readFileSync('data/rates-fs.json', 'utf8'))\n  return fromDisk[country]\n}\n```\n\nChanging `data/rates.json` selects `src/rates.test.ts`, because it’s an import. Changing `data/rates-fs.json` selects nothing:\n\n```\n RUN  v5.1.0 /Users/flavio/dev/shop\n\nNo affected test files found, exiting with code 0\n```\n\nThe 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.\n\nTo avoid missing those changes, add those folders to `forceRerunTriggers`, or switch to an `import` when the file is JSON.\n\n### Dynamic imports with a computed path\n\nA template literal inside `import()` is fine. Vite expands it into the files that can match:\n\n```\nconst { greeting } = await import(`./locales/${lang}.ts`)\n```\n\nAn edit to `src/locales/it.ts` selected `src/greet.test.ts`.\n\nA path built in a variable is different:\n\n``` js\nexport async function greet(lang: string): Promise<string> {\n  const file = './locales/' + lang + '.ts'\n  const { greeting } = await import(/* @vite-ignore */ file)\n  return greeting\n}\n```\n\nVite can’t know where that goes, so the same edit to `it.ts` selected no test at all.\n\nVitest 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.\n\nAny test file without a record always runs. We can try it in two steps:\n\n```\nnpx vitest --run --experimental.recordDependencies\nnpx vitest --run --changed --experimental.recordDependencies\n```\n\nAfter one recorded run, the edit to `it.ts` selected the right test:\n\n```\n ✓ src/greet.test.ts (1 test) 3ms\n   Affected  1 of 10 test files (related to 1 changed file)\n```\n\nKeep in mind that it records modules, not file reads, so the `readFileSync` case is still invisible.\n\n### Everything outside the repository\n\n`--changed` only compares files tracked in git. Ignored files are out of reach too, since `git ls-files --exclude-standard` skips them.\n\nIt also can’t see changes outside the repository, like:\n\n- a dependency updated without touching `package.json`\n- a changed environment variable\n- a database schema change\n- an external API your tests call\n\nSo I treat `--changed` as the fast feedback loop, and still run the full suite before a merge.\n\n## When no test is affected\n\nWhen there’s nothing to run, `--changed` and `vitest related` both exit with code 0.\n\nVitest 5.1 turns on `--passWithNoTests` by default for both commands, so editing a README won’t fail your hook.\n\nA plain filter that matches nothing behaves differently:\n\n```\nnpx vitest --run src/nothing\necho $?\n1\n```\n\nIf you want `--changed` to fail when it finds no affected tests, turn the option off:\n\n```\nnpx vitest --run --changed --no-passWithNoTests\nNo affected test files found, exiting with code 1\n```\n\n## How much time it saves\n\nThe 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`.\n\nThen I edited `money.ts` and ran both commands three times.\n\nHere’s a full run:\n\n```\n Test Files  400 passed (400)\n      Tests  400 passed (400)\n   Duration  4.57s (transform 50%, import 32%, worker 11%, tests 8%)\n```\n\nAnd here’s the `--changed` run:\n\n```\n ✓ src/product-400.test.ts (1 test) 2ms\n ✓ src/product-200.test.ts (1 test) 2ms\n ✓ src/product-360.test.ts (1 test) 2ms\n ✓ src/product-120.test.ts (1 test) 2ms\n ✓ src/product-80.test.ts (1 test) 1ms\n ✓ src/product-240.test.ts (1 test) 2ms\n ✓ src/product-40.test.ts (1 test) 2ms\n ✓ src/product-160.test.ts (1 test) 2ms\n ✓ src/product-280.test.ts (1 test) 2ms\n ✓ src/product-320.test.ts (1 test) 1ms\n\n Test Files  10 passed (10)\n   Affected  10 of 400 test files (related to 1 changed file)\n      Tests  10 passed (10)\n```\n\nHere’s the wall clock time of each run, measured with `time` on an Apple Silicon Mac:\n\n| Run | `npx vitest --run` | `npx vitest --run --changed` | \n|---|---|---|\n| 1 | 4.96s | 0.73s | \n| 2 | 4.99s | 0.67s | \n| 3 | 5.35s | 0.70s | \n\nThese 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.\n\nEven 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.\n\n## Watch mode does this already\n\nIf 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.\n\nHere’s watch mode on the shop project after saving a change to `discount.ts`:\n\n```\n PASS  Waiting for file changes...\n       press h to show help, press q to quit\n RERUN  src/discount.ts\n\n ✓ src/cart.test.ts (2 tests) 2ms\n ✓ src/discount.test.ts (2 tests) 2ms\n ✓ src/checkout.test.ts (1 test) 1ms\n ✓ src/receipt.test.ts (1 test) 11ms\n ✓ src/receipt-snapshot.test.ts (1 test) 11ms\n\n Test Files  5 passed (5)\n      Tests  7 passed (7)\n   Start at  15:11:42\n   Duration  87ms\n```\n\nThe 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.\n\n`--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.\n\n## Use vitest related in a pre-commit hook\n\n`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:\n\n```\nnpx vitest related src/format.ts --run\nRUN  v5.1.0 /Users/flavio/dev/shop\n\n ✓ src/format.test.ts (1 test) 11ms\n ✓ src/receipt.test.ts (1 test) 11ms\n\n Test Files  2 passed (2)\n   Affected  2 of 6 test files (related to src/format.ts)\n      Tests  2 passed (2)\n   Start at  15:08:07\n   Duration  103ms (tests 61%, import 26%, worker 10%, transform 3%)\n```\n\nYou can pass several files:\n\n```\nnpx vitest related src/format.ts src/shipping.ts --run\nTest Files  3 passed (3)\n   Affected  3 of 6 test files (related to 2 files)\n```\n\nThat shape fits [lint-staged](https://github.com/lint-staged/lint-staged), which runs a command with the staged files appended as arguments. Install it:\n\n```\nnpm install -D lint-staged\n```\n\nThen add the config to `package.json`:\n\n```\n{\n  \"lint-staged\": {\n    \"*.ts\": \"vitest related --run\"\n  }\n}\n```\n\nAnd call it from the git pre-commit hook in `.git/hooks/pre-commit` (or from Husky, if you use it):\n\n``` bash\n#!/bin/sh\nnpx lint-staged\n```\n\nMake the hook executable with `chmod +x .git/hooks/pre-commit`.\n\nNow 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:\n\n```\n✖ vitest related --run:\n\n RUN  v5.1.0 /Users/flavio/dev/shop\n\n ❯ src/discount.test.ts (2 tests | 1 failed) 5ms\n   × WELCOME5 is worth 5 euros 3ms\n ❯ src/cart.test.ts (2 tests | 1 failed) 5ms\n   × applies the coupon before VAT 3ms\n\n Test Files  2 failed | 3 passed (5)\n   Affected  5 of 10 test files (related to src/discount.ts)\n      Tests  2 failed | 5 passed (7)\n```\n\n`cart.test.ts` failed because `cart.ts` imports `discount.ts`. The hook caught it even though the cart code didn’t change.\n\n`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.\n\nIf you want your pre-commit hook to stay fast, stick with `related`. My post on [git hooks for AI engineering](https://flaviocopes.com/git-hooks/) covers what else you can run there.\n\n## Run only the affected tests on pull requests in CI\n\nOn a pull request, compare against the base branch. In [GitHub Actions](https://flaviocopes.com/github-actions-introduction/) the base branch name is in `github.base_ref`:\n\n```\nname: Tests\n\non:\n  pull_request:\n\njobs:\n  test:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions/checkout@v7\n        with:\n          fetch-depth: 0\n      - uses: actions/setup-node@v7\n        with:\n          node-version: 22\n      - run: npm ci\n      - run: npx vitest --run --changed origin/${{ github.base_ref }}\n```\n\n`fetch-depth: 0` is the key line here. By default `actions/checkout` makes a shallow clone with a single commit.\n\nWithout the git history, git can’t find the point where the branch split from `main`, and the three-dot diff fails.\n\nHere’s the same failure locally, with a shallow clone that also fetches `main` at depth 1:\n\n```\ngit clone --depth 1 --branch free-shipping file:///Users/flavio/dev/origin.git ci\ncd ci\ngit fetch --depth 1 origin main:refs/remotes/origin/main\nnpx vitest --run --changed origin/main\nRUN  v5.1.0 /Users/flavio/dev/ci\n\nCommand `git diff --name-only -z origin/main...HEAD` failed:\nfatal: origin/main...HEAD: no merge base\n```\n\nThe run exits with code 1, so at least the job fails loudly. With the full history the same command ran the one affected test:\n\n```\n ✓ src/shipping.test.ts (2 tests) 2ms\n Test Files  1 passed (1)\n   Affected  1 of 6 test files (related to 2 changed files)\n```\n\nI 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.\n\nThat catches anything the module graph can’t see, like files read with `fs`.\n\n## Tell your coding agent to use it\n\nA coding agent runs whatever test command it finds in the project. We should give it a better one.\n\nVitest already helps a little. It detects when it runs inside an agent by checking environment variables like `CLAUDECODE`, `CURSOR_AGENT`, and `CODEX_THREAD_ID`.\n\nWhen 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.\n\nAdd a few lines to your project’s [AGENTS.md](https://flaviocopes.com/agents-md/):\n\n```\n## Tests\n\n- After editing code, run `npx vitest --run --changed`. It runs only the tests affected by your uncommitted changes.\n- To check specific files, run `npx vitest related <files> --run`.\n- Before saying a task is done, run the full suite once with `npx vitest --run`.\n- If you change files read at runtime (anything in `data/` or `fixtures/`), run the full suite, since `--changed` can't see them.\n```\n\nPut the commands in `package.json` too, so humans and agents type the same thing:\n\n```\n{\n  \"scripts\": {\n    \"test\": \"vitest --run\",\n    \"test:changed\": \"vitest --run --changed\",\n    \"test:branch\": \"vitest --run --changed origin/main\"\n  }\n}\n```\n\nThat 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.\n\nWant me to talk about your product? You can [sponsor this site](https://flaviocopes.com/sponsor/).", "url": "https://wpnews.pro/news/run-only-the-tests-your-change-touches-with-vitest-changed", "canonical_source": "https://flaviocopes.com/vitest-changed/", "published_at": "2026-12-02 14:00:00+00:00", "updated_at": "2026-12-02 14:48:19.591582+00:00", "lang": "en", "topics": ["developer-tools", "ai-tools"], "entities": ["Vitest", "Flavio", "Node.js"], "also_reported_by": [], "takeaway": "Run `vitest --changed` to execute only the test files dependent on edited source files — in the example, editing price.ts ran 4 of 6 test files and 7 of 10 tests instead of the full suite.", "recommendation": null, "alternates": {"html": "https://wpnews.pro/news/run-only-the-tests-your-change-touches-with-vitest-changed", "markdown": "https://wpnews.pro/news/run-only-the-tests-your-change-touches-with-vitest-changed.md", "text": "https://wpnews.pro/news/run-only-the-tests-your-change-touches-with-vitest-changed.txt", "jsonld": "https://wpnews.pro/news/run-only-the-tests-your-change-touches-with-vitest-changed.jsonld"}}