vitest

A collection of recommended practices and configuration examples for Vitest, a test runner commonly used with React, Vue, and TypeScript projects.

In plain words
What is it for?
Use it when configuring Vitest tests for a frontend project, including Testing Library integration, aliases, mocks, and coverage.
Why use it?
It provides a consistent setup for browser-like tests, mocks, cleanup, and code-coverage reports.

Cursor rule

Install

Getting it into your agent

One page per mod, every tool's command on it. A separate URL per tool would split the same page into five that compete with each other.

agentmods
npx agentmods add rules/renvia-code/best-cursor-rules/vitest
Clone the repo
git clone --depth 1 https://github.com/Renvia-code/best-cursor-rules
Per session 0 Nothing until a file matches its globs; then the whole rule loads.
When invoked 1,844 The whole file, excluding the scripts and references it only reads on demand.
Security scan A 0 findings. Scan, not verified.
Origin original No closer match found in the catalogue.
Token cost

What it costs to keep this loaded

Counted locally with the o200k_base tokenizer, which is exact for GPT models; Claude uses its own tokenizer and its counts differ. Treat this as one consistent yardstick across the catalogue rather than a bill. Prices are per million input tokens.

ModelPer sessionOnce invoked
Fable 5 $0.00000 $0.01844
Opus 5 $0.00000 $0.00922
Sonnet 5 $0.00000 $0.00369
Haiku 4.5 $0.00000 $0.00184

Measured 2d ago against content hash b884b53028ea, method: parsed. Prices are Anthropic first-party input rates as of 2026-08-30, from the pricing page.

Security

Grade A, and why

vitest scanned grade A with 0 findings against 26 rules in 11 categories — prompt injection, anti-refusal, data exfiltration, privilege escalation, supply chain, agent snooping, system-prompt leakage, SSRF and excessive agency — measured 2d ago.

A static scan of the body, not an audit. Every finding is printed with the line that produced it so you can judge whether it matters here. A mod is markdown that instructs an agent; that is exactly why what it instructs is worth reading.

Nothing flagged

None of the 26 patterns this scan looks for appear in this file: no shell pipes, no recursive deletes, no credential paths, no hidden text, no instruction-override or anti-refusal phrasing, no agent-config snooping. That is not a guarantee, it is the absence of the things that are checkable.

rules/testing/vitest.mdc · 354 lines

How it starts

The opening of the file, as written. The whole thing — 354 lines — stays where its author put it; the contents beside it link to each section on GitHub.

Vitest Best Practices

Overview

Aspect Recommendation
Runner Vitest
UI Testing @testing-library/react
Mocking vi.mock, vi.fn
Coverage c8 or istanbul

Configuration

vitest.config.ts

import { defineConfig } from 'vitest/config'
import react from '@vitejs/plugin-react'
import path from 'path'

export default defineConfig({
  plugins: [react()],
  test: {
    globals: true,
    environment: 'jsdom',
    setupFiles: ['./tests/setup.ts'],
    include: ['**/*.{test,spec}.{ts,tsx}'],
    coverage: {
      provider: 'v8',
      reporter: ['text', 'json', 'html'],
      exclude: ['node_modules/', 'tests/setup.ts'],
    },
  },
  resolve: {
    alias: {
      '@': path.resolve(__dirname, './src'),
    },
  },
})

Test Setup

// tests/setup.ts
import '@testing-library/jest-dom'
import { cleanup } from '@testing-library/react'
import { afterEach, vi } from 'vitest'

// Cleanup after each test
afterEach(() => {
  cleanup()
})

// Mock window.matchMedia
Object.defineProperty(window, 'matchMedia', {
  writable: true,
  value: vi.fn().mockImplementation((query) => ({
    matches: false,
    media: query,
    onchange: null,
    addListener: vi.fn(),
    removeListener: vi.fn(),
    addEventListener: vi.fn(),
    removeEventListener: vi.fn(),
    dispatchEvent: vi.fn(),
  })),
})

Test Structure

Basic Test File

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

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

  it('should do something', () => {
    const result = myFunction(input)
    expect(result).toBe(expectedOutput)
  })

  it('should handle edge case', () => {
    expect(() => myFunction(null)).toThrow('Invalid input')
  })
})

Component Testing

import { describe, it, expect } from 'vitest'
import { render, screen, fireEvent } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { Button } from '@/components/Button'

describe('Button', () => {
  it('renders with text', () => {
    render(<Button>Click me</Button>)
    expect(screen.getByRole('button', { name: 'Click me' })).toBeInTheDocument()
  })

  it('calls onClick when clicked', async () => {
    const user = userEvent.setup()
    const handleClick = vi.fn()
    
    render(<Button onClick={handleClick}>Click me</Button>)
    await user.click(screen.getByRole('button'))
    
    expect(handleClick).toHaveBeenCalledTimes(1)
  })

  it('is disabled when disabled prop is true', () => {
    render(<Button disabled>Click me</Button>)
    expect(screen.getByRole('button')).toBeDisabled()
  })
})

Read the full file on GitHub · 354 lines

Changes

What this file has done since we first saw it

Hashed on every crawl. A supply-chain change to an agent config is a question of when, not whether, so the history is kept rather than the latest state alone.

  1. 2d ago First seen · 354 lines · 0 tokens per session scan A b884b53028ea

Subscribe to this mod's changes

vitest is a cursor rule published in the GitHub repository Renvia-code/best-cursor-rules (12 stars, last pushed 9mo ago), licensed CC0-1.0. It costs nothing until one of its globs matches a file; then it loads 1,844 tokens. A static security scan graded it A with 0 findings. No closer match exists in the catalogue, so it is treated as the original; first seen 2026-08-30.