Vitest 5 failed three of my four tests. None of them were bugs.

By Esteban Trillo5 min readTypeScriptTestingTooling

I bumped vitest from 4.1.12 to 5.0.5 on a small suite and ran it. Four tests, three failures:

vitest run on 5.0.5
❯ 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 202ms

The 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.

A small black bird labeled 'Vitest 5' pulls away a wooden prop tagged 'old defaults' from under an easel marked 'tests', whose checkmark is turning into a red X. A man with glasses crouches beside it, lifting a cloth and pointing at the prop. To the right sits a box with a code symbol labeled 'code: unchanged'.

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.

src/subscribe.ts
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";
}
src/subscribe.test.ts (passes on 4.1.12)
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 times

clearMocks 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:

one test, one story
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 not
guaranteed to complete before the test finishes

This 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:

await it
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:

find unawaited async assertions
grep -rnE "^\s*expect\(.*\)\.(resolves|rejects)\." src

toMatchFileSnapshot 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:

poll with the signal
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 global Temporal, so nothing changed for me. If you’re on a runtime that has it, vi.useFakeTimers() now fakes it too. Add Temporal to toNotFake to opt out.
  • Browser Mode locators are strict: getByText('Item') no longer matches Item 1.
  • Custom matcher types: Matchers<T> is now Matchers<R, T>, so declare module blocks that extend it need a second type parameter.
  • bench moved: 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 .gitignore and 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:

before: a switch in mockImplementation
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}`);
});
after: vi.when
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:

start from a clean spy
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:

vitest.config.ts
export default defineConfig({
test: {
testTimeout: 1234,
projects: [
{ test: { name: "root", include: ["src/**/*.test.ts"] } },
"./packages/*/vitest.config.ts",
],
},
});
packages/app/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:

vitest run --reporter=verbose
✓ |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 timeout

The -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:

vitest doctor
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:

  1. Grep CI logs for the “was not awaited” warning, and add the awaits.
  2. Run the suite with clearMocks: true and fix the tests that fail.
  3. 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.

Piwi hands a single letter to the user at a mailbox; a small note reads no noise.

Get the next one in your inbox

One email when a post goes out, with its sketch. Nothing in between, and one link to leave.

Sign in faster next time?

Add a passkey and skip the email link. Your fingerprint, face or device PIN is enough.