# Vitest

> Use when writing or modifying Vitest tests to follow best practices for test structure, assertions, mocking, and coverage

- Skill: `tomevault-io/vitest-4` (Agent Skill, multi-file: 2 files)
- Install (CLI): `npx skillmds@latest add tomevault-io/vitest-4`
- Raw SKILL.md: https://api.skillmd.com/api/skills/tomevault-io/vitest-4/raw
- Safety review: pending (external: skill-scanner PASS, skillspector PASS)
- Works with: Claude Code, Claude.ai, OpenAI Codex
- Category: Coding & Dev Tools
- Author: tomevault-io (https://skillmd.com/u/tomevault-io)
- Updated: 2026-09-17
- Page: https://skillmd.com/skills/tomevault-io/vitest-4

---


# Vitest Testing

## Quick Start

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

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

  it('should handle basic case', () => {
    expect(myFunction('input')).toBe('expected');
  });

  it('should throw on invalid input', () => {
    expect(() => myFunction(null)).toThrow('Invalid input');
  });
});
```

## Core Patterns

- **Structure**: `describe` for grouping, `it` for individual tests
- **Assertions**: `expect(value).toBe()`, `.toEqual()`, `.toMatchObject()`, `.toThrow()`
- **Async**: `async/await` or return Promise; use `vi.waitFor()` for polling
- **Mocking**: `vi.fn()`, `vi.spyOn()`, `vi.mock('module')`
- **Setup/Teardown**: `beforeEach`, `afterEach`, `beforeAll`, `afterAll`
- **Snapshots**: `expect(value).toMatchSnapshot()`, update with `-u` flag

## Best Practices

- One assertion concept per test (multiple expects OK if testing same behavior)
- Use descriptive test names: "should [action] when [condition]"
- Avoid test interdependence; each test should be isolated
- Mock external dependencies (APIs, file system, time)
- Use `vi.useFakeTimers()` for time-dependent tests

## Reference Files

- [references/assertions.md](references/assertions.md) - Complete assertion API
- [references/mocking.md](references/mocking.md) - Mocking strategies
- [references/async.md](references/async.md) - Async testing patterns

---
> Converted and distributed by [TomeVault](https://tomevault.io/claim/mcclowes) — claim your Tome and manage your conversions.
<!-- tomevault:4.0:skill_md:2026-04-13 -->

