DEV Community

Alex Spinov
Alex Spinov

Posted on

Vitest Has a Free API That Makes Unit Testing in Vite Projects Lightning Fast

Vitest is the native test runner for Vite. Same config, same transforms, same plugin ecosystem. Tests run with Vite's speed — instant HMR, native ESM, no Babel.

Quick Start

npm install -D vitest
Enter fullscreen mode Exit fullscreen mode
// vite.config.ts — that's it, Vitest reads your existing Vite config
import { defineConfig } from 'vitest/config'
export default defineConfig({ test: { globals: true } })
Enter fullscreen mode Exit fullscreen mode

Basic Test

import { describe, it, expect } from 'vitest'

describe('math', () => {
  it('adds numbers', () => {
    expect(1 + 1).toBe(2)
  })
})
Enter fullscreen mode Exit fullscreen mode

Jest-Compatible API

import { describe, it, expect, vi, beforeEach } from 'vitest'

// Mocking
const mockFn = vi.fn()
vi.mock('./api', () => ({ fetchData: vi.fn() }))

// Spying
const spy = vi.spyOn(console, 'log')

// Timers
vi.useFakeTimers()
vi.advanceTimersByTime(1000)
Enter fullscreen mode Exit fullscreen mode

Drop-in replacement for Jest. Same describe, it, expect, vi (instead of jest).

Watch Mode (Instant Feedback)

npx vitest        # watch mode by default
npx vitest run    # single run (CI)
Enter fullscreen mode Exit fullscreen mode

Vitest re-runs only affected tests when you save a file — using Vite's module graph.

In-Source Testing

// src/utils.ts
export function add(a: number, b: number) { return a + b }

if (import.meta.vitest) {
  const { it, expect } = import.meta.vitest
  it('adds', () => { expect(add(1, 2)).toBe(3) })
}
Enter fullscreen mode Exit fullscreen mode

Tests live next to the code. Removed from production builds automatically.

Vitest vs Jest

Feature Vitest Jest
Config Vite config Separate
ESM Native Transform
Speed 2-10x faster Baseline
Watch Smart (module graph) Pattern matching
TypeScript Native Babel/ts-jest

The Bottom Line

If you use Vite (React, Vue, Svelte, Solid), Vitest is the obvious choice. Same config, faster execution, Jest-compatible API. No reason to use Jest in Vite projects.


Need to automate data collection or build custom scrapers? Check out my Apify actors for ready-made tools, or email spinov001@gmail.com for custom solutions.

Top comments (0)