Top 30 Vitest Interview Questions and Answers [2026]
October 10, 2026
12 min read
TL;DR: Vitest interviews in 2026 test module mocking and hoisting, mock reset rules, environments versus Browser Mode, and how to keep a large suite fast in CI. Candidates should know that Vitest 5.0 (September 3, 2026) clears mocks before every test by default and fails any async assertion that is not awaited.
Vitest 5.0 shipped on September 3, 2026 and changed two defaults that make old tests fail on upgrade: clearMocks is now on, and an unawaited expect(...).resolves fails the test instead of printing a warning.
It also requires Node.js 22.12 and Vite 6.4 or later. Anyone who wrote Vitest code in 2024 knows half of what follows; the other half moved in the last twelve months.
Key takeaways
1Current release as of late September 2026: Vitest 5.0.2, with 4.1.x still receiving patches.
2The workspace file is gone: Vitest 4 replaced it with test.projects, and Vitest 5 makes inline projects inherit the root config.
3Browser Mode lost its experimental tag in Vitest 4.0, and each provider is now its own package, such as @vitest/browser-playwright.
4Calling vi.mock inside a describe or test block now throws at transform time instead of warning.
Core Concepts
1. Why would a team choose Vitest over Jest?
Because Vitest reuses the project's Vite config and transform pipeline, so tests see the same aliases, plugins and TypeScript handling as the app, with no separate Babel or ts-jest setup.
It runs ES modules natively and keeps a Jest-compatible API (describe, test, expect, snapshot matchers), which makes migration mostly mechanical.
A strong candidate also says when the switch is not worth it: a large, stable Jest suite on a non-Vite build gains little, and anything that depends on Jest-only plugins needs a replacement first.
The honest answer is about config drift and ESM, not raw speed claims.
2. What breaks when you port a Jest suite to Vitest?
mockReset differs. Jest resets to an empty function; Vitest resets vi.fn(impl) back to impl.
__mocks__ folders are not loaded unless vi.mock() is called for that module.
No done callback. Rewrite callback tests with async/await or a Promise.
Hooks also run as a stack by default rather than in declaration order; sequence.hooks: 'list' restores Jest's order.
3. How does watch mode decide which tests to rerun?
It walks Vite's module graph. After a source file changes, Vitest reruns only the test files that import it, directly or transitively, the same way Vite decides what to hot-reload.
Plain vitest starts in watch mode during development and in run mode when process.env.CI is set or the terminal is not interactive.
Two related commands come up in CI questions: vitest related src/a.ts src/b.ts --run runs tests that statically import the given files (useful in lint-staged), and vitest run --changed runs tests affected by uncommitted changes, or by changes since a given commit or branch.
4. Where does Vitest config live, and what does Vitest 5 require?
Vitest looks for vitest.config.ts first and falls back to vite.config.ts, with test options under a test key.
A vitest.config.ts replaces the Vite config entirely, so a separate vitest.config.ts that calls mergeConfig with the Vite config keeps test-only options out of the app build.
Vitest 5 requires Node.js 22.12 or later and Vite 6.4 or later. It also stopped searching parent directories for a config file, so running vitest from a subfolder of a monorepo now needs --config ../vitest.config.ts.
Yarn users must add vite to their own package.json, because it became a peer dependency.
5. How do you run a single test from the command line?
By file and line: vitest src/cart.test.ts:42 runs the test declared on line 42 (the full relative filename is required). By name: -t filters on the test's full name.
Vitest 5 changed what "full name" means. -t now matches the suite chain joined with ' > ', the string the reporter prints, so -t 'math adds' becomes -t 'math > adds'.
A pattern that matches one segment, such as -t adds, works in both versions. test.only is fine locally but should fail CI; allowOnly is false in CI by default.
Mocking
6. What is the difference between vi.fn, vi.spyOn and vi.mock?
They mock at three levels:
vi.fn() creates a standalone mock function to pass in as a dependency or callback.
vi.spyOn(obj, 'method') wraps an existing method on an object. It records calls and can override the implementation, and it can be restored to the original.
vi.mock('./module') replaces a whole module for every importer in the test file. With no factory, every export is automocked; with { spy: true }, exports keep their real implementation but calls are recorded.
The design point a senior candidate makes: prefer passing dependencies in, so vi.fn() is enough, and reserve vi.mock for module boundaries you cannot inject, such as an HTTP client imported deep inside a component.
7. Why is vi.mock hoisted, and what is vi.hoisted for?
Static imports are evaluated before any other code in an ES module, so a mock registered on line 10 would be too late for an import on line 1. Vitest moves every vi.mock call to the top of the file before running it.
The side effect is that a vi.mock factory cannot use variables declared in the file, because they do not exist yet when it runs.
vi.hoisted solves that: its callback is hoisted too, and whatever it returns can be used in a factory and in tests.
Imported bindings are not available inside vi.hoisted; referencing one throws Cannot access '__vi_import_0__' before initialization.
Since Vitest 5, a vi.mock, vi.unmock or vi.hoisted call written inside a function or describe block throws, because it never ran where it was written. vi.doMock is not hoisted and still works anywhere, for imports that come after it.
Passing import('./pricing.js') instead of a string gives the factory the module's types and follows the file if an IDE renames it. The catch to mention: a partial mock only affects importers of the module.
A function in pricing.js that calls getRate internally still calls the real one, because it never goes through the module's exports.
9. What do mockClear, mockReset and mockRestore each reset?
Each one does more than the last. mockClear() empties mock.calls and mock.results but keeps the implementation. mockReset() also resets the implementation: to an empty function for vi.fn(), or back to impl for vi.fn(impl) and spies. mockRestore() also puts the original method back on the object, for spies made with vi.spyOn.
The restoreMocks trap. Since Vitest 4, vi.restoreAllMocks() and the restoreMocks option only restore vi.spyOn spies, leave automocks alone, and do not clear history or reset the implementation. A candidate who expects restoreMocks: true to give each test a clean mock is describing Vitest 3.
10. How do you mock a class, and what changed for class mocks?
Vitest 4 made vi.fn and vi.spyOn support constructors, so new works on a mock and mockImplementation(class { ... }) is valid.
Vitest 5 fixed instances of a class mock: their prototype now chains to the implementation class, so methods defined with class syntax exist on instances and instanceof against the real class passes.
class Dog { speak() { return 'bark!' } }
const MockedDog = vi.fn(Dog)
const dog = new MockedDog()
dog.speak() // 'bark!' in Vitest 5, undefined before
dog instanceof Dog // true in Vitest 5
For a module that exports a class, automocking with vi.mock('./client.js') gives mocked prototype methods shared by all instances; override one instance's method when a test needs different behavior per instance.
11. How do fake timers work, and what do they not fake by default?
vi.useFakeTimers() replaces setTimeout, setInterval, setImmediate, their clear functions and Date with @sinonjs/fake-timers. Time then moves only when the test advances it.
process.nextTick and queueMicrotask are not faked unless listed in toFake, and faking nextTick hangs the default forks pool. Timer callbacks that await promises need the async variants such as vi.advanceTimersByTimeAsync.
In Vitest 5, fake timers and vi.setSystemTime also mock Temporal, which matters on Node.js 26, where Temporal is enabled by default.
12. How do you stub fetch, environment variables and globals safely?
With vi.stubGlobal('fetch', vi.fn()) and vi.stubEnv('API_URL', 'http://test'), then vi.unstubAllGlobals() and vi.unstubAllEnvs() in an afterEach, or the unstubGlobals and unstubEnvs config options to do it automatically.
Assigning globalThis.fetch = ... by hand leaks into the next test file that shares the worker when isolation is off.
For HTTP-heavy code, a strong answer mocks at the network layer rather than per call, so the code under test still builds real requests and parses real responses.
Async and Assertions
13. How do you test async code without false passes?
Await the assertion, not only the call. await expect(promise).resolves.toBe(1) and await expect(fn()).rejects.toThrow('not found') both wait for the promise.
For code paths where the assertion sits inside a callback, expect.assertions(n) fails the test if fewer assertions ran.
Vitest 5 closed the most common hole: an async assertion that is not awaited now fails the test with "Promise returned by expect(actual).resolves.toBe(expected) was not awaited".
Before 5.0, Vitest awaited it at the end and only printed a warning, and the test could pass although the check never ran where it was written.
14. When do you use expect.poll, and when vi.waitFor?
expect.poll(fn).toBe(x) reruns a function and the matcher until the assertion passes or the timeout ends.
It suits a value that becomes true eventually, such as a status endpoint or a DOM query. vi.waitFor(callback) retries a callback until it stops throwing and returns its value, which suits waiting for a server or a mock to be called before continuing.
In Vitest 5, expect.poll fails when the callback does not settle within timeout, and the callback receives an AbortSignal so in-flight requests can be canceled.
In Browser Mode, expect.element(locator) is the polling form for DOM assertions.
15. What are the snapshot options, and how do you keep snapshots useful?
Three matchers: toMatchSnapshot() writes to a __snapshots__ file, toMatchInlineSnapshot() writes the value into the test file itself, and toMatchFileSnapshot(path) compares against a file you name, such as a generated .html or .sql file that reviewers can read with syntax highlighting.
Update with vitest -u or the u key in watch mode.
Strong candidates keep snapshots small and inline, capture meaningful output, and review them in the pull request like code. A 400-line component snapshot that everyone updates with -u tests nothing.
In concurrent tests, use the expect from the test context, because the global expect cannot tell which test a snapshot belongs to.
16. How does concurrency work inside and across test files?
Test files run in parallel across workers. Tests inside a file run one after another unless marked test.concurrent or run with sequence.concurrent: true, in which case async tests in that file overlap.
Vitest 5 removed test.sequential, describe.sequential and the sequential option; { concurrent: false } replaces them.
The follow-up question: concurrent tests and the default clearMocks interact badly, because one test finishing clears the call history of mocks another test is still using. Concurrent tests should create their own mocks.
Environments and Browser
17. How do you pick between node, jsdom, happy-dom and Browser Mode?
Start from what the code touches. Server code and pure logic run in node, the default and the fastest. Components that only need a DOM tree run in happy-dom or jsdom, simulated DOMs where happy-dom is lighter and jsdom implements more APIs.
Anything that depends on layout, real CSS, focus handling or a browser-only API belongs in Browser Mode, which runs the test inside a real browser.
Set the environment per file with a // @vitest-environment jsdom comment, or per project. The environment guide is explicit that browser is not an environment: Browser Mode is configured as its own project.
18. How does Browser Mode work, and which provider would you use?
Browser Mode serves the test files through Vite and runs them inside a real browser page, driven by a provider.
Since Vitest 4.0 each provider is a package: @vitest/browser-playwright, @vitest/browser-webdriverio or @vitest/browser-preview, passed as a function in config.
The Browser Mode guide recommends Playwright because it runs tests in parallel; preview simulates events instead of using the DevTools protocol and is for local previews only.
In Vitest 5 the WebdriverIO provider moved to the community-run vitest-community organization.
Tests import page from vitest/browser and use locators such as page.getByRole('button'), which are strict by default in Vitest 5: getByText('Item') no longer matches "Item 1".
19. Can Vitest do visual regression testing?
Yes, in Browser Mode since Vitest 4.0, with toMatchScreenshot:
import { expect, test } from 'vitest'
import { page } from 'vitest/browser'
test('hero renders', async () => {
await expect(page.getByTestId('hero')).toMatchScreenshot('hero-section')
})
The first run stores reference images; later runs compare against them.
The practical answer covers where screenshots are compared: fonts and anti-aliasing differ between macOS laptops and Linux CI runners, so teams generate and compare references in one environment, usually the CI container.
Vitest 5 added a screenshotDirectory option for where those references live. See the visual regression guide.
20. What is in-source testing, and when is it a good idea?
Tests written inside the source file, in an if (import.meta.vitest) block, which can test private helpers without exporting them:
It needs includeSource: ['src/**/*.{js,ts}'] in config and define: { 'import.meta.vitest': 'undefined' } in the production build so the bundler strips the block. It suits small pure utilities.
For components or anything with fixtures, separate test files stay easier to read; see the in-source testing guide.
Config, CI and Speed
21. How do you configure a monorepo with several kinds of tests?
With test.projects in the root config. Each entry is a glob of packages, a path to a config file, or an inline config with its own name, environment and include:
Three version facts matter here: the vitest.workspace file was replaced by projects in 3.2 and removed in 4.0; since Vitest 5 inline projects inherit the root config (plugins, aliases, pool) unless they set extends: false; and a referenced config can declare its own projects, which Vitest names app (unit), app (e2e) and so on.
22. Which pool would you use, and what does isolation cost?
The default pool is forks, child processes that support process.chdir() and native modules. threads uses worker threads and communicates faster, but native libraries such as Prisma, bcrypt and canvas can segfault in threads. vmThreads and vmForks run each file in a fresh VM context inside a reused worker, which is faster for DOM suites but leaks memory, so workers restart past vmMemoryLimit.
forks (default)
Child processes: process.chdir() works
Safe for native modules such as Prisma and bcrypt
Slower messaging with the main process
threads
Worker threads: faster messaging
Some native libraries segfault
Changing process.env.TZ has no effect
By default every test file gets a fresh module graph (isolate: true). Turning isolation off with --no-isolate can cut run time sharply but lets module state leak between files.
Vitest 4 rewrote the pools: maxThreads and maxForks became maxWorkers, and poolOptions was removed in favor of top-level options.
23. How do you set up coverage correctly in Vitest 4 and later?
Install @vitest/coverage-v8 (the default provider) or @vitest/coverage-istanbul, and always set coverage.include:
Vitest 4 removed coverage.all and now reports only files that were imported during the run unless include names them, so a file no test touches silently disappears from the report without it.
The v8 provider switched to AST-based remapping in 4.0, which the Vitest 4 migration guide says makes it as accurate as istanbul; coverage numbers shifted for many teams on upgrade.
The old claim that c8 is the default provider dates from Vitest 0.x.
24. How do you split a slow suite across CI machines?
Shard it and merge the results:
# on each of 3 CI jobs
vitest run --shard=1/3 --reporter=blob
# in a final job, after downloading every blob
vitest --merge-reports --reporter=junit
--shard divides test files into equal parts and cannot be used with watch mode. Blob reports land in .vitest/blob/, and --merge-reports turns them into one report in any format except blob.
Since Vitest 5, reporters, attachments and traces all write under a single .vitest directory, so one .gitignore entry covers them.
For flaky-test hunting, the --repeats flag added in 5.0 runs every test a set number of times whatever the result.
25. How do test fixtures work with test.extend?
test.extend creates a custom test whose context carries fixtures: values set up before a test and torn down after it. Vitest 4.1 added a builder form that infers each fixture's type from its return value:
import { test as baseTest } from 'vitest'
export const test = baseTest
.extend('db', { scope: 'file' }, async ({}, { onCleanup }) => {
const db = await createTestDatabase()
onCleanup(() => db.close())
return db
})
test.aroundEach(async (runTest, { db }) => {
await db.transaction(runTest)
})
Fixtures are lazy: a test that does not destructure db does not create it. Scopes are test (the default), file and worker.
The aroundEach hook, new in 4.1, wraps each test so it runs inside a transaction, a tracing span or an AsyncLocalStorage context, which beforeEach and afterEach cannot do. See the test context guide.
What Changed Recently
Jan 16, 2025
Vitest 3.0
Jun 2, 2025
Vitest 3.2: workspace renamed to projects
Oct 22, 2025
Vitest 4.0: stable Browser Mode, visual regression, pool rewrite
Mar 12, 2026
Vitest 4.1: tags, aroundEach, leak detection, Vite 8 support
Sep 3, 2026
Vitest 5.0: new defaults, vi.when, Trace View, vitest doctor
26. What did Vitest 4.0 remove or rename?
The 4.0 release on October 22, 2025 made Browser Mode stable and cleared out old configuration. The changes that break upgrades, per the migration guide:
workspace is replaced by projects.
coverage.all and coverage.extensions are removed; set coverage.include.
poolOptions is removed, and maxThreads/maxForks become maxWorkers.
Browser providers moved to separate packages, and page is imported from vitest/browser.
vite-node was replaced by Vite's Module Runner.
It also required Node.js 20 and Vite 6 at minimum, both raised again in 5.0.
27. What did Vitest 4.1 add that changes how suites are organized?
Test tags and leak detection. Vitest 4.1 (March 12, 2026) lets you define tags in config with options attached, then label tests and filter by expression:
--detect-async-leaks reports timers, handles and promises a test file leaves running, with source locations; it adds overhead, so it is a debugging switch rather than a CI default.
The release also added aroundEach/aroundAll, the typed fixture builder and support for Vite 8.
clearMocks defaults to true. Calls recorded in a setup file, at module top level or in beforeAll are cleared before the test that asserts on them.
Unawaited resolves, rejects and toMatchFileSnapshot fail the test.
Nested vi.mock/vi.hoisted calls throw.
test.sequential is gone; use { concurrent: false }.
Browser locators are exact by default, and toHaveTextContent checks strict equality (toMatchTextContent is the loose version).
A candidate who has done the upgrade will say which of these hit their suite and whether they fixed the tests or set clearMocks: false. The first answer is usually the better one.
29. What does vi.when do, and what is the ordering rule?
vi.when, added in 5.0, gives a mock different behavior per argument without a hand-written mockImplementation full of if statements:
The rule to know from the API reference: behaviors are tried last-in, first-out, so the most recently registered match wins and earlier ones act as fallbacks.
Unmatched calls fall through to the original implementation unless onUnmatched says otherwise, and expect(chain).toHaveBeenExhausted() checks that every registered behavior was used.
We ran these examples on Vitest 5.0.2; when a chain mixed literal arguments with expect.any() matchers, the results did not follow the documented order, so keep matchers literal until that settles.
30. What are Trace View and vitest doctor in Vitest 5?
Two tools for the slow and flaky parts of a suite.
Trace View, enabled with browser.traceView: true, records every interaction and assertion in a Browser Mode test as a DOM snapshot, so a failure in CI can be replayed step by step in Vitest UI or the HTML reporter.
Unlike the Playwright traces Vitest 4 supported, it does not depend on the provider or need a separate viewer.
vitest doctor reruns the suite under alternative settings (another pool, isolate: false, happy-dom instead of jsdom, fewer workers) and recommends the fastest one that still passes; it rejects isolate: false if shuffling file order breaks tests.
The Vitest 5 announcement measured a 1,280-module reference app at 7.24s on 4.1 and 5.83s on 5.0, a 19% cut, on an Apple M4.
Signs of a Strong Answer
They explain hoisting as a consequence of ES module evaluation order, then show vi.hoisted, rather than reciting that "vi.mock goes at the top".
They know restoreAllMocks only restores spies since Vitest 4, and that clearMocks is on by default in Vitest 5.
They pick the environment per project and can say what jsdom cannot do that Browser Mode can.
They set coverage.include without prompting and can explain why coverage numbers moved after the Vitest 4 upgrade.
They describe a real speed problem they fixed with pool choice, isolation, sharding or vitest doctor, with before and after numbers.
They treat snapshots as code under review, not as a file -u regenerates.
Hiring Vitest Developers
Vitest skills usually come with a front-end or full-stack role rather than a standalone title.