Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

vitest

БесплатноБез исполняемых скриптовНе проверен

Vitest - Modern TypeScript testing framework with Vite-native performance, ESM support, and TypeScript-first design

bobmatnycот bobmatnyc★ 79 звёзд на GitHub

Об этом скилле

Vitest - Modern TypeScript Testing

Overview

Vitest is a next-generation test framework powered by Vite, designed for modern TypeScript/JavaScript projects. It provides blazing-fast test execution through HMR-based test running, native ESM support, and first-class TypeScript integration.

Key Features:

  • ⚡ Vite-native: Instant HMR-based test execution (10-100x faster than Jest)
  • 🎯 TypeScript-first: Built-in TypeScript support, no configuration needed
  • 🔄 ESM-native: Native ES modules, async/await, top-level await
  • 🧪 Jest-compatible: Compatible API for easy migration
  • 📸 Snapshot testing: Built-in snapshot support
  • 🎨 Component testing: React Testing Library, Vue Test Utils integration
  • 📊 Coverage: Built-in v8/c8 coverage (faster than Istanbul)
  • 🌐 UI mode: Beautiful web UI for test debugging

Installation:

npm install -D vitest
# TypeScript types (usually auto-detected)
npm install -D @vitest/ui  # Optional: UI mode

Basic Setup

1. Configure Vitest

vitest.config.ts:

import { defineConfig } from 'vitest/config';

export default defineConfig({
  test: {
    globals: true,           // Use describe/it/expect globally
    environment: 'node',     // or 'jsdom' for DOM testing
    coverage: {
      provider: 'v8',        // or 'istanbul'
      reporter: ['text', 'json', 'html'],
      exclude: [
        'node_modules/',
        'dist/',
        '**/*.test.ts',
        '**/*.spec.ts',
      ],
    },
    include: ['**/*.{test,spec}.{ts,tsx}'],
    exclude: ['node_modules', 'dist', '.idea', '.git', '.cache'],
  },
});

2. TypeScript Configuration

tsconfig.json:

{
  "compilerOptions": {
    "types": ["vitest/globals"]  // For global describe/it/expect
  }
}

Alternative (without globals):

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

3. Package.json Scripts

{
  "scripts": {
    "test": "vitest run",              // CI mode (single run)
    "test:watch": "vitest",            // Watch mode (default)
    "test:ui": "vitest --ui",          // UI mode
    "test:coverage": "vitest run --coverage"
  }
}

Core Testing Patterns

Basic Test Structure

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

describe('Calculator', () => {
  let calculator: Calculator;

  beforeEach(() => {
    calculator = new Calculator();
  });

  it('adds two numbers correctly', () => {
    const result = calculator.add(2, 3);
    expect(result).toBe(5);
  });

  it('handles negative numbers', () => {
    expect(calculator.add(-5, 3)).toBe(-2);
  });
});

TypeScript Type Testing

import { describe, it, expectTypeOf, assertType } from 'vitest';

interface User {
  id: number;
  name: string;
  email: string;
}

describe('Type Safety', () => {
  it('ensures correct types', () => {
    const user: User = {
      id: 1,
      name: 'Alice',
      email: '[email protected]',
    };

    // Type assertions
    expectTypeOf(user.id).toBeNumber();
    expectTypeOf(user.name).toBeString();
    expectTypeOf(user).toMatchTypeOf<User>();

    // Assert type at compile time
    assertType<User>(user);
  });

  it('checks function return types', () => {
    function getUser(): User {
      return { id: 1, name: 'Bob', email: '[email protected]' };
    }

    expectTypeOf(getUser).returns.toMatchTypeOf<User>();
  });
});

Mocking and Spies

vi.mock for Module Mocking

import { describe, it, expect, vi } from 'vitest';
import { fetchUser } from './api';
import { UserService } from './UserService';

// Mock entire module
vi.mock('./api', () => ({
  fetchUser: vi.fn(),
}));

describe('UserService', () => {
  it('fetches user data', async () => {
    const mockUser = { id: 1, name: 'Alice' };
    vi.mocked(fetchUser).mockResolvedValue(mockUser);

    const service = new UserService();
    const user = await service.getUser(1);

    expect(fetchUser).toHaveBeenCalledWith(1);
    expect(user).toEqual(mockUser);
  });
});

vi.spyOn for Method Spying

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

class Logger {
  log(message: string) {
    console.log(message);
  }
}

describe('Logger Spy', () => {
  it('tracks method calls', () => {
    const logger = new Logger();
    const spy = vi.spyOn(logger, 'log');

    logger.log('Hello');
    logger.log('World');

    expect(spy).toHaveBeenCalledTimes(2);
    expect(spy).toHaveBeenCalledWith('Hello');
    expect(spy).toHaveBeenLastCalledWith('World');

    spy.mockRestore(); // Restore original implementation
  });
});

Mock Implementation

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

describe('Mock Implementation', () => {
  it('provides custom mock implementation', () => {
    const mockFn = vi.fn((x: number) => x * 2);

    expect(mockFn(5)).toBe(10);
    expect(mockFn).toHaveBeenCalledWith(5);

    // Change implementation
Полный SKILL.md на GitHub

Установить vitest в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

Вложенные файлы

CODE_EXAMPLES_INDEX.mdIMPLEMENTATION_SUMMARY.mdmetadata.json

FAQ

Что делает скилл vitest?

Vitest - Modern TypeScript testing framework with Vite-native performance, ESM support, and TypeScript-first design

Как установить скилл vitest?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл vitest запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить vitest с