6. Vitest: The Modern Test Runner
Vitest is a modern test runner built on Vite. It's fast, lightweight, and designed for the modern JavaScript ecosystem. Vitest is a drop-in replacement for Jest with better performance and native ESM support. Understanding Vitest is essential for modern JavaScript projects.
The key insight is that Vitest is designed for speed. It leverages Vite's fast dev server and native ESM support to run tests instantly. Vitest is the future of JavaScript testing, and many projects are migrating from Jest to Vitest for the performance benefits.
This module covers Vitest setup, features, and how it compares to Jest.
Vitest Features
Vitest provides all the features you expect from a modern test runner: describe, test, expect, matchers, spies, mocks, and async testing. It's compatible with Jest's API, making migration easy. Key advantages over Jest: native ESM support, no need for babel config, faster execution, and watch mode with hot reload.
Vitest also supports: in-browser testing, snapshot testing, coverage reports, and parallel test execution. It integrates with most testing libraries including React Testing Library, Vue Test Utils, and more. Understanding Vitest is essential for modern JavaScript testing.
Try It Yourself: Setting Up Vitest
Follow these steps to set up Vitest in a project.
Step 1: Create a projectnpm create vite@latest vitest-demo -- --template vanilla<br>cd vitest-demo<br>npm install
Step 2: Install Vitestnpm install --save-dev vitest @vitest/ui
Step 3: Configure Vitest
Add to vite.config.js:import { defineConfig } from <strong><code>vite;
export default defineConfig({
test: {
globals: true,
environment: jsdom,
include: [**/*.{test,spec}.{js,ts,jsx,tsx}],
},
});
Step 4: Create a function and test// math.js<br>export const add = (a, b) => a + b;<br>export const multiply = (a, b) => a * b;// math.test.js<br>import { describe, it, expect } from <strong><code>vitest;
import { add, multiply } from ./math;
describe(math functions, () => {
it(adds correctly, () => {
expect(add(2, 3)).toBe(5);
});
it(multiplies correctly, () => {
expect(multiply(2, 3)).toBe(6);
});
});
Step 5: Add a test script
Add to package.json:<strong><code>scripts: {
test: vitest,
test:ui: vitest --ui,
test:coverage: vitest --coverage
}
Step 6: Run the testsnpm run test
Try It Yourself: Create a component and test it with Vitest and React Testing Library. Observe how fast Vitest runs compared to Jest.
Knowledge Check
Ready to test your understanding of 6. Vitest: The Modern Test Runner?