Skills for Claude Code CLI such as full stack dev Cloudflare, React, Tailwind v4, and AI integrations.
Python aianthropicautomationclaude-codeclaude-skillscloudflaredevtoolsproductivityreactskillstailwindvite
feat: Add vitest and testing-library skills (Batch 3)
Jezc8f32b33c849
diff --git a/skills/testing-library/.claude-plugin/plugin.json b/skills/testing-library/.claude-plugin/plugin.jsonnew file mode 100644index 00000000..28520b89--- /dev/null+++ b/skills/testing-library/.claude-plugin/plugin.json@@ -0,0 +1,12 @@+{+ "name": "testing-library",+ "description": "Test React components with Testing Library patterns. Covers queries (getBy/findBy/queryBy), user-event interactions, async testing (findBy vs waitFor), accessibility testing, and MSW integration for API mocking. Use when: testing React components, simulating user interactions, testing forms, mocking API calls with MSW, or writing accessible tests.",+ "version": "1.0.0",+ "author": {+ "name": "Jeremy Dawes",+ "email": "[email protected]"+ },+ "license": "MIT",+ "repository": "https://github.com/jezweb/claude-skills",+ "keywords": ["testing-library","react testing library","getByRole","user-event","waitFor","MSW","screen."]+}diff --git a/skills/testing-library/README.md b/skills/testing-library/README.mdnew file mode 100644index 00000000..b61b2393--- /dev/null+++ b/skills/testing-library/README.md@@ -0,0 +1,18 @@+# Testing Library Skill++React component testing with accessible queries.++## Keywords++testing-library, react testing library, @testing-library/react, @testing-library/user-event, @testing-library/jest-dom, getByRole, getByLabelText, getByText, findByRole, queryByRole, waitFor, waitForElementToBeRemoved, screen, render, user-event, userEvent, fireEvent, accessibility testing, a11y, axe, MSW, mock service worker, API mocking, form testing, async testing, component testing, integration testing++## Auto-trigger++This skill activates when discussing:+- Testing React components+- Using getByRole, getByLabelText, or other Testing Library queries+- User interaction simulation with userEvent+- Waiting for async UI updates+- Mocking API calls with MSW+- Accessibility testing with axe+- Form testing patternsdiff --git a/skills/testing-library/SKILL.md b/skills/testing-library/SKILL.mdnew file mode 100644index 00000000..f8bb57e4--- /dev/null+++ b/skills/testing-library/SKILL.md@@ -0,0 +1,504 @@+---+name: testing-library+description: |+ Test React components with Testing Library patterns. Covers queries (getBy/findBy/queryBy), user-event interactions, async testing (findBy vs waitFor), accessibility testing, and MSW integration for API mocking.++ Use when: testing React components, simulating user interactions, testing forms, mocking API calls with MSW, or writing accessible tests. Keywords: testing-library, react testing library, getByRole, user-event, waitFor, MSW, screen.+license: MIT+---++# React Testing Library++**Status**: Production Ready+**Last Updated**: 2026-02-06+**Version**: 16.x+**User Event**: 14.x++---++## Quick Start++```bash+# Install with Vitest+pnpm add -D @testing-library/react @testing-library/user-event @testing-library/jest-dom jsdom++# Or with Jest+pnpm add -D @testing-library/react @testing-library/user-event @testing-library/jest-dom+```++### Setup File (src/test/setup.ts)++```typescript+import '@testing-library/jest-dom/vitest';+import { cleanup } from '@testing-library/react';+import { afterEach } from 'vitest';++// Cleanup after each test+afterEach(() => {+ cleanup();+});+```++### Vitest Config++```typescript+// vitest.config.ts+export default defineConfig({+ test: {+ globals: true,+ environment: 'jsdom',+ setupFiles: ['./src/test/setup.ts'],+ },+});+```++---++## Query Priority (Accessibility First)++Use queries in this order for accessible, resilient tests:++| Priority | Query | Use For |+|----------|-------|---------|+| 1 | `getByRole` | Buttons, links, headings, inputs |+| 2 | `getByLabelText` | Form inputs with labels |+| 3 | `getByPlaceholderText` | Inputs without visible labels |+| 4 | `getByText` | Non-interactive text content |+| 5 | `getByTestId` | Last resort only |++### Examples++```typescript+import { render, screen } from '@testing-library/react';++// ✅ GOOD - semantic role queries+screen.getByRole('button', { name: /submit/i });+screen.getByRole('heading', { level: 1 });+screen.getByRole('textbox', { name: /email/i });+screen.getByRole('link', { name: /learn more/i });++// ✅ GOOD - label-based queries for forms+screen.getByLabelText(/email address/i);++// ⚠️ OK - when no better option+screen.getByText(/welcome to our app/i);++// ❌ AVOID - not accessible, brittle+screen.getByTestId('submit-button');+```++---++## Query Variants++| Variant | Returns | Throws | Use For |+|---------|---------|--------|---------|+| `getBy` | Element | Yes | Element exists now |+| `queryBy` | Element or null | No | Element might not exist |+| `findBy` | Promise<Element> | Yes | Async, appears later |+| `getAllBy` | Element[] | Yes | Multiple elements |+| `queryAllBy` | Element[] | No | Multiple or none |+| `findAllBy` | Promise<Element[]> | Yes | Multiple, async |++### When to Use Each++```typescript+// Element exists immediately+const button = screen.getByRole('button');++// Check element doesn't exist+expect(screen.queryByRole('dialog')).not.toBeInTheDocument();++// Wait for async element to appear+const modal = await screen.findByRole('dialog');++// Multiple elements+const items = screen.getAllByRole('listitem');+```++---++## User Event (Realistic Interactions)++**Always use `userEvent` over `fireEvent`** - it simulates real user behavior.++```typescript+import { render, screen } from '@testing-library/react';+import userEvent from '@testing-library/user-event';++describe('Form', () => {+ it('submits form data', async () => {+ const user = userEvent.setup();+ const onSubmit = vi.fn();++ render(<LoginForm onSubmit={onSubmit} />);++ // Type in inputs+ await user.type(screen.getByLabelText(/email/i), '[email protected]');+ await user.type(screen.getByLabelText(/password/i), 'secret123');++ // Click submit+ await user.click(screen.getByRole('button', { name: /sign in/i }));++ expect(onSubmit).toHaveBeenCalledWith({+ email: '[email protected]',+ password: 'secret123',+ });+ });+});+```++### Common User Events++```typescript+const user = userEvent.setup();++// Clicking+await user.click(element);+await user.dblClick(element);+await user.tripleClick(element); // Select all text++// Typing+await user.type(input, 'hello world');+await user.clear(input);+await user.type(input, '{Enter}'); // Special keys++// Keyboard+await user.keyboard('{Shift>}A{/Shift}'); // Shift+A+await user.tab(); // Tab navigation++// Selection+await user.selectOptions(select, ['option1', 'option2']);++// Hover+await user.hover(element);+await user.unhover(element);++// Clipboard+await user.copy();+await user.paste();+```++---++## Async Testing++### findBy - Wait for Element++```typescript+it('shows loading then content', async () => {+ render(<AsyncComponent />);++ // Shows loading initially+ expect(screen.getByText(/loading/i)).toBeInTheDocument();++ // Wait for content to appear (auto-retries)+ const content = await screen.findByText(/data loaded/i);+ expect(content).toBeInTheDocument();+});+```++### waitFor - Wait for Condition++```typescript+import { waitFor } from '@testing-library/react';++it('updates count after click', async () => {+ const user = userEvent.setup();+ render(<Counter />);++ await user.click(screen.getByRole('button', { name: /increment/i }));++ // Wait for state update+ await waitFor(() => {+ expect(screen.getByText(/count: 1/i)).toBeInTheDocument();+ });+});+```++### waitForElementToBeRemoved++```typescript+import { waitForElementToBeRemoved } from '@testing-library/react';++it('hides modal after close', async () => {+ const user = userEvent.setup();+ render(<ModalComponent />);++ await user.click(screen.getByRole('button', { name: /close/i }));++ // Wait for modal to disappear+ await waitForElementToBeRemoved(() => screen.queryByRole('dialog'));+});+```++---++## MSW Integration (API Mocking)++Mock API calls at the network level with Mock Service Worker.++```bash+pnpm add -D msw+```++### Setup (src/test/mocks/handlers.ts)++```typescript+import { http, HttpResponse } from 'msw';++export const handlers = [+ http.get('/api/user', () => {+ return HttpResponse.json({+ id: 1,+ name: 'Test User',+ email: '[email protected]',+ });+ }),++ http.post('/api/login', async ({ request }) => {+ const body = await request.json();+ if (body.password === 'correct') {+ return HttpResponse.json({ token: 'abc123' });+ }+ return HttpResponse.json(+ { error: 'Invalid credentials' },+ { status: 401 }+ );+ }),+];+```++### Setup (src/test/mocks/server.ts)++```typescript+import { setupServer } from 'msw/node';+import { handlers } from './handlers';++export const server = setupServer(...handlers);+```++### Test Setup++```typescript+// src/test/setup.ts+import { server } from './mocks/server';+import { beforeAll, afterEach, afterAll } from 'vitest';++beforeAll(() => server.listen({ onUnhandledRequest: 'error' }));+afterEach(() => server.resetHandlers());+afterAll(() => server.close());+```++### Using in Tests++```typescript+import { server } from '../test/mocks/server';+import { http, HttpResponse } from 'msw';++it('handles API error', async () => {+ // Override handler for this test+ server.use(+ http.get('/api/user', () => {+ return HttpResponse.json(+ { error: 'Server error' },+ { status: 500 }+ );+ })+ );++ render(<UserProfile />);++ await screen.findByText(/error loading user/i);+});+```++---++## Accessibility Testing++### Check for A11y Violations++```bash+pnpm add -D @axe-core/react+```++```typescript+import { axe, toHaveNoViolations } from 'jest-axe';++expect.extend(toHaveNoViolations);++it('has no accessibility violations', async () => {+ const { container } = render(<MyComponent />);+ const results = await axe(container);+ expect(results).toHaveNoViolations();+});+```++### Role-Based Queries Are A11y Tests++Using `getByRole` implicitly tests accessibility:++```typescript+// This passes only if button is properly accessible+screen.getByRole('button', { name: /submit/i });++// Fails if:+// - Element isn't a button or role="button"+// - Accessible name doesn't match+// - Element is hidden from accessibility tree+```++---++## Testing Patterns++### Forms++```typescript+it('validates required fields', async () => {+ const user = userEvent.setup();+ render(<ContactForm />);++ // Submit without filling required fields+ await user.click(screen.getByRole('button', { name: /submit/i }));++ // Check for validation errors+ expect(screen.getByText(/email is required/i)).toBeInTheDocument();+ expect(screen.getByText(/message is required/i)).toBeInTheDocument();+});+```++### Modals/Dialogs++```typescript+it('opens and closes modal', async () => {+ const user = userEvent.setup();+ render(<ModalTrigger />);++ // Modal not visible initially+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument();++ // Open modal+ await user.click(screen.getByRole('button', { name: /open/i }));+ expect(screen.getByRole('dialog')).toBeInTheDocument();++ // Close modal+ await user.click(screen.getByRole('button', { name: /close/i }));+ await waitForElementToBeRemoved(() => screen.queryByRole('dialog'));+});+```++### Lists++```typescript+it('renders list items', () => {+ render(<TodoList items={['Buy milk', 'Walk dog']} />);++ const items = screen.getAllByRole('listitem');+ expect(items).toHaveLength(2);+ expect(items[0]).toHaveTextContent('Buy milk');+});+```++---++## Common Matchers (jest-dom)++```typescript+// Presence+expect(element).toBeInTheDocument();+expect(element).toBeVisible();+expect(element).toBeEmptyDOMElement();++// State+expect(button).toBeEnabled();+expect(button).toBeDisabled();+expect(checkbox).toBeChecked();+expect(input).toBeRequired();++// Content+expect(element).toHaveTextContent(/hello/i);+expect(element).toHaveValue('test');+expect(element).toHaveAttribute('href', '/about');++// Styles+expect(element).toHaveClass('active');+expect(element).toHaveStyle({ color: 'red' });++// Focus+expect(input).toHaveFocus();+```++---++## Debugging++### screen.debug()++```typescript+it('debugs rendering', () => {+ render(<MyComponent />);++ // Print entire DOM+ screen.debug();++ // Print specific element+ screen.debug(screen.getByRole('button'));+});+```++### logRoles++```typescript+import { logRoles } from '@testing-library/react';++it('shows available roles', () => {+ const { container } = render(<MyComponent />);+ logRoles(container);+});+```++---++## Common Mistakes++### Using getBy for Async++```typescript+// ❌ WRONG - fails if element appears async+const modal = screen.getByRole('dialog');++// ✅ CORRECT - waits for element+const modal = await screen.findByRole('dialog');+```++### Not Awaiting User Events++```typescript+// ❌ WRONG - race condition+user.click(button);+expect(result).toBeInTheDocument();++// ✅ CORRECT - await the interaction+await user.click(button);+expect(result).toBeInTheDocument();+```++### Using container.querySelector++```typescript+// ❌ WRONG - not accessible, brittle+const button = container.querySelector('.submit-btn');++// ✅ CORRECT - accessible query+const button = screen.getByRole('button', { name: /submit/i });+```++---++## See Also++- `vitest` skill - Test runner configuration+- `testing-patterns` skill - General testing patterns+- Official docs: https://testing-library.com/docs/react-testing-library/introdiff --git a/skills/testing-library/rules/testing-library-patterns.md b/skills/testing-library/rules/testing-library-patterns.mdnew file mode 100644index 00000000..2ced0df8--- /dev/null+++ b/skills/testing-library/rules/testing-library-patterns.md@@ -0,0 +1,97 @@+---+globs: ["**/*.test.tsx", "**/*.test.jsx", "**/*.spec.tsx", "**/test/*.tsx"]+---++# Testing Library Pattern Corrections++## Query Priority++| If Claude suggests... | Use instead... |+|----------------------|----------------|+| `getByTestId('submit')` | `getByRole('button', { name: /submit/i })` |+| `container.querySelector('.btn')` | `screen.getByRole('button')` |+| `getByText('Submit')` (for button) | `getByRole('button', { name: /submit/i })` |++## Async Testing++```typescript+// ❌ WRONG - getBy doesn't wait+const modal = screen.getByRole('dialog');++// ✅ CORRECT - findBy waits for element+const modal = await screen.findByRole('dialog');+```++## User Event Setup++```typescript+// ❌ WRONG - deprecated direct call+import userEvent from '@testing-library/user-event';+userEvent.click(button);++// ✅ CORRECT - setup() first, then await+const user = userEvent.setup();+await user.click(button);+```++## fireEvent vs userEvent++| If Claude suggests... | Use instead... |+|----------------------|----------------|+| `fireEvent.click(button)` | `await user.click(button)` |+| `fireEvent.change(input, { target: { value: 'x' } })` | `await user.type(input, 'x')` |+| `fireEvent.keyDown(input, { key: 'Enter' })` | `await user.keyboard('{Enter}')` |++**Why?** userEvent simulates real user behavior (focus, hover, then click) while fireEvent just dispatches a single event.++## Checking Element Not Exists++```typescript+// ❌ WRONG - throws if not found+expect(screen.getByRole('dialog')).not.toBeInTheDocument();++// ✅ CORRECT - returns null if not found+expect(screen.queryByRole('dialog')).not.toBeInTheDocument();+```++## Awaiting Assertions++```typescript+// ❌ WRONG - missing await+expect(screen.findByText('Hello')).toBeInTheDocument();++// ✅ CORRECT - await the findBy+expect(await screen.findByText('Hello')).toBeInTheDocument();+```++## waitFor Usage++```typescript+// ❌ WRONG - side effects in waitFor callback+await waitFor(() => {+ user.click(button); // Don't do this!+ expect(result).toBeInTheDocument();+});++// ✅ CORRECT - only assertions in waitFor+await user.click(button);+await waitFor(() => {+ expect(result).toBeInTheDocument();+});+```++## Cleanup++Testing Library auto-cleans in modern versions, but if using Vitest:++```typescript+// src/test/setup.ts+import { cleanup } from '@testing-library/react';+import { afterEach } from 'vitest';++afterEach(() => {+ cleanup();+});+```++**Last Updated**: 2026-02-06diff --git a/skills/testing-library/templates/msw-handlers.ts b/skills/testing-library/templates/msw-handlers.tsnew file mode 100644index 00000000..f0a1237d--- /dev/null+++ b/skills/testing-library/templates/msw-handlers.ts@@ -0,0 +1,117 @@+/**+ * MSW Handlers Template+ * Location: src/test/mocks/handlers.ts+ *+ * Define API mock handlers for testing+ */+import { http, HttpResponse, delay } from 'msw';++// Base URL for API calls+const API_BASE = '/api';++// Mock data+const mockUser = {+ id: '1',+ name: 'Test User',+ email: '[email protected]',+};++const mockItems = [+ { id: '1', title: 'Item 1', completed: false },+ { id: '2', title: 'Item 2', completed: true },+];++export const handlers = [+ // GET /api/user - Return current user+ http.get(`${API_BASE}/user`, async () => {+ await delay(100); // Simulate network delay+ return HttpResponse.json(mockUser);+ }),++ // GET /api/items - Return list of items+ http.get(`${API_BASE}/items`, () => {+ return HttpResponse.json(mockItems);+ }),++ // POST /api/items - Create new item+ http.post(`${API_BASE}/items`, async ({ request }) => {+ const body = (await request.json()) as { title: string };+ const newItem = {+ id: String(Date.now()),+ title: body.title,+ completed: false,+ };+ return HttpResponse.json(newItem, { status: 201 });+ }),++ // PUT /api/items/:id - Update item+ http.put(`${API_BASE}/items/:id`, async ({ params, request }) => {+ const { id } = params;+ const updates = await request.json();+ const item = mockItems.find((i) => i.id === id);++ if (!item) {+ return HttpResponse.json({ error: 'Not found' }, { status: 404 });+ }++ return HttpResponse.json({ ...item, ...updates });+ }),++ // DELETE /api/items/:id - Delete item+ http.delete(`${API_BASE}/items/:id`, ({ params }) => {+ const { id } = params;+ const index = mockItems.findIndex((i) => i.id === id);++ if (index === -1) {+ return HttpResponse.json({ error: 'Not found' }, { status: 404 });+ }++ return HttpResponse.json({ success: true });+ }),++ // POST /api/login - Authentication+ http.post(`${API_BASE}/login`, async ({ request }) => {+ const { email, password } = (await request.json()) as {+ email: string;+ password: string;+ };++ if (email === '[email protected]' && password === 'password123') {+ return HttpResponse.json({+ token: 'mock-jwt-token',+ user: mockUser,+ });+ }++ return HttpResponse.json(+ { error: 'Invalid credentials' },+ { status: 401 }+ );+ }),++ // Error response example+ http.get(`${API_BASE}/error`, () => {+ return HttpResponse.json(+ { error: 'Internal server error' },+ { status: 500 }+ );+ }),+];++/**+ * Server setup (src/test/mocks/server.ts)+ *+ * import { setupServer } from 'msw/node';+ * import { handlers } from './handlers';+ * export const server = setupServer(...handlers);+ */++/**+ * Test setup (src/test/setup.ts)+ *+ * import { server } from './mocks/server';+ *+ * beforeAll(() => server.listen({ onUnhandledRequest: 'error' }));+ * afterEach(() => server.resetHandlers());+ * afterAll(() => server.close());+ */diff --git a/skills/testing-library/templates/setup.ts b/skills/testing-library/templates/setup.tsnew file mode 100644index 00000000..d2cfbd8c--- /dev/null+++ b/skills/testing-library/templates/setup.ts@@ -0,0 +1,57 @@+/**+ * Testing Library Setup for Vitest+ * Add to vitest.config.ts: setupFiles: ['./src/test/setup.ts']+ */+import '@testing-library/jest-dom/vitest';+import { cleanup } from '@testing-library/react';+import { afterEach, vi } from 'vitest';++// Cleanup after each test+afterEach(() => {+ cleanup();+});++// Mock window.matchMedia (for responsive components)+Object.defineProperty(window, 'matchMedia', {+ writable: true,+ value: vi.fn().mockImplementation((query: string) => ({+ matches: false,+ media: query,+ onchange: null,+ addListener: vi.fn(),+ removeListener: vi.fn(),+ addEventListener: vi.fn(),+ removeEventListener: vi.fn(),+ dispatchEvent: vi.fn(),+ })),+});++// Mock IntersectionObserver (for lazy loading, infinite scroll)+class MockIntersectionObserver {+ observe = vi.fn();+ disconnect = vi.fn();+ unobserve = vi.fn();+}++Object.defineProperty(window, 'IntersectionObserver', {+ writable: true,+ value: MockIntersectionObserver,+});++// Mock ResizeObserver+class MockResizeObserver {+ observe = vi.fn();+ disconnect = vi.fn();+ unobserve = vi.fn();+}++Object.defineProperty(window, 'ResizeObserver', {+ writable: true,+ value: MockResizeObserver,+});++// Mock scrollTo (for scroll-related tests)+Object.defineProperty(window, 'scrollTo', {+ writable: true,+ value: vi.fn(),+});diff --git a/skills/vitest/.claude-plugin/plugin.json b/skills/vitest/.claude-plugin/plugin.jsonnew file mode 100644index 00000000..f12aaa2c--- /dev/null+++ b/skills/vitest/.claude-plugin/plugin.json@@ -0,0 +1,12 @@+{+ "name": "vitest",+ "description": "Build fast unit and integration tests with Vitest 4.x. Covers configuration for Workers/React/Node, vi.mock/vi.spyOn patterns, snapshot testing, in-source testing, workspace configuration, and browser mode. Use when: setting up tests, migrating from Jest, mocking modules, testing React components, or configuring monorepo workspaces.",+ "version": "1.0.0",+ "author": {+ "name": "Jeremy Dawes",+ "email": "[email protected]"+ },+ "license": "MIT",+ "repository": "https://github.com/jezweb/claude-skills",+ "keywords": ["vitest","test","unit test","vi.mock","vi.spyOn","snapshot","coverage","Jest migration."]+}diff --git a/skills/vitest/README.md b/skills/vitest/README.mdnew file mode 100644index 00000000..9ef0db05--- /dev/null+++ b/skills/vitest/README.md@@ -0,0 +1,19 @@+# Vitest Skill++Modern test framework for Vite projects.++## Keywords++vitest, test, testing, unit test, integration test, vi.mock, vi.spyOn, vi.fn, mock, spy, stub, snapshot, inline snapshot, coverage, v8 coverage, jsdom, happy-dom, browser testing, playwright, workspace, monorepo, in-source testing, Jest migration, Jest to Vitest, test runner, watch mode, vitest ui, @vitest/coverage-v8, @vitest/browser, vitest.config.ts, defineConfig, globals, setupFiles, test environment++## Auto-trigger++This skill activates when discussing:+- Setting up Vitest+- Writing unit tests with Vitest+- Mocking with vi.mock or vi.spyOn+- Migrating from Jest to Vitest+- Configuring test coverage+- Snapshot testing+- Browser mode testing+- Monorepo test workspacesdiff --git a/skills/vitest/SKILL.md b/skills/vitest/SKILL.mdnew file mode 100644index 00000000..e7c1968f--- /dev/null+++ b/skills/vitest/SKILL.md@@ -0,0 +1,493 @@+---+name: vitest+description: |+ Build fast unit and integration tests with Vitest 4.x. Covers configuration for Workers/React/Node, vi.mock/vi.spyOn patterns, snapshot testing, in-source testing, workspace configuration, and browser mode.++ Use when: setting up tests, migrating from Jest, mocking modules, testing React components, or configuring monorepo workspaces. Keywords: vitest, test, unit test, vi.mock, vi.spyOn, snapshot, coverage, Jest migration.+license: MIT+---++# Vitest - Modern Test Framework++**Status**: Production Ready+**Last Updated**: 2026-02-06+**Vitest Version**: 4.x+**Vite Compatibility**: 6.x++---++## Quick Start++```bash+# Install+pnpm add -D vitest++# Add to package.json+{+ "scripts": {+ "test": "vitest",+ "test:run": "vitest run",+ "test:coverage": "vitest run --coverage"+ }+}+```++---++## Configuration++### Minimal Config (vitest.config.ts)++```typescript+import { defineConfig } from 'vitest/config';++export default defineConfig({+ test: {+ globals: true,+ environment: 'node',+ },+});+```++### React Config++```typescript+import { defineConfig } from 'vitest/config';+import react from '@vitejs/plugin-react';++export default defineConfig({+ plugins: [react()],+ test: {+ globals: true,+ environment: 'jsdom',+ setupFiles: ['./src/test/setup.ts'],+ css: true,+ },+});+```++### Cloudflare Workers Config++```typescript+import { defineConfig } from 'vitest/config';+import { cloudflare } from '@cloudflare/vite-plugin';++export default defineConfig({+ plugins: [cloudflare()],+ test: {+ globals: true,+ environment: 'node',+ // Workers tests often need longer timeouts for D1/KV+ testTimeout: 10000,+ },+});+```++---++## Mocking Patterns++### vi.mock - Module Mocking++```typescript+import { vi, describe, it, expect } from 'vitest';+import { fetchUser } from './api';++// Mock entire module+vi.mock('./api', () => ({+ fetchUser: vi.fn(),+}));++describe('User component', () => {+ it('fetches user data', async () => {+ // Type-safe mock implementation+ vi.mocked(fetchUser).mockResolvedValue({ id: 1, name: 'Test' });++ // ... test code++ expect(fetchUser).toHaveBeenCalledWith(1);+ });+});+```++### vi.spyOn - Spy on Methods++```typescript+import { vi, describe, it, expect, beforeEach, afterEach } from 'vitest';++describe('Date handling', () => {+ beforeEach(() => {+ vi.useFakeTimers();+ vi.setSystemTime(new Date('2026-01-01'));+ });++ afterEach(() => {+ vi.useRealTimers();+ });++ it('uses mocked date', () => {+ expect(new Date().getFullYear()).toBe(2026);+ });+});+```++### vi.stubGlobal - Global Mocks++```typescript+import { vi, describe, it, expect } from 'vitest';++describe('Environment', () => {+ it('mocks fetch globally', async () => {+ const mockFetch = vi.fn().mockResolvedValue({+ ok: true,+ json: () => Promise.resolve({ data: 'test' }),+ });++ vi.stubGlobal('fetch', mockFetch);++ const response = await fetch('/api/test');+ expect(mockFetch).toHaveBeenCalledWith('/api/test');++ vi.unstubAllGlobals();+ });+});+```++---++## Snapshot Testing++### Basic Snapshots++```typescript+import { describe, it, expect } from 'vitest';++describe('Component output', () => {+ it('matches snapshot', () => {+ const result = renderComponent({ title: 'Hello' });+ expect(result).toMatchSnapshot();+ });++ it('matches inline snapshot', () => {+ const result = { name: 'test', count: 42 };+ expect(result).toMatchInlineSnapshot(`+ {+ "count": 42,+ "name": "test",+ }+ `);+ });+});+```++### Update Snapshots++```bash+# Update all snapshots+vitest run --update++# Interactive update+vitest --ui+```++---++## In-Source Testing++Test code directly in source files (tree-shaken in production):++```typescript+// src/utils/math.ts+export function add(a: number, b: number): number {+ return a + b;+}++// In-source test block+if (import.meta.vitest) {+ const { describe, it, expect } = import.meta.vitest;++ describe('add', () => {+ it('adds two numbers', () => {+ expect(add(1, 2)).toBe(3);+ });+ });+}+```++**Config for in-source testing:**++```typescript+// vitest.config.ts+export default defineConfig({+ test: {+ includeSource: ['src/**/*.{js,ts}'],+ },+ define: {+ 'import.meta.vitest': 'undefined', // Tree-shake in production+ },+});+```++---++## Workspace Configuration (Monorepos)++```typescript+// vitest.workspace.ts+import { defineWorkspace } from 'vitest/config';++export default defineWorkspace([+ // Each package can have its own config+ 'packages/*/vitest.config.ts',++ // Or define inline+ {+ test: {+ name: 'unit',+ include: ['src/**/*.test.ts'],+ environment: 'node',+ },+ },+ {+ test: {+ name: 'browser',+ include: ['src/**/*.browser.test.ts'],+ browser: {+ enabled: true,+ provider: 'playwright',+ name: 'chromium',+ },+ },+ },+]);+```++---++## Browser Mode Testing++```typescript+// vitest.config.ts+export default defineConfig({+ test: {+ browser: {+ enabled: true,+ provider: 'playwright', // or 'webdriverio'+ name: 'chromium',+ headless: true,+ },+ },+});+```++```bash+# Install browser provider+pnpm add -D @vitest/browser playwright+```++---++## Coverage++```bash+# Install coverage provider+pnpm add -D @vitest/coverage-v8++# Run with coverage+vitest run --coverage+```++```typescript+// vitest.config.ts+export default defineConfig({+ test: {+ coverage: {+ provider: 'v8',+ reporter: ['text', 'html', 'lcov'],+ exclude: [+ 'node_modules/',+ 'src/test/',+ '**/*.d.ts',+ ],+ thresholds: {+ statements: 80,+ branches: 80,+ functions: 80,+ lines: 80,+ },+ },+ },+});+```++---++## Jest Migration++### Key Differences++| Jest | Vitest |+|------|--------|+| `jest.fn()` | `vi.fn()` |+| `jest.mock()` | `vi.mock()` |+| `jest.spyOn()` | `vi.spyOn()` |+| `jest.useFakeTimers()` | `vi.useFakeTimers()` |+| `jest.clearAllMocks()` | `vi.clearAllMocks()` |+| `@jest/globals` | `vitest` |++### Migration Steps++1. **Replace imports:**+```typescript+// Before (Jest)+import { jest } from '@jest/globals';++// After (Vitest)+import { vi } from 'vitest';+```++2. **Update config:**+```typescript+// jest.config.js → vitest.config.ts+export default defineConfig({+ test: {+ globals: true, // Enables describe/it/expect without imports+ environment: 'jsdom',+ },+});+```++3. **Replace jest. with vi.:**+```bash+# Quick replace (review changes carefully)+find src -name "*.test.ts" -exec sed -i 's/jest\./vi./g' {} \;+```++---++## Common Patterns++### Testing Async Code++```typescript+import { describe, it, expect } from 'vitest';++describe('async operations', () => {+ it('resolves promise', async () => {+ const result = await fetchData();+ expect(result).toBeDefined();+ });++ it('rejects with error', async () => {+ await expect(failingOperation()).rejects.toThrow('Expected error');+ });+});+```++### Testing with Fixtures++```typescript+import { describe, it, expect, beforeEach } from 'vitest';++describe('with fixtures', () => {+ let testData: TestData;++ beforeEach(() => {+ testData = createTestFixture();+ });++ it('uses fixture', () => {+ expect(testData.id).toBeDefined();+ });+});+```++### Parameterized Tests++```typescript+import { describe, it, expect } from 'vitest';++describe.each([+ { input: 1, expected: 2 },+ { input: 2, expected: 4 },+ { input: 3, expected: 6 },+])('double($input)', ({ input, expected }) => {+ it(`returns ${expected}`, () => {+ expect(double(input)).toBe(expected);+ });+});+```++---++## Debugging++### Run Single Test++```bash+vitest run -t "test name"+vitest run src/specific.test.ts+```++### Debug Mode++```bash+# With Node inspector+node --inspect-brk ./node_modules/vitest/vitest.mjs run++# Or use Vitest UI+vitest --ui+```++### Watch Mode++```bash+vitest # Watch mode (default)+vitest run # Single run+vitest watch # Explicit watch+```++---++## Troubleshooting++### "Cannot find module" in mocks++```typescript+// Ensure mock path matches import path exactly+vi.mock('./api'); // Matches: import { x } from './api'+vi.mock('../api'); // Different! Won't work for './api' imports+```++### ESM/CJS Issues++```typescript+// vitest.config.ts - for CJS dependencies+export default defineConfig({+ test: {+ deps: {+ inline: ['problematic-cjs-package'],+ },+ },+});+```++### Globals Not Defined++```typescript+// If using globals: true but TypeScript complains+// Add to tsconfig.json:+{+ "compilerOptions": {+ "types": ["vitest/globals"]+ }+}+```++---++## See Also++- `testing-patterns` skill - General testing patterns+- `testing-library` skill - React Testing Library integration+- Official docs: https://vitest.devdiff --git a/skills/vitest/rules/vitest-patterns.md b/skills/vitest/rules/vitest-patterns.mdnew file mode 100644index 00000000..b6ab2325--- /dev/null+++ b/skills/vitest/rules/vitest-patterns.md@@ -0,0 +1,100 @@+---+globs: ["**/*.test.ts", "**/*.test.tsx", "**/*.spec.ts", "**/vitest.config.ts"]+---++# Vitest Pattern Corrections++## Jest to Vitest Migration++| If Claude suggests... | Use instead... |+|----------------------|----------------|+| `jest.fn()` | `vi.fn()` |+| `jest.mock()` | `vi.mock()` |+| `jest.spyOn()` | `vi.spyOn()` |+| `jest.useFakeTimers()` | `vi.useFakeTimers()` |+| `@jest/globals` import | `vitest` import |+| `jest.config.js` | `vitest.config.ts` |++## Mock Path Matching++Vitest mocks must match the exact import path:++```typescript+// ❌ WRONG - path doesn't match import+import { api } from './api';+vi.mock('../api'); // Won't work!++// ✅ CORRECT - path matches import exactly+import { api } from './api';+vi.mock('./api');+```++## vi.mocked for Type Safety++```typescript+// ❌ WRONG - no type safety on mock+vi.mock('./api');+(fetchUser as jest.Mock).mockResolvedValue(data);++// ✅ CORRECT - type-safe mock+vi.mock('./api');+vi.mocked(fetchUser).mockResolvedValue(data);+```++## Globals Configuration++If using `globals: true` in config, add types:++```json+// tsconfig.json+{+ "compilerOptions": {+ "types": ["vitest/globals"]+ }+}+```++## Cleanup Between Tests++```typescript+// ❌ WRONG - mocks persist between tests+vi.mock('./api');++// ✅ CORRECT - reset mocks in beforeEach/afterEach+beforeEach(() => {+ vi.clearAllMocks();+});++afterEach(() => {+ vi.restoreAllMocks();+});+```++## Async Test Patterns++```typescript+// ❌ WRONG - missing await+it('fetches data', () => {+ expect(fetchData()).resolves.toBe('data'); // Test passes before assertion!+});++// ✅ CORRECT - await the assertion+it('fetches data', async () => {+ await expect(fetchData()).resolves.toBe('data');+});+```++## In-Source Testing Guard++```typescript+// ❌ WRONG - tests included in production build+describe('tests', () => { ... });++// ✅ CORRECT - guarded, tree-shaken in production+if (import.meta.vitest) {+ const { describe, it, expect } = import.meta.vitest;+ describe('tests', () => { ... });+}+```++**Last Updated**: 2026-02-06diff --git a/skills/vitest/templates/test-utils.ts b/skills/vitest/templates/test-utils.tsnew file mode 100644index 00000000..6e4a3c87--- /dev/null+++ b/skills/vitest/templates/test-utils.ts@@ -0,0 +1,86 @@+/**+ * Common test utilities for Vitest+ */+import { vi } from 'vitest';++/**+ * Create a mock function with typed implementation+ */+export function createMockFn<T extends (...args: unknown[]) => unknown>(+ implementation?: T+) {+ return vi.fn(implementation) as unknown as T & ReturnType<typeof vi.fn>;+}++/**+ * Wait for condition to be true (useful for async UI updates)+ */+export async function waitFor(+ condition: () => boolean | Promise<boolean>,+ { timeout = 5000, interval = 50 } = {}+): Promise<void> {+ const start = Date.now();++ while (!(await condition())) {+ if (Date.now() - start > timeout) {+ throw new Error(`waitFor timed out after ${timeout}ms`);+ }+ await new Promise((resolve) => setTimeout(resolve, interval));+ }+}++/**+ * Create a deferred promise for testing async flows+ */+export function createDeferred<T>() {+ let resolve!: (value: T) => void;+ let reject!: (error: Error) => void;++ const promise = new Promise<T>((res, rej) => {+ resolve = res;+ reject = rej;+ });++ return { promise, resolve, reject };+}++/**+ * Mock fetch with typed responses+ */+export function mockFetch(responses: Record<string, unknown>) {+ const mockFn = vi.fn(async (url: string) => {+ const response = responses[url];+ if (response === undefined) {+ return {+ ok: false,+ status: 404,+ json: () => Promise.resolve({ error: 'Not found' }),+ };+ }+ return {+ ok: true,+ status: 200,+ json: () => Promise.resolve(response),+ };+ });++ vi.stubGlobal('fetch', mockFn);+ return mockFn;+}++/**+ * Reset all mocks and timers+ */+export function resetAllMocks() {+ vi.clearAllMocks();+ vi.restoreAllMocks();+ vi.useRealTimers();+ vi.unstubAllGlobals();+}++/**+ * Flush all pending promises+ */+export async function flushPromises() {+ await new Promise((resolve) => setTimeout(resolve, 0));+}diff --git a/skills/vitest/templates/vitest.config.ts b/skills/vitest/templates/vitest.config.tsnew file mode 100644index 00000000..6d3ddf13--- /dev/null+++ b/skills/vitest/templates/vitest.config.ts@@ -0,0 +1,39 @@+/// <reference types="vitest/config" />+import { defineConfig } from 'vitest/config';++export default defineConfig({+ test: {+ // Enable global test APIs (describe, it, expect)+ globals: true,++ // Test environment: 'node' | 'jsdom' | 'happy-dom'+ environment: 'node',++ // Setup files run before each test file+ // setupFiles: ['./src/test/setup.ts'],++ // Include patterns+ include: ['src/**/*.{test,spec}.{js,ts,jsx,tsx}'],++ // Exclude patterns+ exclude: ['node_modules', 'dist', '.git'],++ // Coverage configuration+ coverage: {+ provider: 'v8',+ reporter: ['text', 'html', 'lcov'],+ exclude: [+ 'node_modules/',+ 'src/test/',+ '**/*.d.ts',+ '**/*.config.*',+ ],+ },++ // Timeout for async tests (ms)+ testTimeout: 5000,++ // Watch mode exclude+ watchExclude: ['node_modules', 'dist'],+ },+});