agentleFS
vlad-ryzhkovvlad-ryzhkov/ai-context-engineering-for-frontend/.claude/skills/component-tests/SKILL.md

component-tests

Skill2 starsChanged 8 months agoUnlicenseView on GitHub

Generate Vitest + Testing Library tests for React or Vue components. Supports single component, file path, or directory/glob targets. Auto-detects component type (feature/ui) to determine required test states. A11y pre-audit runs before test writing to inform ARIA-based selectors. Requires framework parameter [react|vue]. Do not use for E2E tests — use /e2e-tests instead.

1 other project uses a version of this.

Adopted by

Most recently taken up by

The file

We split this skill into the rules it gives an agent

12 rules. About 0 are common, 4 are distinctive, and 8 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈4

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 8

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    Before execution the agent MUST load: .claude/protocols/gardener.md

    line 21
  2. Very specific:

    When --type is not provided, scan the component file imports:

    line 55
  3. Very specific:

    Check framework param. BLOCKER if missing.

    line 131
  4. Very specific:

    When --diff is provided:

    line 135
  5. Very specific:

    If no component files remain → output "No new/modified components in diff" → STOP (not an error).

    line 146
  6. Very specific:

    Import describe, it, expect from @jest/globals (if using ESM) or rely on globals

    line 171
  7. Very specific:

    Use jest.fn() instead of vi.fn(), jest.mock() instead of vi.mock()

    line 172
  8. Very specific:

    Run command: npx jest {test-file-path} instead of npx vitest run {test-file-path}

    line 173
  9. Distinctive:

    If found, note file path and function signature.

    line 183
  10. Distinctive:

    Read CLAUDE.md for stack config.

    line 184
  11. Distinctive:

    Use custom render utility from step 2 if applicable

    line 211
  12. Distinctive:

    Use ARIA roles from step 4b for selectors

    line 212

≈ “Common” is an estimate: at least 1 in 5 of the 350,495 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Recommended Flow

/component-gen → /api-bind → /component-tests (auto-detects --type from component imports)


SYSTEM REQUIREMENTS

Before execution the agent MUST load: .claude/protocols/gardener.md


Component Tests Generator

Generates Vitest or Jest + Testing Library tests for React or Vue components. Auto-detects test runner (Vitest vs Jest) from project config. Auto-detects component type (feature/ui) from imports to determine required test states. Each test validates behavior from the USER's perspective (roles, labels, text), not implementation.

When to Use

  • Component generated by /component-gen needs test coverage
  • Existing component needs tests added
  • Auditing test quality of an existing suite

Input Validation (MANDATORY)

❌ BLOCKER if framework not provided.

Accepted invocation formats:
  /component-tests [react|vue] ComponentName
  /component-tests [react|vue] src/path/to/Component.tsx
  /component-tests [react|vue] src/features/cart
  /component-tests [react|vue] ComponentName --type [ui|feature]
  /component-tests [react|vue] --diff [base-branch]

`--type` is optional. If omitted, auto-detect from component imports (see Component Type Detection).
`--diff` mode: generate tests only for components changed since `base-branch` (default: `main`).

Component Type Detection

When --type is not provided, scan the component file imports:

