💻 Programming

Vitest

Vite-native Unit Test Framework

A fast Vite-based testing framework. Offers a Jest-compatible API for easy migration and native ESM support for fast execution.

📖 Detailed Explanation

Vitest is a next-generation unit testing framework based on Vite. Since its first release in 2022 it has grown quickly and is now established as the official testing solution of the Vite ecosystem. It reuses Vite's transform pipeline and configuration as they are, ensuring consistency between the development and test environments.

One of Vitest's biggest advantages is its Jest-compatible API. APIs used in Jest such as describe, it, expect, beforeEach, and afterEach can be used almost unchanged, so existing Jest test code can be migrated with minimal changes. Mocking APIs such as jest.fn() and jest.mock() are also provided in similar form as vi.fn() and vi.mock().

Native support for ESM (ECMAScript Modules) is Vitest's core strength. While Jest is CommonJS-based and needs complex configuration for ESM support, Vitest uses Vite's ESM-based dev server to support ESM without extra configuration. As a result, test startup time is dramatically shorter, and re-runs in watch mode are also very fast.

In practice, Vitest provides a modern development experience, including instant test re-runs using HMR (Hot Module Replacement), zero-config support for TypeScript and JSX, and parallel test execution through multithreaded workers. In Vite-based projects (Vue, React, Svelte, etc.) in particular, you can use your vite.config.ts settings as they are, avoiding duplicated configuration.

💻 Code Example

Basic test
// sum.ts
export function sum(a: number, b: number): number {
    return a + b;
}

// sum.test.ts
import { describe, it, expect, beforeEach } from 'vitest';
import { sum } from './sum';

describe('sum 함수', () => {
    it('두 숫자를 더한다', () => {
        expect(sum(1, 2)).toBe(3);
    });

    it('음수도 처리한다', () => {
        expect(sum(-1, 1)).toBe(0);
        expect(sum(-1, -1)).toBe(-2);
    });

    // 테이블 기반 테스트 (test.each)
    it.each([
        [1, 1, 2],
        [2, 2, 4],
        [0, 0, 0],
    ])('sum(%i, %i) = %i', (a, b, expected) => {
        expect(sum(a, b)).toBe(expected);
    });
});
Mocking
// api.ts
export async function fetchUser(id: string) {
    const response = await fetch(`/api/users/${id}`);
    return response.json();
}

// userService.ts
import { fetchUser } from './api';

export async function getUserName(id: string): Promise<string> {
    const user = await fetchUser(id);
    return user.name;
}

// userService.test.ts
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { getUserName } from './userService';

// 모듈 모킹
vi.mock('./api', () => ({
    fetchUser: vi.fn()
}));

import { fetchUser } from './api';

describe('getUserName', () => {
    beforeEach(() => {
        vi.clearAllMocks();
    });

    it('사용자 이름을 반환한다', async () => {
        // 모킹된 함수의 반환값 설정
        vi.mocked(fetchUser).mockResolvedValue({
            id: '1',
            name: '홍길동'
        });

        const name = await getUserName('1');

        expect(name).toBe('홍길동');
        expect(fetchUser).toHaveBeenCalledWith('1');
        expect(fetchUser).toHaveBeenCalledTimes(1);
    });

    it('API 에러 시 예외를 던진다', async () => {
        vi.mocked(fetchUser).mockRejectedValue(new Error('Network Error'));

        await expect(getUserName('1')).rejects.toThrow('Network Error');
    });
});
Snapshot testing
// component.test.ts
import { describe, it, expect } from 'vitest';

// 객체 스냅샷
describe('스냅샷 테스트', () => {
    it('사용자 객체 스냅샷', () => {
        const user = {
            id: 1,
            name: '홍길동',
            email: 'hong@example.com',
            roles: ['admin', 'user'],
            createdAt: new Date('2024-01-01')
        };

        // 첫 실행 시 스냅샷 생성, 이후 비교
        expect(user).toMatchSnapshot();
    });

    it('인라인 스냅샷', () => {
        const config = {
            theme: 'dark',
            language: 'ko'
        };

        // 인라인 스냅샷 - 코드에 직접 저장
        expect(config).toMatchInlineSnapshot(`
          {
            "language": "ko",
            "theme": "dark",
          }
        `);
    });

    // React 컴포넌트 스냅샷 (with @testing-library/react)
    it('React 컴포넌트 렌더링 스냅샷', () => {
        const html = '<button class="btn-primary">제출</button>';
        expect(html).toMatchSnapshot();
    });
});

// vitest.config.ts 설정 예시
// export default defineConfig({
//     test: {
//         snapshotFormat: {
//             printBasicPrototype: false
//         }
//     }
// });

🗣️ Examples of Practical Conversations

Discussing a switch from Jest to Vitest in a team meeting

"Switching from Jest to Vitest cuts test run time by more than half. Our project is already Vite-based, so we can use vite.config.ts as is, and the API is almost identical to Jest, so migration is simple. Just change to vi.mock() and change the import path to vitest, and most things work."

In a CI/CD pipeline optimization meeting

"When running Vitest in GitHub Actions, generate a JUnit report with the --reporter=junit option and a coverage report with --coverage. Parallel execution is the default, and you can also choose a worker pool mode with the --pool=threads option. Don't forget to disable watch mode in CI with the --run flag."

In a technical interview

"Vitest is faster than Jest because it uses Vite's ESM-based dev server. Jest transpiles to CommonJS before testing, but Vitest handles ESM natively, so there's no bundling overhead. It also uses HMR to re-run only the changed files, so watch mode is especially fast."

In a code review - improving test code

"In this test, the vi.mock() call is repeated in every test case. It's cleaner to call it once at the top of the file and reset with vi.clearAllMocks() in beforeEach. Also check whether type inference works well in vi.mocked(fetchUser).mockResolvedValue(). If it doesn't, specify the generic explicitly with vi.mocked (with a type argument). Finally, when using the await expect().rejects.toThrow() pattern in async tests, never forget to add await."

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

⚠️ Cautions

1
Subtle differences from Jest

Most Jest APIs are compatible, but there are some differences. jest.fn() must be changed to vi.fn(), and jest.mock() to vi.mock(). Also, vi.mock() is hoisted to the top of the file, so use vi.doMock() if you need dynamic mocking. Timer-related APIs may also behave slightly differently.

2
Browser test setup

Vitest runs in a Node.js environment by default. If you need DOM testing, you must set environment: 'jsdom' or 'happy-dom' in vitest.config.ts. If you need real browser testing, use Playwright or WebdriverIO together with the @vitest/browser package.

3
Coverage setup

For coverage reports, you must separately install the @vitest/coverage-v8 or @vitest/coverage-istanbul package. v8 is faster, but istanbul can provide more accurate results. In CI environments, set coverage.reporter to ['text', 'json', 'html'] to generate reports in various formats.

🔗 Related Terms

📚 Learn More