Skip to main content
skill CX Codex

vitest-testing · secondsky — Claude Code skill: Vitest tests

A skill that teaches your agent to write unit and integration tests with Vitest in TypeScript and JavaScript projects. Handy when you need config, mocks and coverage set up fast.

Install into Claude Code · Skills CLI (Vercel) All methods and platforms ↓
npx skills add secondsky/claude-skills --skill vitest-testing -a claude-code
Open on GitHub

What vitest-testing does

The skill hands the agent working knowledge of Vitest: setting up vitest.config.ts, writing describe/it/expect, parametrising tests with describe.each, mocking functions and modules through vi, and controlling timers and system time. There is a coverage section using the v8 provider with thresholds for lines, functions and branches.

Inside you get config examples, an assertion cheat sheet, module and timer mocking, and integration tests via supertest. A practices block covers one test file per source file, grouping with describe(), and sharing expensive fixtures in beforeAll(). It advises aiming for around 80% coverage rather than chasing 100%.

The command examples lean on Bun (bun test, bun add -d vitest), though npm install -D vitest is shown too. If your project does not use Bun, swap the run commands for your own. The integration examples pull in supertest — worth checking whether it is already in your dependencies.

What it helps with

  • set up vitest.config.ts with coverage and thresholds
  • mock a module and reset mocks between tests
  • test async code with resolves and rejects
  • freeze system time inside a test
  • write an integration test for an HTTP endpoint

Example prompts for the agent

  • Set up Vitest in this project: create vitest.config.ts with v8 coverage and 80% thresholds
  • Write tests for src/utils/math.ts using describe.each for parametrisation
  • Mock the ./api module and assert that fetchUser is called once

How to install vitest-testing

1Skills CLI (Vercel)

npx skills add secondsky/claude-skills --skill vitest-testing -a claude-code

2Manually: put the files in place

~/.claude/skills/vitest-testing/SKILL.md

Copy the whole skill folder; for one project use .claude/skills/vitest-testing/

Step by step, with commands for each platform: How to install skills in Claude Code: five ways

Questions about vitest-testing

How do I install vitest-testing in Claude?

Run npx skills add secondsky/claude-skills --skill vitest-testing -a claude-code. The skill file lands at ~/.claude/skills/vitest-testing/SKILL.md.

What does vitest-testing do?

It gives the agent knowledge for testing TS/JS projects with Vitest: configuration, assertions, function and module mocks, fake timers, coverage and integration tests.

Does the skill require Bun?

The command examples use Bun, but npm install -D vitest is shown as well. With another package manager you will need to adapt the test run commands.

Source text

SKILL.md · MIT
---
name: vitest-testing
description: Modern TypeScript/JavaScript testing with Vitest. Fast unit and integration tests, native ESM support, Vite-powered HMR, and comprehensive mocking. Use for testing TS/JS projects.
allowed-tools: Bash, Read, Edit, Write, Grep, Glob, TodoWrite
license: MIT
---

# Vitest Testing

Expert knowledge for testing JavaScript/TypeScript projects using Vitest - a blazingly fast testing framework powered by Vite.

## Quick Start

### Installation

```bash
# Using Bun (recommended)
bun add -d vitest

# Using npm
npm install -D vitest
```

### Configuration

```typescript
// vitest.config.ts
import { defineConfig } from 'vitest/config'

export default defineConfig({
  test: {
    globals: true,
    environment: 'node', // or 'jsdom'
    coverage: {
      provider: 'v8',
      reporter: ['text', 'json', 'html'],
      thresholds: { lines: 80, functions: 80, branches: 80 },
    },
    include: ['**/*.{test,spec}.{js,ts,jsx,tsx}'],
  },
})
```

## Running Tests

```bash
# Run all tests (prefer bun)
bun test

# Watch mode (default)
bun test --watch

# Run once (CI mode)
bun test --run

# With coverage
bun test --coverage

# Specific file
bun test src/utils/math.test.ts

# Pattern matching
bun test --grep="calculates sum"

# UI mode (interactive)
bun test --ui

# Verbose output (in Vitest 2+, --reporter=verbose prints a flat list;
# use --reporter=tree for the hierarchical tree view)
bun test --reporter=verbose
```

## Writing Tests

### Basic Structure

```typescript
import { describe, it, expect, beforeEach, afterEach } from 'vitest'
import { add, subtract } from './math'

describe('Math utilities', () => {
  beforeEach(() => {
    // Setup before each test
  })

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

  it('subtracts two numbers correctly', () => {
    expect(subtract(5, 3)).toBe(2)
  })
})
```

### Parametrized Tests

```typescript
describe.each([
  { input: 2, expected: 4 },
  { input: 3, expected: 9 },
])('square function', ({ input, expected }) => {
  it(`squares ${input} to ${expected}`, () => {
    expect(square(input)).toBe(expected)
  })
})
```

