Interview questions with answers
Vitest interview questions and answers
Vite-powered tests: vi mocks, watch mode, browser mode and coverage. Open any question to read its model answer; the multiple-choice set marks the right option and explains it.
- Subjective
- 30
- Objective
- 30
Subjective questions 30
1What is Vitest and why choose it over Jest?Asked almost every time
Vitest is a test runner built on Vite. It reuses your Vite config, plugins and transforms, so TypeScript, JSX and ESM work without extra setup; its watch mode is fast because it uses Vite's module graph to rerun only affected tests. Its API is largely Jest-compatible (describe, it, expect, vi for mocks), so migrations are usually small.
2How do you mock with vi?Asked almost every time
vi.fn() creates a mock function, vi.spyOn(obj, 'method') spies on a method, and vi.mock('module', factory) replaces a module (hoisted to the top of the file). vi.importActual keeps the real module for partial mocks. vi.mocked() gives typed access to mocks, and vi.restoreAllMocks() cleans up.
3How do you test React components with Vitest?Asked almost every time
Use React Testing Library with environment: 'jsdom' (or happy-dom), add @testing-library/jest-dom/vitest in a setup file for matchers, render components, query by role and interact with user-event. Browser Mode can run the same tests in a real browser.
4What is vi.hoisted and why is it needed?Asked almost every time
vi.mock calls are hoisted to the top of the file, before imports, so they cannot use variables declared later. vi.hoisted(() => ({ fetchUser: vi.fn() })) creates values that are also hoisted, so mock factories can reference them.
5How does Vitest reuse Vite configuration?Asked almost every time
It reads vite.config (or vitest.config) so aliases, plugins (React, TypeScript paths) and transforms match the app. Test options go under the test key. This avoids maintaining separate Babel or Jest transform settings.
6How do you configure the test environment?Very often asked
In vitest.config.ts (or the test field of vite.config.ts) set environment: 'jsdom' or 'happy-dom' for DOM tests, 'node' otherwise, setupFiles for global setup (such as jest-dom matchers), globals: true if you want Jest-style globals, and include/exclude patterns. Per-file environments can use a comment at the top of the file.
7What is Vitest Browser Mode?Very often asked
It runs tests in a real browser (through Playwright or WebdriverIO providers) instead of a simulated DOM, so layout, CSS and browser APIs behave like production. It suits component tests where jsdom falls short, and provides interactivity APIs similar to user-event.
8How do fake timers work in Vitest?Very often asked
vi.useFakeTimers() then vi.advanceTimersByTime(ms), vi.runAllTimers() or vi.setSystemTime(date); restore with vi.useRealTimers(). Async versions such as advanceTimersByTimeAsync let pending promises settle between timers.
9How do you measure coverage?Very often asked
Run vitest run --coverage with a provider: v8 (fast, uses V8's built-in coverage) or istanbul (instrumentation). Configure reporters, include/exclude and thresholds under test.coverage.
10How do you test async code and errors?Very often asked
Use async tests with await, and await expect(promise).resolves / .rejects.toThrow(). expect.assertions(n) ensures async assertions actually ran. vi.waitFor retries a callback until it passes.
11How do you mock network requests in Vitest?Very often asked
Use MSW with setupServer in a setup file for realistic HTTP mocking, or vi.spyOn(globalThis, 'fetch').mockResolvedValue(new Response(JSON.stringify(data))) for simple cases. Restore mocks after each test.
12How do you stub environment variables and globals?Very often asked
vi.stubEnv('API_URL', 'http://test') and vi.stubGlobal('matchMedia', fn) set values for a test; vi.unstubAllEnvs() and vi.unstubAllGlobals() (or the unstubEnvs config option) restore them.
13What are test contexts and fixtures in Vitest?Very often asked
Each test receives a context object; test.extend({ db: async ({}, use) => { const db = await create(); await use(db); await db.close(); } }) defines fixtures that set up and tear down resources only for tests that use them.
14How do you run only some tests?Very often asked
Filter by file name on the command line, by test name with -t, use .only or .skip, tags with --project, or run tests related to changed files with --changed. In watch mode, press keys to filter interactively.
15What are concurrent tests?Very often asked
test.concurrent (or describe.concurrent) runs tests in the same file in parallel. Use the expect from the test context for snapshots and assertions so results are attributed to the right test.
16How do you benchmark with Vitest?Very often asked
Write bench('name', () => {...}) in *.bench.ts files and run vitest bench, which uses Tinybench to report operations per second and compare implementations.
17What are workspaces/projects in Vitest?Often asked
One config can define several projects (for example unit tests in node, component tests in jsdom or the browser, different packages in a monorepo), each with its own settings, run together with one command and one report.
18What is in-source testing?Often asked
Writing tests inside the source file under if (import.meta.vitest) { ... }. They run with Vitest but are removed from production builds through a define setting. Handy for small utility functions.
19How does Vitest run tests in parallel?Often asked
Test files run in parallel in worker threads or child processes (pool: 'threads' | 'forks' | 'vmThreads'); tests within a file run in sequence unless marked concurrent. --shard splits files across CI machines.
20How do snapshots work in Vitest?Often asked
toMatchSnapshot() writes to a __snapshots__ file, toMatchInlineSnapshot() writes into the test, and toMatchFileSnapshot() compares with a separate file; update with -u. Review snapshot changes like code.
21How do you migrate a project from Jest to Vitest?Often asked
Install Vitest, move config to vitest.config.ts, replace jest. calls with vi. (or enable globals), adjust module mocks (factories must return objects with named exports, default for default exports), switch setup files, and fix any CommonJS-only patterns.
22How do you test code that uses import.meta.env?Often asked
Vite defines import.meta.env in tests too; set values with vi.stubEnv or .env.test files, since Vitest loads env files for the test mode.
23What is the difference between vi.fn, vi.spyOn and vi.mock?Often asked
vi.fn() creates a standalone mock function; vi.spyOn(obj, 'method') wraps an existing method and can be restored; vi.mock('module') replaces a whole module for the file.
24How do you test a custom hook in Vitest?Often asked
Use renderHook from React Testing Library, read result.current, wrap updates in act, and provide context with the wrapper option.
25How do you deal with tests that leak state between files?Often asked
Vitest isolates files by default (separate module graphs). Within a file, reset mocks with restoreMocks or mockReset config, clean the DOM after each test, and avoid module-level mutable state.
26What does expect.poll do?Often asked
It repeatedly runs a function and asserts on its result until it passes or times out, useful for waiting on asynchronous conditions without fixed sleeps.
27How does Vitest handle CSS and assets?Often asked
By default CSS is processed lightly or ignored in tests (configurable with css options), and CSS Modules can return class names. Static assets resolve to paths, as in Vite.
28What is the Vitest UI?Sometimes asked
vitest --ui opens a browser dashboard showing test files, results, module graphs and console output, with filtering and reruns.
29Can Vitest type-check tests?Sometimes asked
Yes, vitest typecheck (or --typecheck) runs type-level tests using expectTypeOf and assertType through the TypeScript compiler, useful for libraries with complex types.
30How do you report results in CI?Sometimes asked
Use reporters such as junit for CI dashboards, github-actions for annotations, json or html, set with --reporter or the reporters config option.
Objective questions 30
1Which object provides mocking utilities in Vitest?Asked almost every time
Why: vi mirrors Jest's jest object.
2Vitest is built on…Asked almost every time
Why: It reuses Vite's config and transforms.
3Why is vi.hoisted needed?Asked almost every time
Why: Factories can use hoisted values.
4Where does Vitest read aliases and plugins from?Asked almost every time
Why: Same pipeline as the app.
5Which import adds jest-dom matchers to Vitest?Asked almost every time
Why: Add it in a setup file.
6Which option gives DOM APIs to tests?Very often asked
Why: jsdom or happy-dom simulate the DOM.
7Which function partially mocks a module while keeping real exports?Very often asked
Why: Spread the actual module into the factory.
8Which coverage providers does Vitest support?Very often asked
Why: Pick one under test.coverage.provider.
9Which mode runs tests in a real browser?Very often asked
Why: Browser Mode uses Playwright or WebdriverIO.
10What does watch mode rerun on change?Very often asked
Why: It uses Vite's module graph.
11Which sets an environment variable for a test?Very often asked
Why: Restore with unstubAllEnvs.
12Which defines reusable fixtures?Very often asked
Why: Set up and tear down per test.
13Which runs tests in a file in parallel?Very often asked
Why: Use context expect.
14Which command runs benchmarks?Very often asked
Why: Uses Tinybench.
15Which flag filters tests by name?Very often asked
Why: Matches test names.
16Which setting enables Jest-style global describe and expect?Often asked
Why: Otherwise import them from 'vitest'.
17Which call controls the fake clock's date?Often asked
Why: It sets the current time for Date.
18Where do in-source tests go?Often asked
Why: They are stripped from production builds.
19Which assertion checks a promise rejects?Often asked
Why: Same as Jest.
20Which renders a hook in a test?Often asked
Why: From Testing Library.
21Which retries an assertion until it passes?Often asked
Why: No fixed sleeps.
22Which mocks a global like matchMedia?Often asked
Why: Restored with unstubAllGlobals.
23Which reporter creates CI annotations on GitHub?Often asked
Why: Shows failures inline.
24Which flag runs tests affected by changed files?Often asked
Why: It uses Git to find changed files.
25Test files are isolated by default by…Often asked
Why: Configurable with isolate.
26Which command opens the Vitest dashboard?Sometimes asked
Why: The UI shows results and module graphs.
27Which API checks types in type tests?Sometimes asked
Why: expectTypeOf runs under --typecheck.
28How do you split test files across CI machines?Sometimes asked
Why: Sharding divides files between runs.
29Which DOM environment is a lighter alternative to jsdom?Sometimes asked
Why: Faster for many tests.
30Which reporter format suits CI dashboards?Sometimes asked
Why: XML results.
Track what you have practised and search every bank in your dashboard.
Start learning