Classify as feature if any present:

  • useQuery / useMutation / useInfiniteQuery (TanStack Query)
  • useFetch / useAsyncData (Vue composables)
  • defineStore / useStore (Pinia)
  • create( imported from zustand

Classify as ui otherwise.

Log resolved type: [auto-detected: feature] or [auto-detected: ui] before proceeding.

Input Context

context: fork — you cannot see chat history before your invocation.

Allowed inputs: Framework param, component file path, CLAUDE.md.

Protocol

BANNED (all frameworks)

  • Testing implementation details (internal state, hook internals) — FORBIDDEN
  • querySelector or getByTestId as primary selector — use role/label/text
  • Mocking internal hooks to test return values — test behavior, not hooks
  • expect(container).toMatchSnapshot() as primary assertion — too brittle
  • Empty describe blocks or test stubs it.todo() counted as coverage — FORBIDDEN
  • setTimeout / sleep in tests — use waitFor or findBy*

Framework-Specific BANNED

React: act() wrapping when userEvent handles it automatically

Vue: Direct mutation of props in tests — use re-mount with new props

Selector Priority (Testing Library)

1. getByRole (button, heading, list, listitem, alert, status)
2. getByLabelText (form fields)
3. getByText (readable content)
4. getByPlaceholderText (inputs)
5. getByAltText (images)
LAST RESORT: getByTestId (add data-testid to component only if no other option)

Test Structure Requirements

--type feature (Smart/Async)

Required — all 4 states:

  1. Loading state — skeleton/spinner present, accessible label
  2. Error state — error message rendered, retry button present
  3. Empty state — no-data message (distinct from error)
  4. Success state — actual data rendered, accessible list items
  5. Interaction — retry button click triggers refetch

Additional tests for: form submit/validation, sorting/filtering, pagination.

--type ui (Presentational)

Required:

  1. Prop variants — renders correctly for each significant prop (size, variant, disabled)
  2. User interactions — click, type, keyboard events the component handles
  3. Callbacks — emitted events or callback props called with correct args

FORBIDDEN for --type ui: hallucinated async states. Do NOT add isLoading, isError, or empty-state tests to presentational components.

Workflow

Step 1 — Validate

Check framework param. BLOCKER if missing. Resolve --type: ui | feature | auto (default).

Step 2-DIFF — Diff-Based Discovery (only for --diff mode)

When --diff is provided:

  1. Resolve base branch: use provided branch or default to main.
  2. Get changed component files:

    git diff --name-only origin/{base}...HEAD -- '*.tsx' '*.vue'
  3. Filter out non-component files:
    • Exclude: *.test.*, *.spec.*, *.d.ts, index.ts (barrel files), *.stories.*
  4. If no component files remain → output "No new/modified components in diff" → STOP (not an error).
  5. For each remaining file → proceed to Step 4 (Per-File Loop).
  6. Skip Step 2 (Discover & Glob) entirely — diff provides the file list.

Step 1b — Detect Test Runner

Auto-detect which test runner the project uses:

ls vitest.config.* vite.config.* jest.config.* 2>/dev/null
grep -E '"vitest"|"jest"' package.json | head -5

Detection priority:

  1. vitest.config.* exists → Vitest
  2. jest.config.* exists → Jest
  3. package.json has "vitest" in devDependencies → Vitest
  4. package.json has "jest" in devDependencies → Jest
  5. Neither found → default to Vitest (matches template defaults)

Log resolved runner: [runner: vitest] or [runner: jest].

Runner differences (Jest only):

  • Import describe, it, expect from @jest/globals (if using ESM) or rely on globals
  • Use jest.fn() instead of vi.fn(), jest.mock() instead of vi.mock()
  • Run command: npx jest {test-file-path} instead of npx vitest run {test-file-path}

Step 2 — Discover & Glob

  1. Resolve Target to file list:
    • By name: glob src/**/{Name}/{Name}.{tsx,vue,ts} → if multiple matches, prefer src/features/
    • By path: use as-is
    • By directory: glob {dir}/**/*.{tsx,vue}
  2. Glob root for test setup: vitest.setup.ts / vitest.setup.js / jest.setup.ts / jest.setup.js. If found, read it.
  3. Grep src/ for custom render utils: renderWithProviders, createTestWrapper, mountWithPinia. If found, note file path and function signature.
  4. Read CLAUDE.md for stack config.

Step 3 — Load References

Load references/{framework}-testing.md.

Step 4 — Per-File Loop

For each discovered file:

4a. Auto-detect --type (if not explicit): scan imports per Component Type Detection. Log result.

4b. A11y Pre-Audit (before writing tests):

  • Scan semantic HTML — list available button, input, nav, main, etc.
  • List explicit role="..." attributes
  • Flag div-as-button or span-as-link (note as A11y issue)
  • Flag interactive elements missing aria-label or visible label
  • Output: list of ARIA roles/labels → these become the getByRole/getByLabelText selectors in 4d

4c. Plan test cases based on resolved --type. Bullet list only — no code yet.

4d. Generate test file:

  • Output path: adjacent to the source file (regardless of --type classification)
    • React: {source-dir}/{ComponentName}.test.tsx
    • Vue: {source-dir}/{ComponentName}.test.ts
  • Use custom render utility from step 2 if applicable
  • Use ARIA roles from step 4b for selectors

4e. Run tests (use detected runner from Step 1b):

# Vitest (default)
npx vitest run {test-file-path} 2>&1 | tail -30

# Jest (if detected)
npx jest {test-file-path} --no-coverage 2>&1 | tail -30

4f. Fix failures (per-file budget):

  • Max 2 fix iterations per file
  • On 3rd failure: add at top of test file:

    // TODO: Tests PARTIAL — unresolved after 2 fix attempts.
    // Blocker: {error summary}

    Mark file PARTIAL. Continue to next file — do NOT halt the session.

4g. Post-check BANNED patterns:

grep -n "querySelector\|snapshot\|sleep\|setTimeout\|\.toBe(true)\b" {test-file}

Step 5 — Gardener → SKILL COMPLETE

Escalation (Per-File, Non-Blocking)

Each file has an independent 2-fix-iteration budget. On 3rd failure: add TODO comment, mark PARTIAL, continue to next file (see Workflow Step 4f).

Session-level ESCALATION (full halt) ONLY when > 50% of batch files are PARTIAL with the same root cause:

🚨 ESCALATION: Batch-wide failure — {root cause}
Files affected: {list}
Likely fix: {recommended action}
⏸️ Awaiting decision.

Quality Gates

  • Framework param validated
  • --type resolved (explicit or auto-detected) and logged
  • vitest.setup.ts and custom render utilities discovered or confirmed absent
  • A11y pre-audit completed per file — ARIA roles extracted before test writing
  • [--type feature] All 4 states have ≥1 test each
  • [--type ui] Prop variants and interactions tested. No hallucinated async states.
  • Selectors use getByRole / getByLabelText / getByText (not querySelector)
  • No snapshot tests as primary assertion
  • No sleep or setTimeout — use waitFor / findBy*
  • npx vitest run — all PASS or PARTIAL with // TODO comment

References

  • React testing patterns: references/react-testing.md
  • Vue testing patterns: references/vue-testing.md
  • Anti-patterns: .claude/fe-antipatterns/_index.md

Completion Contract

✅ SKILL COMPLETE: /component-tests
├─ Framework: [react | vue]
├─ Scope: [Single: ComponentName | Batch: X files]
├─ Component Types: [X feature | Y ui]
├─ Test Runs: [X PASS | Y FAIL | Z PARTIAL]
└─ A11y Pre-Audit: [PASS | N issues across M files]
⚠️ SKILL PARTIAL: /component-tests
├─ Framework: [react | vue]
├─ Scope: [Single: ComponentName | Batch: X files]
├─ Component Types: [X feature | Y ui]
├─ Test Runs: [X PASS | Y FAIL | Z PARTIAL]
├─ A11y Pre-Audit: [PASS | N issues across M files]
└─ Blockers: [per-file TODO reasons]

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.