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.
npm install -D vitestyarn add -D vitestpnpm add -D vitestVitest 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.
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.
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.
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.
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.
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.
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.
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.