NewNode 26.14: mockResolvedValue and Friends in node:test →
w3/w3-tutorials

Vitest 5 migration: fix the tests that break on upgrade

Vitest 5 turns old warnings into errors and changes defaults like clearMocks. See the exact failures from a real upgrade, how to fix each one, and two CI changes that break without a single failing test.

Updated Nov 16, 20269 min readIntermediatevitest 5.1.0 · vitest 4.1.12 · vite 8.3.8 · node 22.22.3 · npm 10.9.8

Vitest 5 shipped on September 3, 2026, and 5.1.0 is the current release. Most of the upgrade is free speed. The rest is stricter behaviour: things Vitest 4 only warned about now fail the run, and some defaults changed in ways that break tests you never touched.

This guide takes a small Vitest 4.1.12 suite, upgrades it to 5.1.0, and fixes each failure in turn. Every error message below is copied from a real run.

Before you upgrade

Vitest 5 needs Node.js 22.12.0 or later and Vite 6.4.0 or later. Check Node first:

terminal
node --version
text
v22.22.3

Vite is now a peer dependency of vitest rather than a direct one. npm, pnpm and Bun install peer dependencies for you. Yarn doesn't, so Yarn users have to add vite to their own package.json.

Then check your Vitest integrations, because not all of them support 5 yet. The Cloudflare Workers pool is one example:

terminal
npm view @cloudflare/vitest-pool-workers version peerDependencies
text
version = '0.23.0'
peerDependencies = {
  vitest: '^4.1.0',
  '@vitest/runner': '^4.1.0',
  '@vitest/snapshot': '^4.1.0'
}

If a package you rely on pins vitest to ^4, stay on 4.1.x until it supports 5. Vitest 4.1.12 was published on October 15, 2026, six weeks after 5.0, so the 4.x line still gets patch releases.

1. Run the suite on Vitest 4

The example project has four test files, and each uses a pattern that is common in real suites. The code under test is tiny: convert() multiplies by getRate() from src/rates.ts, fetchUser() is async, and createNotifier(send) calls send with a message. On Vitest 4.1.12 all four files pass, with one warning:

terminal
npx vitest run
text
 RUN  v4.1.12

Warning: A vi.mock("../src/rates") call in "…/test/convert.test.ts" is not at the top level of the module. Although it appears nested, it will be hoisted and executed before any tests run. Move it to the top level to reflect its actual execution order. This will become an error in a future version.
See: https://vitest.dev/guide/mocking/modules#how-it-works

 Test Files  4 passed (4)
      Tests  4 passed (4)

Take that warning seriously. Vitest 5 is the "future version" it mentions.

2. Upgrade and watch it fail

terminal
npm install -D vitest@5
text
added 2 packages, removed 11 packages, changed 7 packages, and audited 36 packages in 1s

The install removes packages because Vitest 5 bundles its own dependencies. Now run the same suite:

terminal
npx vitest run
text
 RUN  v5.1.0

 ❯ test/convert.test.ts (0 test)
 ❯ test/math.test.ts (0 test)
 ❯ test/notify.test.ts (1 test | 1 failed) 4ms
   × sends the welcome message 3ms
 ❯ test/users.test.ts (1 test | 1 failed) 4ms
   × loads the user 4ms

 Test Files  4 failed (4)
      Tests  2 failed (2)

Every file fails, and each for a different reason. Two suites fail before any test runs, and two tests fail on their assertions.

3. Move vi.mock to the top level

text
 FAIL  test/convert.test.ts [ test/convert.test.ts ]
Error: 1 call in "test/convert.test.ts" was defined outside of the module's top level scope:

- vi.mock("../src/rates") at test/convert.test.ts:5:3

Although it appears nested, it will be hoisted and executed before anything in this file. Move it to the top level to reflect its actual execution order.

The test called vi.mock inside describe:

test/convert.test.ts
import { describe, expect, test, vi } from 'vitest'
import { convert } from '../src/convert'

describe('convert', () => {
  vi.mock('../src/rates', () => ({ getRate: () => 2 }))

  test('multiplies by the rate', () => {
    expect(convert(10, 'EUR')).toBe(20)
  })
})

Vitest moves every vi.mock call to the top of the file, above the imports. So this mock never ran inside the describe block. It replaced ../src/rates for the whole file. The nested version looks scoped, but it isn't, and Vitest 5 now throws an error instead of letting the code mislead whoever reads it next. Move the call to the top level:

test/convert.test.ts
import { describe, expect, test, vi } from 'vitest'
import { convert } from '../src/convert'

vi.mock('../src/rates', () => ({ getRate: () => 2 }))

describe('convert', () => {
  test('multiplies by the rate', () => {
    expect(convert(10, 'EUR')).toBe(20)
  })
})

If you really need a mock for only part of a file, use vi.doMock. It isn't hoisted, and it applies to the next dynamic import() of the module.

4. Await async assertions

text
 FAIL  test/users.test.ts > loads the user
Error: Promise returned by `expect(actual).resolves.toEqual(expected)` was not awaited. This assertion is asynchronous and must be awaited; otherwise, it is not guaranteed to complete before the test finishes:

await expect(actual).resolves.toEqual(expected)

The assertion had no await:

test/users.test.ts
import { expect, test } from 'vitest'
import { fetchUser } from '../src/users'

test('loads the user', async () => {
  expect(fetchUser(1)).resolves.toEqual({ id: 1, name: 'Ada' })
})

Vitest 4 passed this test, because it waited for loose assertions when the test ended. That meant the check ran later than it appeared to. As soon as a test did anything after the assertion, such as cleanup, the order was wrong. Vitest 5 fails the test instead. The rule covers .resolves, .rejects and toMatchFileSnapshot. The fix is the missing keyword:

test/users.test.ts
import { expect, test } from 'vitest'
import { fetchUser } from '../src/users'

test('loads the user', async () => {
  await expect(fetchUser(1)).resolves.toEqual({ id: 1, name: 'Ada' })
})

The error points at the exact line, so a large suite is tedious to fix but not hard.

5. Stop counting mock calls from beforeAll

text
 FAIL  test/notify.test.ts > sends the welcome message
AssertionError: expected "vi.fn()" to be called with arguments: [ 'ada', 'Welcome, ada!' ]

Number of calls: 0

The code under test ran once in beforeAll:

test/notify.test.ts
import { beforeAll, expect, test, vi } from 'vitest'
import { createNotifier } from '../src/notify'

const send = vi.fn()
const notifier = createNotifier(send)

beforeAll(() => {
  notifier.welcome('ada')
})

test('sends the welcome message', () => {
  expect(send).toHaveBeenCalledWith('ada', 'Welcome, ada!')
})

Nothing in this file is wrong. The default changed: clearMocks is now true, so Vitest calls vi.clearAllMocks() before every test. That wipes calls recorded in beforeAll, at the top level of a module or in a setup file. Mock implementations stay; only the call history goes.

Do the work per test instead. beforeEach runs after the automatic clear, so its calls survive:

test/notify.test.ts
import { beforeEach, expect, test, vi } from 'vitest'
import { createNotifier } from '../src/notify'

const send = vi.fn()
const notifier = createNotifier(send)

beforeEach(() => {
  notifier.welcome('ada')
})

test('sends the welcome message', () => {
  expect(send).toHaveBeenCalledWith('ada', 'Welcome, ada!')
})

You can also switch the old behaviour back on:

vitest.config.ts
import { defineConfig } from 'vitest/config'

export default defineConfig({
  test: {
    clearMocks: false,
  },
})

With that config, the original beforeAll version passes on 5.1.0. Treat it as a stopgap. Call history shared between tests is what makes a test pass or fail depending on which tests ran before it, and that is why the default changed.

6. Replace describe.sequential

text
 FAIL  test/math.test.ts [ test/math.test.ts ]
TypeError: describe.sequential is not a function

