Skip to content
masterclassBuddyTech Buzz5 fresh blogs · 5:00 AM IST

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
  1. Ajest
  2. BviCorrect answer
  3. Cmock
  4. Dsinon

Why: vi mirrors Jest's jest object.

2Vitest is built on…Asked almost every time
  1. AViteCorrect answer
  2. BBabel only
  3. Cesbuild alone
  4. DWebpack

Why: It reuses Vite's config and transforms.

3Why is vi.hoisted needed?Asked almost every time
  1. Avi.mock is hoisted above other codeCorrect answer
  2. BIt speeds up tests
  3. CIt enables watch mode
  4. DIt mocks timers

Why: Factories can use hoisted values.

4Where does Vitest read aliases and plugins from?Asked almost every time
  1. Ajest.config
  2. Bpackage.json scripts
  3. CThe Vite configCorrect answer
  4. Dbabel.config only

Why: Same pipeline as the app.

5Which import adds jest-dom matchers to Vitest?Asked almost every time
  1. Avitest/dom
  2. B@vitest/matchers
  3. C@testing-library/jest-dom/vitestCorrect answer
  4. Djest-dom/register

Why: Add it in a setup file.

6Which option gives DOM APIs to tests?Very often asked
  1. Aruntime: 'web'
  2. Benvironment: 'jsdom'Correct answer
  3. Cbrowser: false
  4. Ddom: true

Why: jsdom or happy-dom simulate the DOM.

7Which function partially mocks a module while keeping real exports?Very often asked
  1. Avi.restore
  2. Bvi.spyAll
  3. Cvi.importActualCorrect answer
  4. Dvi.unmock

Why: Spread the actual module into the factory.

8Which coverage providers does Vitest support?Very often asked
  1. Av8 and istanbulCorrect answer
  2. Bc8 only
  3. Cnyc only
  4. Dlcov only

Why: Pick one under test.coverage.provider.

9Which mode runs tests in a real browser?Very often asked
  1. ABrowser ModeCorrect answer
  2. BNode mode
  3. CSSR mode
  4. DWatch mode

Why: Browser Mode uses Playwright or WebdriverIO.

10What does watch mode rerun on change?Very often asked
  1. AAll tests
  2. BOnly tests affected by the changed modulesCorrect answer
  3. CNothing
  4. DOnly failed tests ever

Why: It uses Vite's module graph.

11Which sets an environment variable for a test?Very often asked
  1. Avi.stubEnvCorrect answer
  2. Bprocess.env only
  3. Cvi.env
  4. Dvi.setEnv

Why: Restore with unstubAllEnvs.

12Which defines reusable fixtures?Very often asked
  1. Atest.extendCorrect answer
  2. Bvi.fixture
  3. CbeforeAll only
  4. Ddescribe.fixture

Why: Set up and tear down per test.

13Which runs tests in a file in parallel?Very often asked
  1. Avi.parallel
  2. Bdescribe.async
  3. Ctest.concurrentCorrect answer
  4. Dtest.parallel

Why: Use context expect.

14Which command runs benchmarks?Very often asked
  1. Avitest --bench-only
  2. Bnpm bench
  3. Cvitest benchCorrect answer
  4. Dvitest perf

Why: Uses Tinybench.

15Which flag filters tests by name?Very often asked
  1. A--name-only
  2. B-tCorrect answer
  3. C--grep-files
  4. D--only

Why: Matches test names.

16Which setting enables Jest-style global describe and expect?Often asked
  1. Alegacy: true
  2. Bglobals: trueCorrect answer
  3. Cjest: true
  4. Dcompat: 'jest'

Why: Otherwise import them from 'vitest'.

17Which call controls the fake clock's date?Often asked
  1. Avi.clock
  2. BDate.mock
  3. Cvi.now
  4. Dvi.setSystemTimeCorrect answer

Why: It sets the current time for Date.

18Where do in-source tests go?Often asked
  1. A__tests__ only
  2. BInside if (import.meta.vitest)Correct answer
  3. CIn package.json
  4. DIn vite.config

Why: They are stripped from production builds.

19Which assertion checks a promise rejects?Often asked
  1. Aexpect.reject(p)
  2. Bp.should.fail
  3. Cexpect(p).toThrow()
  4. Dawait expect(p).rejects.toThrow()Correct answer

Why: Same as Jest.

20Which renders a hook in a test?Often asked
  1. ArenderHookCorrect answer
  2. BmountHook
  3. Cvi.hook
  4. DtestHook

Why: From Testing Library.

21Which retries an assertion until it passes?Often asked
  1. Avi.waitFor only
  2. Bexpect.eventually
  3. Cexpect.pollCorrect answer
  4. Dexpect.retry

Why: No fixed sleeps.

22Which mocks a global like matchMedia?Often asked
  1. Avi.stubGlobalCorrect answer
  2. Bvi.global
  3. CglobalThis.mock
  4. Dvi.window

Why: Restored with unstubAllGlobals.

23Which reporter creates CI annotations on GitHub?Often asked
  1. Adot
  2. Bverbose
  3. Ctap
  4. Dgithub-actionsCorrect answer

Why: Shows failures inline.

24Which flag runs tests affected by changed files?Often asked
  1. A--diff
  2. B--related-only
  3. C--changedCorrect answer
  4. D--watch-only

Why: It uses Git to find changed files.

25Test files are isolated by default by…Often asked
  1. ASeparate module graphs per fileCorrect answer
  2. BSeparate machines
  3. CDocker containers
  4. DNothing

Why: Configurable with isolate.

26Which command opens the Vitest dashboard?Sometimes asked
  1. Avitest dash
  2. Bvitest --uiCorrect answer
  3. Cvitest serve
  4. Dvitest open

Why: The UI shows results and module graphs.

27Which API checks types in type tests?Sometimes asked
  1. AtsExpect
  2. BexpectTypeOfCorrect answer
  3. CtypeCheck()
  4. DassertTs

Why: expectTypeOf runs under --typecheck.

28How do you split test files across CI machines?Sometimes asked
  1. A--shard=1/3Correct answer
  2. B--split 3
  3. C--workers 3
  4. D--pool 3

Why: Sharding divides files between runs.

29Which DOM environment is a lighter alternative to jsdom?Sometimes asked
  1. Acheerio
  2. Bhappy-domCorrect answer
  3. Cpuppeteer
  4. Ddomino-lite

Why: Faster for many tests.

30Which reporter format suits CI dashboards?Sometimes asked
  1. Adefault
  2. Bbasic
  3. CjunitCorrect answer
  4. Ddot

Why: XML results.

Track what you have practised and search every bank in your dashboard.

Start learning