skills/vitest-testing-patterns/SKILL.md
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.
npx skillsauth add curiositech/windags-skills vitest-testing-patternsInstall this skill globally with one command. Works with Claude Code, Cursor, and Windsurf.
3 of 9 scanners reported clean
Some scanners were skipped, did not run, or reported a non-clean status. Review each row below.
Write effective tests using Vitest and React Testing Library following project conventions.
If testing authentication flows:
getSession() → test 401/200 responsesuseAuth → test loading/authenticated/unauthenticated statesIf testing async operations:
waitFor() for state changes, mock fetch/axiosuserEvent.setup() + await user.click()vi.useFakeTimers() + vi.advanceTimersByTime()If testing form interactions:
getByRole('textbox') + userEvent.type()getByLabelText() for accessibilityIf testing error boundaries:
If choosing mock strategy:
vi.mock('@/lib/api'))Mock Pollution: Tests affect each other due to shared mock state
vi.clearAllMocks() in beforeEach() or afterEach()Over-Mocking: Mocking too much implementation detail, tests become brittle
Async Race Conditions: Tests fail sporadically due to timing issues
waitFor() or findBy* queries instead of getBy* for async contentQuery Priority Violations: Using low-priority queries when accessible ones exist
getByTestId or querySelector for interactive elementsgetByRole('button'), getByLabelText(), etc.Mock Implementation Drift: Mocks don't match real API changes
Testing a form component with validation and API submission:
// 1. SETUP - Mock dependencies at module level
vi.mock('@/hooks/useAuth', () => ({
useAuth: vi.fn().mockReturnValue({
user: { id: 'user-123' },
isLoading: false,
}),
}));
vi.mock('@/lib/api', () => ({
submitForm: vi.fn(),
}));
// 2. DECISION - Component test with form interaction
describe('ContactForm', () => {
beforeEach(() => {
vi.clearAllMocks(); // Prevent mock pollution
});
it('handles successful form submission', async () => {
// 3. SETUP - Configure mocks for success case
const mockSubmit = vi.mocked(submitForm);
mockSubmit.mockResolvedValue({ success: true });
const user = userEvent.setup();
render(<ContactForm />);
// 4. DECISION - Use accessible queries (getByLabelText vs getByTestId)
await user.type(screen.getByLabelText(/name/i), 'John Doe');
await user.type(screen.getByLabelText(/email/i), '[email protected]');
// 5. ACTION - Submit form
await user.click(screen.getByRole('button', { name: /submit/i }));
// 6. DECISION - Use waitFor for async state changes
await waitFor(() => {
expect(screen.getByText(/success/i)).toBeInTheDocument();
});
// 7. VERIFY - Mock was called with correct data
expect(mockSubmit).toHaveBeenCalledWith({
name: 'John Doe',
email: '[email protected]',
});
});
it('displays validation errors', async () => {
// Expert catches: Test error state, not just happy path
const user = userEvent.setup();
render(<ContactForm />);
// Submit empty form
await user.click(screen.getByRole('button', { name: /submit/i }));
// Verify validation errors appear
expect(screen.getByText(/name is required/i)).toBeInTheDocument();
expect(screen.getByText(/email is required/i)).toBeInTheDocument();
// Verify API was not called with invalid data
expect(submitForm).not.toHaveBeenCalled();
});
});
Novice misses: Testing only happy path, using getByTestId, not cleaning mocks
Expert catches: Error states, accessible queries, mock verification, async handling
waitFor() or findBy* queriesvi.clearAllMocks() in hooks)getByRole() or getByLabelText()toHaveBeenCalledWith() for critical callsact() warnings in test outputuserEvent not fireEvent❌ DO NOT use for:
playwright-testing skill insteadperformance-testing skill insteadopenapi-testing skill insteadvisual-testing skill instead✅ USE this skill for:
data-ai
license: Apache-2.0 NOT for unrelated tasks outside this domain.
development
Use when designing caching strategies (cache-aside, write-through, write-behind), implementing distributed locks, building rate limiters, leaderboards, real-time streams (XADD/consumer groups), pub/sub, or tuning eviction policies. Triggers: thundering-herd on cache miss, dogpile on key expiry, Redlock vs SET-NX-PX choice, sliding-window rate limiter, hot-key on a single cluster slot, big-key blowup, MULTI/EXEC across slots, KEYS in production. NOT for Redis Cluster operations/admin (different domain), embedded KV (SQLite, leveldb), in-process LRU caches, or Memcached.
tools
Drawing the `'use client'` boundary correctly in React Server Components apps (Next.js App Router, RSC frameworks) — leaf-pushing, slot composition, serialization rules, and environment poisoning prevention. Grounded in react.dev and Next.js 16 docs.
development
Use when designing rate limiting for an API, choosing between token bucket / sliding window / leaky bucket / fixed window, implementing it in Redis, deciding edge (Cloudflare/Upstash) vs origin enforcement, sizing per-user vs per-IP vs per-endpoint quotas, returning the right 429 response with Retry-After, or fixing the boundary-burst bug in fixed-window limiters. Triggers: 429 too many requests, INCR + EXPIRE, ZADD + ZREMRANGEBYSCORE + ZCARD, X-RateLimit-Remaining header, Cloudflare WAF rate limiting rules, Upstash @upstash/ratelimit, leaky bucket shaping vs policing, distributed rate limiter consistency. NOT for DDoS mitigation specifically (different scale), CAPTCHA / bot management, full WAF design, or per-user quota billing.