Skip to content

Vitest - Next Generation Testing Framework

Introduction

Vitest is a blazing fast unit test framework powered by Vite. It provides a complete testing solution with:

  • Instant watch mode
  • Out-of-the-box ESM, TypeScript, and JSX support
  • Multi-threading via workers
  • Filtering, timeouts, and concurrent for test suites

Key Features

Speed

  • Uses Vite's dev server for instant HMR
  • Isolated environment for each test file
  • Smart test detection

Compatibility

  • Jest compatible API
  • Works with most Jest plugins
  • Supports both CommonJS and ESM

Developer Experience

  • Built-in code coverage
  • Snapshot testing
  • UI mode for visualizing tests

Installation

bash
npm install -D vitest

Basic Usage

Create a test file (e.g., sum.test.ts):

ts
import { expect, test } from 'vitest'

test('adds 1 + 2 to equal 3', () => {
  expect(1 + 2).toBe(3)
})

Run tests:

bash
npx vitest

Configuration

Create a vitest.config.ts:

ts
import { defineConfig } from 'vitest/config'

export default defineConfig({
  test: {
    globals: true,
    environment: 'jsdom',
    coverage: {
      provider: 'istanbul'
    }
  }
})

Advanced Features

Mocking

ts
import { vi } from 'vitest'

const fn = vi.fn()
fn('hello')

expect(fn).toHaveBeenCalledWith('hello')

Testing Components

ts
import { mount } from '@vue/test-utils'
import MyComponent from './MyComponent.vue'

test('renders component', () => {
  const wrapper = mount(MyComponent)
  expect(wrapper.text()).toContain('Hello World')
})

Comparison with Jest

FeatureVitestJest
Speed⚡ Fast🐢 Slow
HMR✅ Yes❌ No
ESM Support✅ Native❌ Requires config
TypeScript✅ Built-in❌ Requires ts-jest

Resources

Last updated: