Skip to main content
skill CX Codex

vitest-testing · oakoss — Claude Code skill: what it does, how to install

vitest-testing adds Vitest patterns and best practices to Claude Code. Helps write reliable unit, component, and hook tests without typical async mistakes.

MIT 226 installs ★ 29 updated 2026-08-17

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

What vitest-testing does

The skill equips coding agents with syntax rules and conventions for the Vitest framework. It steers the model toward native ESM workflows, structured suites using describe or it, parameterized test runs, and assertions with expect.

Inside are practical guides for module mocking with vi.mock, function spies via vi.fn, and global stubbing. For frontend code, it enforces proper React Testing Library habits: querying elements by accessibility role, setting up userEvent before interactions, and testing custom hooks through renderHook.

Vitest handles unit, component, and integration checks cleanly. For full browser end-to-end flows, this skill is not intended; the author points directly to Playwright instead.

What it helps with

  • write unit tests with clean Vitest assertions
  • test custom React hooks using renderHook
  • isolate dependencies using vi.mock and vi.spyOn
  • prevent timing issues in async component tests

Example prompts for the agent

  • Write Vitest unit tests for the cart calculation helper and mock external API calls.
  • Test the login form component using React Testing Library role queries and user-event.
  • Create integration tests for the authentication hook with renderHook and verify state updates.

How to install vitest-testing

1Skills CLI (Vercel)

npx skills add oakoss/agent-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 Code?

Run npx skills add oakoss/agent-skills --skill vitest-testing -a claude-code. The skill file will be placed in ~/.claude/skills/vitest-testing/SKILL.md.

What does vitest-testing do?

It instructs the agent on proper Vitest patterns, assertion styles, mock setups, and React Testing Library conventions to write accurate tests.

Can I use vitest-testing for end-to-end tests?

No, it focuses strictly on unit, component, and integration testing. The documentation recommends using Playwright for browser end-to-end scenarios.

Source text

SKILL.md · MIT
---
name: vitest-testing
description: |
  Vitest testing framework for unit, component, and integration tests. Covers test structure (describe/it/test.each), assertions with expect, lifecycle hooks, mocking (vi.fn/vi.mock/vi.spyOn), React Testing Library patterns, hook testing with renderHook, user-event interactions, async utilities, configuration, workspace setup, coverage, and advanced patterns like in-source testing and concurrent execution. Also covers CLI commands, test filtering, tags, sharding, fixtures with test.extend, and fixture scoping.

  Use when writing unit tests, component tests, integration tests, or testing React hooks. Use for test configuration, mocking modules, testing async behavior, snapshot testing, or setting up test coverage.
license: MIT
metadata:
  author: oakoss
  version: '1.2'
  source: 'https://vitest.dev/'
user-invocable: false
---

# Vitest Testing

## Overview

Vitest is a Vite-native unit testing framework that shares the same configuration and plugin ecosystem. Built for speed with native ESM support, hot module replacement for tests, and parallel execution.

**When to use:** Unit tests, component tests, integration tests, hook tests, in-source tests. Testing React components with React Testing Library. Testing TanStack Query/Router/Form patterns.

**When NOT to use:** End-to-end testing (use Playwright), visual regression testing (use Percy/Chromatic), load testing (use k6).

## Quick Reference

| Pattern             | API                                             | Key Points                          |
| ------------------- | ----------------------------------------------- | ----------------------------------- |
| Test structure      | `describe('suite', () => {})`                   | Organize related tests              |
| Single test         | `test('behavior', () => {})` or `it()`          | Both are aliases                    |
| Parameterized tests | `test.each([...])('name', (arg) => {})`         | Run same test with different inputs |
| Concurrent tests    | `test.concurrent('name', async () => {})`       | Run tests in parallel               |
| Skip test           | `test.skip('name', () => {})` or `skipIf(cond)` | Conditionally skip tests            |
| Only test           | `test.only('name', () => {})`                   | Run specific test for debugging     |
| Assertions          | `expect(value).toBe(expected)`                  | Compare primitive values            |
| Deep equality       | `expect(obj).toEqual(expected)`                 | Compare objects/arrays              |
| Async assertions    | `await expect(promise).resolves.toBe(value)`    | Test promise resolution             |
| Before each test    | `beforeEach(() => {})`                          | Setup before each test              |
| After each test     | `afterEach(() => {})`                           | Cleanup after each test             |
| Mock function       | `vi.fn()`                                       | Create spy function                 |
| Mock module         | `vi.mock('./module')`                           | Replace entire module               |
| Spy on method       | `vi.spyOn(obj, 'method')`                       | Track calls to existing method      |
| Clear mocks         | `vi.clearAllMocks()`                            | Clear call history                  |
| Fake timers         | `vi.useFakeTimers()`                            | Control setTimeout/setInterval      |
| Render component    | `render(<Component />)`                         | Mount React component for testing   |
| Query by role       | `screen.getByRole('button')`                    | Find elements by accessibility role |
| User interaction    | `await user.click(element)`                     | Simulate user events                |
| Wait for change     | `await waitFor(() => expect(...))`              | Wait for async changes              |
| Find async element  | `await screen.findByText('text')`               | Query + wait combined               |
| Render hook         | `renderHook(() => useHook())`                   | Test custom hooks                   |
| Update hook props   | `rerender(newProps)`                            | Re-render hook with new props       |
| Snapshot            | `expect(value).toMatchSnapshot()`               | Compare against saved snapshot      |
| Inline snapshot     | `expect(value).toMatchInlineSnapshot()`         | Snapshot stored in test file        |
| CLI run once        | `vitest run`                                    | Single run, no watch                |
| Run changed tests   | `vitest --changed`                              | Tests affected by git changes       |
| Filter by name      | `vitest -t "pattern"`                           | Grep test names                     |
| Soft assertions     | `expect.soft(value).toBe(x)`                    | Continue on failure, collect all    |
| Poll assertions     | `await expect.poll(() => val).toBe(x)`          | Retry until passing                 |
| Test fixtures       | `const test = base.extend<F>({...})`            | Reusable setup via test.extend      |
| Hoisted mocks       | `vi.hoisted(() => ({ fn: vi.fn() }))`           | Variables for vi.mock factory       |
| Shard tests         | `vitest --shard 1/3`                            | Split across CI workers             |
| Tags                | `test('name', { tags: ['slow'] }, ...)`         | Filter with --tags-filter           |
| Stub globals        | `vi.stubGlobal('fetch', vi.fn())`               | Replace global objects cleanly      |

## Common Mistakes

| Mistake                                | Correct Pattern                                     |
| -------------------------------------- | --------------------------------------------------- |
| Using `getBy` for async content        | Use `findBy` or `waitFor` for async                 |
| Testing implementation details         | Test behavior and public API                        |
| Using `getByTestId` as first choice    | Prefer `getByRole`, `getByLabelText`, `getByText`   |
| Missing `userEvent.setup()`            | Always call `const user = userEvent.setup()` first  |
| Shared state between tests             | Use `beforeEach` to reset or create fresh instances |
| Not cleaning up mocks                  | Use `vi.clearAllMocks()` in `afterEach`             |
| Mocking too much                       | Only mock external dependencies and APIs            |
| Not disabling retries in tests         | Set `retry: false` for TanStack Query tests         |
| Immediate assertions on async          | Use `await waitFor()` or `findBy` queries           |
| Creating QueryClient in render         | Create once in wrapper or use `useState`            |
| Testing library code                   | Trust the library, test your usage                  |
| Not awaiting user events               | All `user.*` methods return promises                |
| Using `act` manually                   | `userEvent` and Testing Library handle this         |
| Inline select without memoization      | Extract to stable function for TanStack Query       |
| Variables in vi.mock factory           | Use `vi.hoisted()` to declare mock variables        |
| Single `expect` for multiple checks    | Use `expect.soft()` to collect all failures         |
| `setTimeout` in tests for async waits  | Use `expect.poll()` or `vi.waitFor()`               |
| Manual `beforeEach` for reusable setup | Use `test.extend` fixtures for composable setup     |

## Delegation

- **Test discovery**: For finding untested code paths, use `Explore` agent
- **Coverage analysis**: For full coverage review, use `Task` agent
- **E2E testing**: If `playwright` skill is available, delegate E2E testing to it
- **Code review**: After writing tests, delegate to `code-reviewer` agent

## References

- [Test fundamentals: structure, assertions, lifecycle hooks](references/test-fundamentals.md)
- [Mocking: vi.fn, vi.mock, vi.spyOn, module mocking](references/mocking.md)
- [Component testing: React Testing Library, queries, user-event](references/component-testing.md)
- [Hook testing: renderHook, async hooks, TanStack patterns](references/hook-testing.md)
- [Test setup: jest-dom matchers, cleanup, custom render, MSW, polyfills](references/test-setup.md)
- [Configuration: vitest.config.ts, workspace, coverage, reporters](references/configuration.md)
- [Advanced patterns: snapshots, concurrent tests, in-source, type testing](references/advanced-patterns.md)
- [CLI and filtering: commands, watch mode, tags, sharding](references/cli-and-filtering.md)
- [Fixtures and context: test.extend, scoping, auto fixtures, injection](references/fixtures-and-context.md)

© oakoss · MIT · oakoss/agent-skills

Similar skills

All skills for Testing and QA →

vitest-testing by other authors comes first.

vitest-testing secondsky vitest-testing — a skill for Claude Code, Codex, Cursor, GitHub Copilot, Gemini CLI, and OpenCode that loads Vitest knowledge into the agent for unit and integration testing in TypeScript and JavaScript projects. CX Codex +1 1,300installs vitest-testing existential-birds vitest-testing — a skill that hands your coding agent a Vitest reference: assertions, mocks, async matchers, config. Useful when the project already runs on Vitest. CX Codex +1 473installs vitest-unit-testing przeprogramowani vitest-unit-testing is a Claude Code rule for writing Vitest unit tests. It guides module mocking and React component test structure. CX Codex +1 ★ 267repo stars vitest-testing-patterns curiositech vitest-testing-patterns provides Vitest and React Testing Library conventions for coding agents. Useful for writing component tests, API route checks, and dependency mocks. CX Codex +1 373installs vitest-unit-testing-cursorrules-prompt-file PatrickJS vitest-unit-testing-cursorrules-prompt-file is a Cursor rule that configures AI to write Vitest unit tests in TypeScript or JavaScript. It runs on project files, mocks dependencies before imports, and groups tests in describe blocks. CX Codex +1 ★ 41,178repo stars vitest pproenca Equips your coding agent with 44 prioritized rules for writing, debugging, and speeding up Vitest suites. Covers async patterns, mocks, and test isolation. CX Codex +1 7,800installs writing-tests spencerpauly writing-tests inspects existing code, detects your test runner, and drafts unit and integration tests with mocks and edge cases. CX Codex +1 550installs vitest-skill TestMu AI Generates Vitest unit tests for JavaScript and TypeScript projects. Provides patterns for vi mocking and React component testing. CX Codex +1 506installs

From the same set106

The whole set →
application-security application-security walks your code and design through OWASP Top 10 and STRIDE, then hands over a pre-deploy checklist plus the compliance angles for GDPR, HIPAA, SOC 2 and PCI-DSS. CX Codex +1 287installs drizzle-orm Equips coding agents with schema conventions, query patterns, and migration workflows for Drizzle ORM across PostgreSQL, MySQL, and SQLite. CX Codex +1 263installs brand-designer brand-designer is a Claude Code skill for building visual brand identities, from logos to brand guidelines. It responds to requests for palettes, typography systems, and social media templates. CX Codex +1 242installs tailwind A Tailwind CSS v4 skill for themes, components, dark mode, container queries, v3 migrations, shadcn/ui, and build troubleshooting. CX Codex +1 233installs content-humanizer content-humanizer rewrites model-written drafts so they read like a person wrote them: sentence rhythm, tone, and the hedging that gives AI text away. CX Codex +1 225installs zod-validation zod-validation guides AI coding agents through Zod v4 schema validation in TypeScript. Helps write schemas, parse incoming payloads, and generate JSON Schema definitions. CX Codex +1 222installs tanstack-form This skill guides TanStack Form v1 usage in React, covering state, validation, and submission. Use it for complex forms and changing field lists. CX Codex +1 222installs knowledge-graph-builder The knowledge-graph-builder skill guides knowledge-graph design, graph database choice, and graph-plus-vector retrieval. Use it for Graph RAG, entity resolution, and fact checks. CX Codex +1 222installs

Project sponsors

Companies that keep this analytics open