I bumped vitest from 4.1.12 to 5.0.5 on a small suite and ran it. Four tests, three failures:
❯ src/subscribe.test.ts (4 tests | 3 failed) 207ms ❯ subscribe (3) × sent exactly one confirmation so far 2ms × rejects a bad email 1ms ❯ polling (1) × poll whose callback hangs 202msThe code under test didn’t change. Every one of those tests had been passing for the wrong reason, and Vitest 5 changed the defaults that hid it.

The defaults were holding the tests up. The code never moved.
This post goes through each failure, the fix, and then the parts of 5.0 worth adopting once you’re green: vi.when, nested projects and vitest doctor.
The suite
This blog runs its own tests on bun test, so there was nothing here to upgrade. I built a scratch project instead, shaped like the newsletter signup this site has: a subscribe function with a database and a mailer passed in.
export type Db = { findByEmail(email: string): Promise<{ email: string } | null>; insert(email: string): Promise<void>;};export type Mailer = { send(to: string, subject: string): Promise<void> };
export async function subscribe(email: string, db: Db, mailer: Mailer) { if (!email.includes("@")) throw new Error("invalid email"); if (await db.findByEmail(email)) return "exists"; await db.insert(email); await mailer.send(email, "Confirm your subscription"); return "created";}const db = { findByEmail: vi.fn(), insert: vi.fn() };const mailer = { send: vi.fn() };
describe("subscribe", () => { it("creates a new subscriber", async () => { db.findByEmail.mockResolvedValue(null); expect(await subscribe("a@b.co", db, mailer)).toBe("created"); });
// leans on the call recorded by the previous test it("sent exactly one confirmation so far", () => { expect(mailer.send).toHaveBeenCalledTimes(1); });
it("rejects a bad email", () => { expect(subscribe("nope", db, mailer)).rejects.toThrow("invalid email"); });});
describe("polling", () => { it("poll whose callback hangs", async () => { const hangingFetch = () => new Promise<boolean>(() => {}); await expect.poll(hangingFetch, { timeout: 200 }).toBe(true); }, 2_000);});Before you start, check the floor. Vitest 5 needs Vite 6.4 or newer and Node 22.12 or newer.
Break 1: mocks are cleared before every test
AssertionError: expected "vi.fn()" to be called 1 times, but got 0 timesclearMocks now defaults to true, so Vitest calls vi.clearAllMocks() before each test. The second test was reading a call made by the first one. That only ever worked because the tests ran in order and nobody ran the second one alone.
The fix is to make the test own its state. Assert on the call in the test that makes it:
it("creates a new subscriber and sends one confirmation", async () => { db.findByEmail.mockResolvedValue(null); expect(await subscribe("a@b.co", db, mailer)).toBe("created"); expect(mailer.send).toHaveBeenCalledTimes(1);});If a suite has dozens of these, clearMocks: false in the config buys you time. I’d treat it as a list of tests to fix, not a setting to keep.
Break 2: unawaited rejects fail the test
Error: Promise returned by `expect(actual).rejects.toThrow(expected)` was not awaited.This assertion is asynchronous and must be awaited; otherwise, it is notguaranteed to complete before the test finishesThis one surprised me, because 4.1 already did half the job. I wrote a version with the wrong error message, and 4.1 failed it. Vitest 4 auto-awaits hanging assertions at the end of the test, so a wrong unawaited assertion still got caught.
What 4.1 let through was a correct unawaited assertion. It printed a warning saying exactly this would break “in the next Vitest major”, and the test passed. Now it fails. If your CI logs have that warning in them, each one is a test that will go red.
The fix is one word:
it("rejects a bad email", async () => { await expect(subscribe("nope", db, mailer)).rejects.toThrow("invalid email");});To find them before the upgrade does, search for resolves and rejects lines that don’t start with await or return:
grep -rnE "^\s*expect\(.*\)\.(resolves|rejects)\." srctoMatchFileSnapshot is async too, and gets the same treatment.
Break 3: expect.poll gives up on time
Error: expect.poll() function didn't resolve in time.Caused by: Error: Matcher did not succeed in time.The callback here returns a promise that never settles, which is what a fetch against a dead server looks like. On 4.1 the 200ms poll timeout didn’t help: the test sat there until the 2-second test timeout killed it. On 5.0 the poll rejects at 200ms.
So this test was always broken. The upgrade makes it fail faster and with a message that points at the poll instead of the test.
The poll callback also gets an AbortSignal now. Pass it to whatever you’re waiting on, so the work stops when the poll gives up:
await expect .poll(({ signal }) => fetch(healthUrl, { signal }).then((r) => r.ok), { timeout: 2_000, }) .toBe(true);The ones I couldn’t hit here
A few changes didn’t show up in this suite. They’re still worth searching for:
- Fake timers mock
Temporal: Node 24 has no globalTemporal, so nothing changed for me. If you’re on a runtime that has it,vi.useFakeTimers()now fakes it too. AddTemporaltotoNotFaketo opt out. - Browser Mode locators are strict:
getByText('Item')no longer matchesItem 1. - Custom matcher types:
Matchers<T>is nowMatchers<R, T>, sodeclare moduleblocks that extend it need a second type parameter. benchmoved: it’s a test-context fixture now, not a top-level import.- Reports moved: HTML, JSON and JUnit output, attachments, screenshots and traces all go to
.vitest/at the project root. Add it to.gitignoreand update any CI step that uploads reports from the old path.
vi.when replaces the argument switch
Once the suite was green I rewrote the mock I always end up writing, the one that returns something different per argument:
db.findByEmail.mockImplementation(async (email: string) => { if (email === "old@b.co") return { email }; if (email === "new@b.co") return null; throw new Error(`unexpected email ${email}`);});const w = vi .when(db.findByEmail) .calledWith("old@b.co") .thenResolve({ email: "old@b.co" }) .calledWith("new@b.co") .thenResolveOnce(null);
expect(await subscribe("old@b.co", db, mailer)).toBe("exists");expect(await subscribe("new@b.co", db, mailer)).toBe("created");expect(w).toHaveBeenExhausted();Arguments match with deep equality, so expect.any(String) works in calledWith as well. Two things weren’t obvious from the docs, so I checked them.
First, toHaveBeenExhausted means every stub was hit at least once. I guessed it meant “all the Once behaviors are used up” and wrote .not.toHaveBeenExhausted(), which failed. An unlimited thenResolve counts as exhausted after one call. Read it as “no stub went unused”, which is the check you want.
Second, unmatched arguments fall through to the spy’s own implementation. With no fallback, vi.fn() returns undefined. In my suite the fallback was the mockImplementation switch from the test before, which clearMocks hadn’t removed, so an unexpected email threw unexpected email who@b.co in a test that never mentioned it. Reset the spy before you layer vi.when on top:
db.findByEmail.mockReset();vi.when(db.findByEmail) .calledWith("old@b.co") .thenResolve({ email: "old@b.co" });
expect(db.findByEmail("who@b.co")).toBeUndefined();Nested projects
A config listed in test.projects can now declare its own projects. I added a package with unit and integration tests:
export default defineConfig({ test: { testTimeout: 1234, projects: [ { test: { name: "root", include: ["src/**/*.test.ts"] } }, "./packages/*/vitest.config.ts", ], },});export default defineConfig({ test: { projects: [ { test: { name: "unit", include: ["src/unit/**/*.test.ts"] } }, { test: { name: "int", include: ["src/int/**/*.test.ts"] } }, ], },});The children are named after their parent package:
✓ |app (int)| src/int/t.test.ts > int sees timeout ✓ |root| src/inherit.test.ts > inline project inherits root testTimeout ✓ |app (unit)| src/unit/t.test.ts > unit sees timeoutThe -p filter follows the tree. vitest -p app ran both of the app’s projects, and vitest -p "app (unit)" ran one.
Inline projects also inherit the root config by default now. The root project above picked up testTimeout: 1234 without asking. In Vitest 4 that took extends: true on every project, so you can delete those lines.
vitest doctor
vitest doctor runs your suite under a few alternative configurations and tells you which was fastest. On the scratch project:
Results (min of 3 runs each) baseline (pool: forks · isolate: true) 0.71s pool: 'threads' 0.54s (-23%) isolate: false 0.58s (-18%) maxWorkers: 3 (with pool: 'threads') 0.51s (-28%)
Recommendation: pool: 'threads' + maxWorkers: 3 (-28%)On a suite that finishes in under a second, those numbers are noise. The tool knows that and tells you to close other heavy programs before trusting it. Where it earns its place is a suite that takes minutes, where nobody has ever checked whether forks still beats threads. It also prints the config snippet to paste in, and it warns that it changes options for every project at once.
What I’d do on a real codebase
Before the upgrade, while you’re still on 4.1:
- Grep CI logs for the “was not awaited” warning, and add the
awaits. - Run the suite with
clearMocks: trueand fix the tests that fail. - Check your Node and Vite versions.
Then bump to 5.0, and both of the big default changes are already done. Delete the extends: true lines and add .vitest/ to .gitignore. Once it’s green, run vitest doctor and swap your nastiest mockImplementation switch for vi.when.
I didn’t try Trace View. It needs Browser Mode with a provider, and this suite had no browser. That’s the next one to break.
