/caddis-extras:component-testingfrom caddis-extras
React component tests with Vitest, Testing Library, userEvent, renderHook and MSW: setup, queries, hooks, API mocking, snapshots, loading/error states. E2E is playwright; method is tdd-workflow.
Ships in caddis-extras. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
React component and hook testing with Vitest + Testing Library. For E2E tests, use the playwright skill. For methodology, use tdd-workflow. This skill covers unit and integration testing of components.
vite.config.tsimport { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
export default defineConfig({
plugins: [react()],
test: {
environment: 'jsdom', // or 'happy-dom' (faster, less spec-compliant)
globals: true, // No need to import describe/it/expect
setupFiles: ['./src/test/setup.ts'],
coverage: {
provider: 'v8',
reporter: ['text', 'html', 'lcov'],
include: ['src/**/*.{ts,tsx}'],
exclude: ['src/**/*.stories.*', 'src/test/**'],
thresholds: { lines: 80, functions: 80, branches: 70 },
},
},
})
src/test/setup.tsimport '@testing-library/jest-dom' // Adds toBeInTheDocument(), toHaveValue(), etc.
import { cleanup } from '@testing-library/react'
import { afterEach, beforeAll, afterAll } from 'vitest'
import { server } from './msw/server' // MSW server (if using)
beforeAll(() => server.listen({ onUnhandledRequest: 'error' }))
afterEach(() => { cleanup(); server.resetHandlers() })
afterAll(() => server.close())
Use queries from most to least accessible:
| Priority | Query | Why |
|---|---|---|
| 1 | getByRole | Tests semantic HTML + ARIA — closest to real user experience |
| 2 | getByLabelText | Tests forms with labels — accessibility signal |
| 3 | getByPlaceholderText | Acceptable for inputs without labels |
| 4 | getByText | Tests text content |
| 5 | getByDisplayValue | Tests current input/textarea/select value |
| 6 | getByAltText | Tests image alt text |
| 7 | getByTitle | Low priority — title attributes are often hidden |
| Avoid | getByTestId | Last resort only — no accessibility signal |
// ✅ GOOD: Role + accessible name
const button = screen.getByRole('button', { name: /save changes/i })
// ✅ GOOD: Label association
const emailInput = screen.getByLabelText(/email/i)
// ❌ AVOID unless no alternative
const element = screen.getByTestId('submit-btn')
getBy* — throws if not found (synchronous)queryBy* — returns null if not found (for negative assertions)findBy* — returns Promise, waits for element to appear (async)getAllBy* / queryAllBy* / findAllBy* — multiple elementsuserEvent vs fireEventAlways prefer userEvent — it simulates real browser interactions (focus, pointer, keyboard events in sequence).
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
// ✅ GOOD: userEvent (realistic user simulation)
test('submits form on Enter key', async () => {
const user = userEvent.setup()
render(<SearchForm onSearch={vi.fn()} />)
await user.type(screen.getByRole('textbox', { name: /search/i }), 'react testing')
await user.keyboard('{Enter}')
expect(screen.getByRole('button', { name: /search/i })).toBeDisabled()
})
// ❌ BAD: fireEvent (bypasses realistic event chain)
fireEvent.click(submitButton) // Skips hover, focus, pointer-down events
import { render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { UserCard } from './UserCard'
describe('UserCard', () => {
const defaultProps = {
user: { id: '1', name: 'Alice', email: '[email protected]', role: 'admin' },
onEdit: vi.fn(),
}
it('renders user display name', () => {
// Arrange
render(<UserCard {...defaultProps} />)
// Assert
expect(screen.getByText('Alice')).toBeInTheDocument()
expect(screen.getByText('[email protected]')).toBeInTheDocument()
})
it('calls onEdit when Edit button clicked', async () => {
const user = userEvent.setup()
// Arrange
render(<UserCard {...defaultProps} />)
// Act
await user.click(screen.getByRole('button', { name: /edit/i }))
// Assert
expect(defaultProps.onEdit).toHaveBeenCalledWith('1')
expect(defaultProps.onEdit).toHaveBeenCalledTimes(1)
})
})
// Unit: mock child
vi.mock('./Avatar', () => ({ Avatar: () => <div data-testid="avatar" /> }))
// Integration: real children, only mock fetch
// MSW handles API responses (see §5)
renderHookimport { renderHook, act } from '@testing-library/react'
import { useCounter } from './useCounter'
describe('useCounter', () => {
it('increments count', () => {
const { result } = renderHook(() => useCounter(0))
act(() => result.current.increment())
expect(result.current.count).toBe(1)
})
it('respects initial value', () => {
const { result } = renderHook(() => useCounter(5))
expect(result.current.count).toBe(5)
})
})
import { render, screen, waitFor, waitForElementToBeRemoved } from '@testing-library/react'
it('shows loading skeleton then data', async () => {
render(<UserList />)
// Loading state is visible
expect(screen.getByRole('status', { name: /loading/i })).toBeInTheDocument()
// Wait for loading to finish
await waitForElementToBeRemoved(() => screen.queryByRole('status', { name: /loading/i }))
// Data is visible
expect(screen.getByText('Alice')).toBeInTheDocument()
})
it('shows error message on fetch failure', async () => {
// Override MSW handler for this test
server.use(
http.get('/api/users', () => HttpResponse.error())
)
render(<UserList />)
await waitFor(() => {
expect(screen.getByRole('alert')).toHaveTextContent(/failed to load/i)
})
})
// src/test/msw/handlers.ts
import { http, HttpResponse } from 'msw'
export const handlers = [
http.get('/api/users', () => {
return HttpResponse.json([
{ id: '1', name: 'Alice', email: '[email protected]' },
{ id: '2', name: 'Bob', email: '[email protected]' },
])
}),
http.post('/api/users', async ({ request }) => {
const body = await request.json()
return HttpResponse.json({ id: '3', ...body }, { status: 201 })
}),
]
// src/test/msw/server.ts
import { setupServer } from 'msw/node'
import { handlers } from './handlers'
export const server = setupServer(...handlers)
it('handles 404 gracefully', async () => {
server.use(
http.get('/api/users/:id', () => HttpResponse.json({ error: 'Not found' }, { status: 404 }))
)
// test body…
})
Use sparingly — prefer explicit assertions. Inline snapshots are better than file snapshots.
// ✅ GOOD: Inline snapshot — diff visible in code review
it('renders badge correctly', () => {
const { container } = render(<Badge variant="success">Active</Badge>)
expect(container.firstChild).toMatchInlineSnapshot(`
<span class="inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium bg-green-100 text-green-800">
Active
</span>
`)
})
// ❌ BAD: File snapshot for large component — diffs are noise
expect(screen.getByRole('dialog')).toMatchSnapshot()
React Server Components cannot be rendered in Vitest (no Node.js RSC renderer yet).
| Situation | Solution |
|---|---|
| Server Component under test | Extract logic to a tested pure function; test the function |
| Client Component with RSC parent | Test Client Component in isolation, mock Server Component output |
| Server Action | Test via integration test with MSW or direct function call |
| Page component | E2E test with Playwright |
// Extract business logic from RSC
export async function getPageData(id: string): Promise<PageData> {
return db.find(id) // This is testable
}
// RSC (not directly testable)
export default async function Page({ params }: { params: { id: string } }) {
const data = await getPageData(params.id) // Test this function instead
return <ClientView data={data} />
}
| Anti-Pattern | Problem |
|---|---|
| Testing implementation details | Tests break on refactor even when behaviour unchanged. Test what the user sees. |
getByTestId everywhere | No accessibility signal — fails to catch ARIA regressions |
| Mocking the module under test | Tautological — you end up testing the mock |
fireEvent instead of userEvent | Misses focus/hover/pointer events that real browsers fire |
| Shared mutable state between tests | Tests pass/fail depending on execution order |
No afterEach cleanup | Stale DOM accumulates — false positives |
@testing-library/jest-dom imported in setup — enables custom matchersuserEvent.setup() called once per test, not fireEventgetByRole used for interactive elements, getByLabelText for form fieldsbeforeAll/afterEach/afterAllgetByTestId unless added specifically for testingrenderHook + act used for hook testsvite.config.tsWhat SKILL.md sets; muted values are Claude Code's defaults
Other plugins' skills for the same job
npx claudepluginhub saajunaid/caddis-plugin --plugin caddis-extras81 skills in this plugin
/adopt-rbacPointer to the org's RBAC adoption skill. Use for "add RBAC to this app" or "adopt rbac-kit"./agent-md-refactorRefactor bloated agent instruction files (AGENTS.md, .cursorrules, .github/ files) into linked, progressively disclosed docs./agent-orchestrationBlueprint for orchestrating the agent pipeline from spec to planning, implementation, testing and debugging, plus when a second model is worth it, the intent→model map and cost guardrails./algorithmic-artGenerative and algorithmic art with p5.js: flow fields, particle systems, animations, WebGL, audio-reactive visuals; exports HTML, PNG, GIF, MP4, SVG. Use for creative coding or any p5.js visual./anchor-reviewSingle-model adversarial review technique — 3-lens analysis with confidence scoring and self-challenge/api-client-patternsTyped client-side API consumption: fetch wrappers, zod validation, auth injection, TanStack Query (useQuery, useMutation, optimistic updates), tRPC, OpenAPI codegen, pagination. Use when consuming REST or tRPC APIs.