## Assertions

```typescript
// Equality
expect(value).toBe(expected)
expect(value).toEqual(expected)

// Truthiness
expect(value).toBeTruthy()
expect(value).toBeNull()
expect(value).toBeDefined()

// Numbers
expect(number).toBeGreaterThan(3)
expect(number).toBeCloseTo(0.3, 1)

// Strings/Arrays
expect(string).toMatch(/pattern/)
expect(array).toContain(item)

// Objects
expect(object).toHaveProperty('key')
expect(object).toMatchObject({ a: 1 })

// Exceptions
expect(() => throwError()).toThrow('message')

// Promises
await expect(promise).resolves.toBe(value)
await expect(promise).rejects.toThrow()
```

## Mocking

### Function Mocks

```typescript
import { vi } from 'vitest'

const mockFn = vi.fn()
mockFn.mockReturnValue(42)
mockFn.mockResolvedValue('async result')
mockFn.mockImplementation((x) => x * 2)

expect(mockFn).toHaveBeenCalled()
expect(mockFn).toHaveBeenCalledWith('arg')
```

### Module Mocking

```typescript
vi.mock('./api', () => ({
  fetchUser: vi.fn(() => ({ id: 1, name: 'Test User' })),
}))

import { fetchUser } from './api'

beforeEach(() => {
  vi.clearAllMocks()
})
```

### Timers

```typescript
beforeEach(() => vi.useFakeTimers())
afterEach(() => vi.restoreAllMocks())

it('advances timers', () => {
  const callback = vi.fn()
  setTimeout(callback, 1000)
  vi.advanceTimersByTime(1000)
  expect(callback).toHaveBeenCalledOnce()
})

it('mocks dates', () => {
  const date = new Date('2024-01-01')
  vi.setSystemTime(date)
  expect(Date.now()).toBe(date.getTime())
})
```

## Coverage

```bash
# Generate coverage report
bun test --coverage

# HTML report
bun test --coverage --coverage.reporter=html
open coverage/index.html

# Check against thresholds
bun test --coverage --coverage.thresholds.lines=90
```

## Integration Testing

```typescript
import request from 'supertest'
import { app } from './app'

describe('API endpoints', () => {
  it('creates a user', async () => {
    const response = await request(app)
      .post('/api/users')
      .send({ name: 'John' })
      .expect(201)

    expect(response.body).toMatchObject({
      id: expect.any(Number),
      name: 'John',
    })
  })
})
```

## Best Practices

- One test file per source file: `math.ts` → `math.test.ts`
- Group related tests with `describe()` blocks
- Use descriptive test names
- Mock only external dependencies
- Use `concurrent` tests for independent async tests
- Share expensive fixtures with `beforeAll()`
- Aim for 80%+ coverage but don't chase 100%

## See Also

- `test-quality-analysis` - Detecting test smells
- `playwright-testing` - E2E testing
- `mutation-testing` - Validate test effectiveness

© secondsky · MIT · secondsky/claude-skills

Similar skills

Everything for Testing and QA →

vitest-testing by other authors comes first.

From the same set89

tailwind-v4-shadcn Sets up Tailwind CSS v4 with shadcn/ui, Vite, and React. Solves broken CSS variables, theme switching errors, and v4 migration pitfalls. CX Codex +1 8,100installs code-review A skill that sets rules for code review: how to take feedback, when to call the code-reviewer subagent, and how to avoid claiming success without proof. CX Codex +1 530installs mcp-management Manages Model Context Protocol servers, catalogues tools into JSON, and executes operations via Gemini CLI or Bun scripts without bloating the context. CX Codex +1 382installs aceternity-ui This skill gives your agent the Aceternity UI playbook: 100+ animated React components for Next.js with Tailwind. Useful for hero sections, parallax and 3D effects. CX Codex +1 1,500installs motion A skill that feeds your agent the Motion (Framer Motion) docs for React: drag-and-drop, scroll effects, layout transitions. Useful when the agent guesses at props. CX Codex +1 1,100installs playwright A Playwright skill for browser automation and end-to-end testing. It finds your running dev server and writes the test script for the task. CX Codex +1 1,000installs api-testing A skill that gets your agent writing HTTP API tests: Supertest for TypeScript, httpx and pytest for Python. Covers REST, GraphQL and error handling. CX Codex +1 890installs rest-api-design This skill hands your agent a set of REST conventions: resource names, HTTP methods, status codes and JSON response shape. Useful when you start a new API or want existing endpoints to match. CX Codex +1 586installs

Project sponsors

Companies that keep this analytics open
Gold sponsor

Impressions, clicks and code copies — open statistics. We keep the numbers public for the same reason NeBlask itself is public. Become a sponsor