Vitest

Language: JavaScript

Testing

Vitest was created to provide a fast, modern testing solution tightly integrated with Vite's development environment. Its zero-config setup and Vite-native execution allow instant feedback during development, making it ideal for frontend projects with hot module replacement.

Vitest is a blazing fast unit testing framework for Vite projects, designed to be highly compatible with Jest. It supports TypeScript out-of-the-box, snapshots, mocks, and a rich API for testing modern JavaScript and TypeScript applications.

Installation

npm: npm install -D vitest
yarn: yarn add -D vitest
pnpm: pnpm add -D vitest

Usage

Vitest allows developers to write tests using a syntax similar to Jest, including `describe`, `it/test`, `expect`, and supports mocking, snapshots, and parallel execution. It integrates with Vite for fast startup and hot-reload support.

Simple test example

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

describe('sum function', () => {
  it('adds two numbers', () => {
    const sum = (a, b) => a + b;
    expect(sum(1, 2)).toBe(3);
  });
});

Defines a simple test suite and test case that verifies a sum function returns the correct result.

Async test example

import { it, expect } from 'vitest';

it('resolves async value', async () => {
  const fetchData = () => Promise.resolve('data');
  await expect(fetchData()).resolves.toBe('data');
});

Tests an asynchronous function and ensures it resolves to the expected value.

Mocking functions

import { vi, it, expect } from 'vitest';

const myFunc = vi.fn();
myFunc('hello');
expect(myFunc).toHaveBeenCalledWith('hello');

Demonstrates creating a mock function and asserting it was called with specific arguments.

Snapshot testing

import { it, expect } from 'vitest';

it('matches snapshot', () => {
  const user = { name: 'Alice', age: 25 };
  expect(user).toMatchSnapshot();
});

Uses snapshot testing to verify that an object structure does not change unexpectedly.

Testing modules with mocks

import { vi, it, expect } from 'vitest';
import * as api from './api';
vi.mock('./api');
api.fetchData.mockResolvedValue('mocked');

it('uses mocked fetchData', async () => {
  const result = await api.fetchData();
  expect(result).toBe('mocked');
});

Shows how to mock an imported module and control its behavior during tests.

Using beforeEach and afterEach

import { beforeEach, afterEach, it, expect } from 'vitest';
let counter = 0;
beforeEach(() => { counter = 0; });
afterEach(() => { console.log('Test completed'); });
it('increments counter', () => { counter += 1; expect(counter).toBe(1); });

Demonstrates setup and teardown hooks in Vitest tests.

Error Handling

Test failed unexpectedly: Check the expected values and ensure mocks are correctly configured.
Async function not awaited: Ensure asynchronous operations are awaited or return promises from test callbacks.
Module import issues: Verify that Vite's module resolution is correctly set up and paths are valid.

Best Practices

Use Vitest's Vite integration for instant test feedback.

Leverage mocks and spies to isolate unit tests.

Use snapshot testing for UI components or structured objects.

Organize test files logically alongside source files or in a `tests` folder.

Run tests in watch mode during development for fast feedback loops.