Vitest
Runs tests using the Vite project configuration and plugins.
- Downloads / mo
- 696.6M
- Stars
- 17.4K
- Last release
- 5.1.1
- License
- MIT
Strengths
- Reuses existing Vite configuration. Use the same Vite plugins and configuration for tests.
- Parallelizes across test files. Test files run across multiple workers by default.
Limitations
- Coverage needs an extra package. Install the selected V8 or Istanbul coverage provider.
- Browser mode changes spying. Export spying with vi.spyOn needs a different approach in Browser Mode.
Quickstart
import { expect, test } from 'vitest' export function sum(a, b) { return a + b } test('adds 1 + 2 to equal 3', () => { expect(sum(1, 2)).toBe(3) })
Vitest examples
export async function launch(params: Frameworks.FrameworkLaunchParams): Promise<number> { if (params.specs.length === 0 && (params.config.shard?.total ?? 1) > 1) { log.info(`No specs to execute in shard ${params.config.shard!.current}/${params.config.shard!.total}, exiting!`) return 0 } let bridgeFailures = 0 // startVitest resolves only after the run, so the instance to cancel is captured while the run starts let running: Vitest | undefined let cancelRequested = params.signal?.aborted ?? false const cancel = () => { cancelRequested = true running?.cancelCurrentRun('keyboard-input').catch((err) => log.warn('Failed to cancel the Vitest run:', err)) } params.signal?.addEventListener('abort', cancel, { once: true }) const viteConfig = await toVitestConfig(params, () => bridgeFailures++) const reporters = viteConfig.test!.reporters viteConfig.test!.reporters = [...(reporters === undefined ? ['default'] : Array.isArray(reporters) ? reporters : [reporters]), { onInit(instance: Vitest) { running = instance // Vitest's Logger exits the process 1ms after SIGINT/SIGTERM, before the launcher's exit handler finishes waiting on this launch listenersBefore.forEach(([signal, before]) => process.listeners(signal).filter((listener) => !before.includes(listener)).forEach((listener) => process.off(signal, listener))) if (cancelRequested) { cancel() } } }] const listenersBefore = snapshotSignalListeners() let vitest: Vitest | undefined try { vitest = await startVitest([], { run: true, watch: false, config: false }, viteConfig) // a cancelled run leaves its tests skipped or pending, which would otherwise count as green return countFailures(vitest) + bridgeFailures + (params.signal?.aborted ? 1 : 0) } finally { params.signal?.removeEventListener('abort', cancel) await vitest?.close() } }