test.sequential, describe.sequential and the sequential option were already deprecated, and Vitest 5 removes them. To opt a suite out of concurrency you turned on elsewhere, pass concurrent: false:

test/math.test.ts
import { describe, expect, test } from 'vitest'

describe('math', { concurrent: false }, () => {
  test('adds', () => {
    expect(1 + 1).toBe(2)
  })
})

The same option works on a single test, as shown in the migration guide. With all four fixes, the suite passes again:

text
 RUN  v5.1.0

 Test Files  4 passed (4)
      Tests  4 passed (4)

7. Check your CI scripts

The next two changes don't fail any test. That makes them easy to miss: CI can break, or keep passing while checking less than you think.

-t patterns use a new separator. The -t filter now matches the full name exactly as the reporter prints it, with the suite and test names joined by ' > '. Vitest 4 joined them with a space. On Vitest 4, -t 'math adds' ran the adds test. On Vitest 5 it matches nothing:

terminal
npx vitest run -t 'math adds'
text
 Test Files  4 skipped (4)
      Tests  4 skipped (4)

That run exits with code 0. A CI job that runs part of the suite this way turns green while running no tests at all. Use the new separator:

terminal
npx vitest run -t 'math > adds'
text
 Test Files  1 passed | 3 skipped (4)
      Tests  1 passed | 3 skipped (4)

Matching a single name (-t adds) or using a wildcard (-t 'math.*adds') also selected the right test on Vitest 5. The migration guide suggests both because they work with either separator.

JSON and JUnit reports go to files. The json and junit reporters now write to .vitest/json/output.json and .vitest/junit/output.xml instead of stdout. A pipe that used to work now sends the normal console output to jq:

terminal
npx vitest run --reporter=json | jq '.numPassedTests'
text
jq: parse error: Invalid numeric literal at line 1, column 5

Read the file instead:

terminal
npx vitest run --reporter=json
jq '{numTotalTests, numPassedTests}' .vitest/json/output.json
text
JSON report written to …/.vitest/json/output.json
{
  "numTotalTests": 4,
  "numPassedTests": 4
}

Or keep the old behaviour with the reporter's stdout option:

vitest.config.ts
import { defineConfig } from 'vitest/config'

export default defineConfig({
  test: {
    reporters: [['json', { stdout: true }]],
  },
})

With that config, npx vitest run | jq '{numTotalTests, numPassedTests}' prints the same object, and no .vitest folder is created. The HTML and blob reporters, attachments and failure screenshots also moved into .vitest, so one .vitest line in .gitignore covers all of them.

Other changes to check

The example suite doesn't hit these, but many real projects will:

If you useWhat changed
Inline test.projectsThey inherit the root config by default, plugins included. Arrays such as setupFiles are appended. Set extends: false to opt out.
VITEST_POOL_ID or VITEST_WORKER_IDIds start at 1, not 0. Check anything named per worker, such as test databases.
Browser Mode locatorsText matches are exact by default. toHaveTextContent is now strict, and toMatchTextContent does partial and regex matches.
bench()The API was rewritten. bench is now a fixture inside test().
Fake timersTemporal is faked too when it exists on the global object.
Running Vitest from a subfolderParent directories are no longer searched for a config file.
toThrow('')It matches any message now. Use a regex for an empty message.

Next steps

Run npx vitest doctor. It reruns your suite with other pool and isolation settings and recommends the fastest one:

terminal
npx vitest doctor
text
Results (min of 3 runs each)

  baseline (pool: forks · isolate: true)  0.26s
  pool: 'threads'                         0.23s (-10%)
  isolate: false                          0.24s (-5%)

Recommendation: pool: 'threads' (-10%)

On a suite this small the gaps are noise. Two runs on this example gave different advice, and the first said to keep the current setup. Trust it more on a suite that takes minutes.

  • Try vi.when for mocks that return different values for different arguments, and Trace View if you test in Browser Mode.
  • Read the full migration guide for the Browser Mode, coverage and custom reporter changes this article skips.

Related tutorials