Detalle del Skill
vitest-testing-patterns
Vitest and React Testing Library test patterns.
Revisar antes de usar
La revisión automática comprueba relevancia, no seguridad ni respaldo. Lee las instrucciones de la fuente antes de usar este Skill.
SKILL.md
Este extracto es una copia guardada durante la revisión. La fuente externa contiene la versión completa y actual.
---
name: vitest-testing-patterns
description: Write tests using Vitest and React Testing Library. Use when creating unit tests, component tests, integration tests, or mocking dependencies. Activates for test file creation, mock patterns,
coverage, and testing best practices.
allowed-tools: Read,Write,Edit,Bash(npm:*,npx:*)
metadata:
category: Code Quality & Testing
tags:
- testing
- code
- automation
- jest
- react
pairs-with:
- skill: test-automation-expert
reason: Vitest unit testing is one layer in a comprehensive test automation strategy
- skill: playwright-e2e-tester
reason: Unit tests (Vitest) and E2E tests (Playwright) form complementary test pyramid layers
- skill: react-performance-optimizer
reason: Component test patterns verify that performance optimizations preserve correct behavior
- skill: typescript-advanced-patterns
reason: Type-safe test utilities and mock factories leverage advanced TypeScript patterns
---
# Vitest Testing Patterns
This skill helps you write effective tests using Vitest and React Testing Library following project conventions.
## When to Use
✅ **USE this skill for:**
- Writing unit tests for utilities and functions
- Creating component tests with React Testing Library
- Setting up mocks for API calls, databases, or external services
- Integration testing patterns
- Understanding test coverage and CI setup
❌ **DO NOT use for:**
- Jest-specific patterns → similar but check Jest docs for differences
- End-to-end testing → use Playwright or Cypress skills
- Performance testing → use dedicated performance tools
- API contract testing → use OpenAPI/Pact patterns
## Test Infrastructure
**Configuration**: `vitest.config.ts`
- Environment: jsdom
- Setup file: `src/test/setup.ts`
- Coverage: v8 provider
**Commands**:
```bash
npm test # Watch mode
npm run test:run # Single run
npm run test:coverage # With coverage
```
## File Organization
```
src/
├── app/api/__tests__/ # API route tests
├── components/__tests__/ # Component tests
├── lib/__tests__/ # Library/utility tests
└── lib/{feature}/__tests__/ # Feature-specific tests
```
Name tests as `{name}.test.ts` or `{name}.test.tsx`.
## Core Testing Patterns
### 1. API Route Tests
```typescript
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { GET, POST } from '../route';
import { NextRequest } from 'next/server';
// Mock dependencies
vi.mock('@/lib/auth', () => ({
getSession: vi.fn(),
}));
vi.mock('@/db', () => ({
db: {
select: vi.fn().mockReturnThis(),
from: vi.fn().mockReturnThis(),
where: vi.fn().mockResolvedValue([]),
},
}));
describe('GET /api/feature', () => {
beforeEach(() => {
vi.clearAllMocks();
});
it('returns 401 when not authenticated', async () => {
vi.mocked(getSession).mockResolvedValue(null);
const request = new NextRequest('http://localhost/api/feature');
const response = await GET(request);
expect(response.status).toBe(401);
});
it('returns data when authenticated', async () => {
vi.mocked(getSession).mockResolvedValue({ userId: 'user-123' });
vi.mocked(db.select).mockReturnValue({
from: vi.fn().mockReturnValue({
where: vi.fn().mockResolvedValue([{ id: '1', name: 'Test' }]),
}),
});
const request = new NextRequest('http://localhost/api/feature');
const response = await GET(request);
const data = await response.json();
expect(response.status).toBe(200);
expect(data).toHaveLength(1);
});
});
```
### 2. Component Tests
```typescript
import { describe, it, expect, vi } from 'vitest';
import { render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { FeatureComponent } from '../FeatureComponent';
// Mock hooks
vi.mock('@/hooks/useAuth', () => ({
useAuth: vi.fn().mockReturnValue({
user: { id: 'user-123', name: 'Test User' },
isLoading: false,
Leer la fuente completa en GitHub (abre una página externa)