Loading source
Pulling the file list, source metadata, and syntax-aware rendering for this listing.
Source from repo
Vitest 3.x reference skill covering configuration, test/describe APIs, mocking, coverage, snapshots, and concurrency.
Files
Skill
Size
Entrypoint
Format
Open file
Syntax-highlighted preview of this file as included in the skill package.
references/advanced-vi.md
1---2name: vi-utilities3description: vi helper for mocking, timers, utilities4---56# Vi Utilities78The `vi` helper provides mocking and utility functions.910```ts11import { vi } from 'vitest'12```1314## Mock Functions1516```ts17// Create mock18const fn = vi.fn()19const fnWithImpl = vi.fn((x) => x * 2)2021// Check if mock22vi.isMockFunction(fn) // true2324// Mock methods25fn.mockReturnValue(42)26fn.mockReturnValueOnce(1)27fn.mockResolvedValue(data)28fn.mockRejectedValue(error)29fn.mockImplementation(() => 'result')30fn.mockImplementationOnce(() => 'once')3132// Clear/reset33fn.mockClear() // Clear call history34fn.mockReset() // Clear history + implementation35fn.mockRestore() // Restore original (for spies)36```3738## Spying3940```ts41const obj = { method: () => 'original' }4243const spy = vi.spyOn(obj, 'method')44obj.method()4546expect(spy).toHaveBeenCalled()4748// Mock implementation49spy.mockReturnValue('mocked')5051// Spy on getter/setter52vi.spyOn(obj, 'prop', 'get').mockReturnValue('value')53```5455## Module Mocking5657```ts58// Hoisted to top of file59vi.mock('./module', () => ({60fn: vi.fn(),61}))6263// Partial mock64vi.mock('./module', async (importOriginal) => ({65...(await importOriginal()),66specificFn: vi.fn(),67}))6869// Spy mode - keep implementation70vi.mock('./module', { spy: true })7172// Import actual module inside mock73const actual = await vi.importActual('./module')7475// Import as mock76const mocked = await vi.importMock('./module')77```7879## Dynamic Mocking8081```ts82// Not hoisted - use with dynamic imports83vi.doMock('./config', () => ({ key: 'value' }))84const config = await import('./config')8586// Unmock87vi.doUnmock('./config')88vi.unmock('./module') // Hoisted89```9091## Reset Modules9293```ts94// Clear module cache95vi.resetModules()9697// Wait for dynamic imports98await vi.dynamicImportSettled()99```100101## Fake Timers102103```ts104vi.useFakeTimers()105106setTimeout(() => console.log('done'), 1000)107108// Advance time109vi.advanceTimersByTime(1000)110vi.advanceTimersByTimeAsync(1000) // For async callbacks111vi.advanceTimersToNextTimer()112vi.advanceTimersToNextFrame() // requestAnimationFrame113114// Run all timers115vi.runAllTimers()116vi.runAllTimersAsync()117vi.runOnlyPendingTimers()118119// Clear timers120vi.clearAllTimers()121122// Check state123vi.getTimerCount()124vi.isFakeTimers()125126// Restore127vi.useRealTimers()128```129130## Mock Date/Time131132```ts133vi.setSystemTime(new Date('2024-01-01'))134expect(new Date().getFullYear()).toBe(2024)135136vi.getMockedSystemTime() // Get mocked date137vi.getRealSystemTime() // Get real time (ms)138```139140## Global/Env Mocking141142```ts143// Stub global144vi.stubGlobal('fetch', vi.fn())145vi.unstubAllGlobals()146147// Stub environment148vi.stubEnv('API_KEY', 'test')149vi.stubEnv('NODE_ENV', 'test')150vi.unstubAllEnvs()151```152153## Hoisted Code154155Run code before imports:156157```ts158const mock = vi.hoisted(() => vi.fn())159160vi.mock('./module', () => ({161fn: mock, // Can reference hoisted variable162}))163```164165## Waiting Utilities166167```ts168// Wait for callback to succeed169await vi.waitFor(async () => {170const el = document.querySelector('.loaded')171expect(el).toBeTruthy()172}, { timeout: 5000, interval: 100 })173174// Wait for truthy value175const element = await vi.waitUntil(176() => document.querySelector('.loaded'),177{ timeout: 5000 }178)179```180181## Mock Object182183Mock all methods of an object:184185```ts186const original = {187method: () => 'real',188nested: { fn: () => 'nested' },189}190191const mocked = vi.mockObject(original)192mocked.method() // undefined (mocked)193mocked.method.mockReturnValue('mocked')194195// Spy mode196const spied = vi.mockObject(original, { spy: true })197spied.method() // 'real'198expect(spied.method).toHaveBeenCalled()199```200201## Test Configuration202203```ts204vi.setConfig({205testTimeout: 10_000,206hookTimeout: 10_000,207})208209vi.resetConfig()210```211212## Global Mock Management213214```ts215vi.clearAllMocks() // Clear all mock call history216vi.resetAllMocks() // Reset + clear implementation217vi.restoreAllMocks() // Restore originals (spies)218```219220## vi.mocked Type Helper221222TypeScript helper for mocked values:223224```ts225import { myFn } from './module'226vi.mock('./module')227228// Type as mock229vi.mocked(myFn).mockReturnValue('typed')230231// Deep mocking232vi.mocked(myModule, { deep: true })233234// Partial mock typing235vi.mocked(fn, { partial: true }).mockResolvedValue({ ok: true })236```237238## Key Points239240- `vi.mock` is hoisted - use `vi.doMock` for dynamic mocking241- `vi.hoisted` lets you reference variables in mock factories242- Use `vi.spyOn` to spy on existing methods243- Fake timers require explicit setup and teardown244- `vi.waitFor` retries until assertion passes245246<!--247Source references:248- https://vitest.dev/api/vi.html249-->250