pf-unit-test-generator

Generate a unit test file for a React component using Testing Library. Use when adding test coverage to new or existing components.

8 stars

Best use case

pf-unit-test-generator is best used when you need a repeatable AI agent workflow instead of a one-off prompt.

Generate a unit test file for a React component using Testing Library. Use when adding test coverage to new or existing components.

Teams using pf-unit-test-generator should expect a more consistent output, faster repeated execution, less prompt rewriting.

When to use this skill

  • You want a reusable workflow that can be run more than once with consistent structure.

When not to use this skill

  • You only need a quick one-off answer and do not need a reusable workflow.
  • You cannot install or maintain the underlying files, dependencies, or repository context.

Installation

Claude Code / Cursor / Codex

$curl -o ~/.claude/skills/pf-unit-test-generator/SKILL.md --create-dirs "https://raw.githubusercontent.com/patternfly/ai-helpers/main/plugins/react/skills/pf-unit-test-generator/SKILL.md"

Manual Installation

  1. Download SKILL.md from GitHub
  2. Place it in .claude/skills/pf-unit-test-generator/SKILL.md inside your project
  3. Restart your AI agent — it will auto-discover the skill

How pf-unit-test-generator Compares

Feature / Agentpf-unit-test-generatorStandard Approach
Platform SupportNot specifiedLimited / Varies
Context Awareness High Baseline
Installation ComplexityUnknownN/A

Frequently Asked Questions

What does this skill do?

Generate a unit test file for a React component using Testing Library. Use when adding test coverage to new or existing components.

Where can I find the source code?

You can find the source code on GitHub using the link provided at the top of the page.

SKILL.md Source

Generate a comprehensive unit test file for the given React component.

## Input

The user will provide a component file path or component code. Read the component source before generating tests.

## Context Detection

Determine if the component is part of a component library (patternfly-react, patternfly-chatbot, or similar) or a consumer application. Check whether the component lives in a library source tree or an application codebase. This determines the testing approach — see "Component Library Contributions" below for adjustments.

## How to Generate

1. Identify what the component does: rendering, user interactions, conditional states, async operations.
2. Look up any PatternFly components used so you understand their expected props and behaviors.
3. Generate a complete test file covering all branches.

## Test File Structure

```typescript
import { render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
```

Organize tests into `describe` blocks by behavior: `rendering`, `user interactions`, `conditional rendering`, `async operations`, `accessibility` — only include sections that apply.

## Rules

**Queries** — use in this order:
1. `getByRole` (always first choice)
2. `getByLabelText`
3. `getByText`
4. `getByTestId` (last resort only)

**Interactions** — always `userEvent`, never `fireEvent`:
```typescript
const user = userEvent.setup();
await user.click(screen.getByRole("button", { name: "Save" }));
```

**Mocking** — mock at the network boundary:
- Mock API calls and external services
- Never mock child components or PatternFly components
- Place all mocks at top of file
- `jest.clearAllMocks()` in `beforeEach`

**Async** — prefer `findBy*` over `waitFor` for waiting on elements:
```typescript
expect(await screen.findByText("Success")).toBeInTheDocument();
```

Use `waitFor` only for non-query assertions:
```typescript
await waitFor(() => {
  expect(onComplete).toHaveBeenCalled();
});
```

**What to test:**
- Component behavior from the user's perspective
- All conditional rendering branches (loading, error, empty, populated)
- User interactions and their effects
- Callback invocations with correct arguments

**What NOT to test:**
- PatternFly component internals (they're already tested)
- Implementation details (state, internal functions)

**CSS classes** — test with `toHaveClass` when classes are part of the component's public API (e.g., modifier classes, conditional styling). Don't test internal or structural classes that are implementation details.

## Component Library Contributions

When testing a component within a component library (patternfly-react, patternfly-chatbot, etc.), these adjustments apply. The "user" of a library component is a developer consuming its API — so test the API contract.

**Mocking child components** — default to mocking child components for unit isolation:
```typescript
jest.mock('../Header', () => ({
  Header: ({ children, ...props }) => <h1 {...props}>{children}</h1>
}));
```
Exception: don't mock when the parent-child interaction is the behavior being tested (e.g., a composite component where orchestration between children is the point).

**Coverage checklist** — cover these for every library component:
1. Default rendering with only required props
2. Prop variations — each prop value produces expected output
3. Custom className — merges with internal classes
4. Spread props — extra props forwarded to root element
5. Children — renders children correctly
6. Callbacks — event handlers fire with correct arguments
7. Conditional rendering — elements show/hide based on props
8. Accessibility — ARIA roles, labels, keyboard interaction

**Snapshots** — use for component structure and element ordering. Do not use snapshots to verify CSS classes — use `toHaveClass` instead:
```typescript
const { asFragment } = render(<MyLayout />);
expect(asFragment()).toMatchSnapshot();
```

**File organization** — one test file per exported component, colocated with the source:
```text
Button/
├── Button.tsx
├── Button.test.tsx
├── ButtonVariant.tsx
└── ButtonVariant.test.tsx
```

**PatternFly-specific conventions** — follow the [PatternFly testing wiki](https://github.com/patternfly/patternfly-react/wiki/React-Testing-Library-Basics,-Best-Practices,-and-Guidelines). Use `test()` for top-level tests and `it()` inside `describe()` blocks:
```typescript
test('renders with default props', () => { ... });

describe('when disabled', () => {
  it('has disabled attribute', () => { ... });
  it('does not fire onClick', () => { ... });
});
```

## Output

Output the complete test file ready to save. Name it `ComponentName.test.tsx` matching the source file.

Related Skills

pf-prototype-mode

8
from patternfly/ai-helpers

Enable prototype mode for React apps with grayscale styling and a banner overlay. Use when demoing early concepts, presenting wireframes, or preventing stakeholders from fixating on visual polish.

pf-project-scaffolder

8
from patternfly/ai-helpers

Scaffolds PatternFly React projects with PF6-safe dependencies, imports, and starter layout. Use when creating a new PatternFly app or bootstrapping a migration sandbox.

pf-import-checker

8
from patternfly/ai-helpers

Audit and fix invalid PatternFly import paths across packages. Use when imports fail, modules are unresolved, or after upgrading PatternFly versions.

pf-component-structure

8
from patternfly/ai-helpers

Audit PatternFly React component nesting, wrapper hierarchies, and layout structure. Use when scanning for hierarchy violations or debugging spacing caused by missing wrapper components.

write-example-description

8
from patternfly/ai-helpers

Write and refine example descriptions for PatternFly.org component and demo pages. Use when authoring or updating the prose in PatternFly example markdown files.

summarize-jira-issues

8
from patternfly/ai-helpers

Summarize your current sprint workload from Jira — assigned issues, contributor roles, and priorities. Use when checking what's left in the sprint or deciding what to work on next.

semantic-release-troubleshooting

8
from patternfly/ai-helpers

Diagnose and fix semantic-release issues when a specific version is not being released. Use when semantic-release skips a version, fails to release, or when troubleshooting after git push --force, squashed commits, permission errors, or reference already exists.

quarterly-initiative-report

8
from patternfly/ai-helpers

Generate quarterly Jira status reports with RAG assessment, blocker tracking, and next-quarter recommendations. Use when preparing quarterly initiative reviews or tracking epic progress.

pf-tokens

8
from patternfly/ai-helpers

Build CSS design tokens for PatternFly core and copy them to the PatternFly repository. Use when regenerating tokens after design changes or during release preparation.

pf-org-version-update

8
from patternfly/ai-helpers

Update patternfly-org for a new PatternFly release — resolve versions, update package.json and versions.json, and provide build steps. Use when cutting a PF release or release candidate.

pf-create-issue

8
from patternfly/ai-helpers

Create well-structured GitHub issues for PatternFly repositories with templates, follow-up tracking, and duplicate detection. Use when filing bugs, feature requests, or cross-repo follow-ups.

pf-bug-triage

8
from patternfly/ai-helpers

Triage PatternFly bug reports — assess completeness, suggest fixes, identify affected components, and recommend assignees. Use when reviewing new bug issues or preparing them for assignment.