testing-strategy
Skill2 starsChanged 6 months agoMITView on GitHub
Testing methodology, factory patterns, mocking strategies, and TDD workflow for React + TypeScript. Use when writing tests, setting up test infrastructure, or planning test coverage.
We split this skill into the rules it gives an agent
3 rules. 0 are common, 3 are distinctive, and 0 are very specific to this project.
0
Common
Most of the 42 edited versions we read keep these.
3
Distinctive
This author's own choices. Worth a look.
0
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 11
TDD when practical: Write the failing test first.
- Distinctive: line 227
react-patterns: Test all 4 component states
- Distinctive: line 228
systematic-debugging: Write reproducing test before fixing bugs
“Common” is measured: kept by at least 6 in 10 of the 42 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Testing Strategy
Philosophy
- Test behavior, not implementation. Refactors should never break tests unless behavior changes.
- TDD when practical. Write the failing test first. Red → Green → Refactor.
- Factory pattern for all test data.
getMockX(overrides?)— no duplicated fixtures. - Test the contract. Props in, rendered output + callbacks out.
Test Pyramid
/\ E2E (Playwright)
/ \ Critical paths only: auth, checkout, core CRUD
/ \ ~10% of tests
/------\ Integration
/ \ Feature workflows, API + rendering
/ \ ~20% of tests
/------------\ Unit
/ \ Components, hooks, utilities
/ \ ~70% of testsFactory Pattern
Props Factory
import { type ComponentProps } from 'react';
const getDefaultProps = (
overrides?: Partial<ComponentProps<typeof UserCard>>
) => ({
name: 'Jane Doe',
email: 'jane@example.com',
role: 'admin' as const,
onEdit: vi.fn(),
onDelete: vi.fn(),
...overrides,
});Data Factory
let idCounter = 0;
export function getMockUser(overrides?: Partial<User>): User {
idCounter += 1;
return {
id: `user-${idCounter}`,
name: 'Test User',
email: `test${idCounter}@example.com`,
role: 'viewer',
createdAt: new Date('2024-01-01').toISOString(),
...overrides,
};
}
export function getMockUsers(count: number, overrides?: Partial<User>): User[] {
return Array.from({ length: count }, () => getMockUser(overrides));
}Query Result Factory
export function getMockQueryResult<T>(data: T, overrides?: Partial<UseQueryResult<T>>) {
return {
data,
isPending: false,
isError: false,
error: null,
refetch: vi.fn(),
...overrides,
};
}
// Usage
vi.mocked(useUsers).mockReturnValue(
getMockQueryResult(getMockUsers(3))
);
// Loading state
vi.mocked(useUsers).mockReturnValue(
getMockQueryResult(undefined, { isPending: true, data: undefined })
);Component Test Structure
import { render, screen, within } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { describe, it, expect, vi, beforeEach } from 'vitest';
describe('UserCard', () => {
const user = userEvent.setup();
const getProps = (overrides?: Partial<UserCardProps>) => ({
name: 'Jane Doe',
onEdit: vi.fn(),
...overrides,
});
beforeEach(() => {
vi.clearAllMocks();
});
it('renders user name', () => {
render(<UserCard {...getProps()} />);
expect(screen.getByText('Jane Doe')).toBeInTheDocument();
});
it('calls onEdit when edit button is clicked', async () => {
const onEdit = vi.fn();
render(<UserCard {...getProps({ onEdit })} />);
await user.click(screen.getByRole('button', { name: /edit/i }));
expect(onEdit).toHaveBeenCalledOnce();
});
it('shows loading skeleton when data is pending', () => {
render(<UserCard {...getProps()} isLoading />);
expect(screen.getByTestId('user-card-skeleton')).toBeInTheDocument();
});
});Hook Testing
import { renderHook, act } from '@testing-library/react';
describe('useCounter', () => {
it('increments count', () => {
const { result } = renderHook(() => useCounter({ initial: 0 }));
act(() => {
result.current.increment();
});
expect(result.current.count).toBe(1);
});
it('respects max value', () => {
const { result } = renderHook(() => useCounter({ initial: 9, max: 10 }));
act(() => {
result.current.increment();
result.current.increment(); // Should not exceed max
});
expect(result.current.count).toBe(10);
});
});Mocking Strategies
Module Mocking
// Mock at module level
vi.mock('@/hooks/useUsers', () => ({
useUsers: vi.fn(),
}));
// Type-safe mock access
const mockUseUsers = vi.mocked(useUsers);
// Configure per test
mockUseUsers.mockReturnValue(getMockQueryResult(getMockUsers(3)));API Mocking (MSW)
import { http, HttpResponse } from 'msw';
import { setupServer } from 'msw/node';
const handlers = [
http.get('/api/users', () => {
return HttpResponse.json(getMockUsers(3));
}),
http.post('/api/users', async ({ request }) => {
const body = await request.json();
return HttpResponse.json(getMockUser(body), { status: 201 });
}),
];
const server = setupServer(...handlers);
beforeAll(() => server.listen());
afterEach(() => server.resetHandlers());
afterAll(() => server.close());Coverage Targets
| Area | Target | Notes |
| Utilities | 95%+ | Pure functions, easy to test fully |
| Hooks | 90%+ | All branches including error paths |
| Components | 80%+ | All states: loading, error, empty, success |
| Pages/Routes | 70%+ | Integration level, key user flows |
| E2E | Critical paths | Auth, checkout, core CRUD only |
Anti-Patterns
| Bad | Good | Why |
| Testing mock behavior | Testing rendered output | Mock is not the product |
await sleep(1000) | await waitFor(() => ...) | Deterministic, not timing-dependent |
| Snapshot tests for logic | Explicit assertions | Snapshots don't explain intent |
Testing useState directly | Testing through UI interaction | Implementation detail |
| One mega test file | Focused describe blocks | Easier to debug failures |
Integration with Other Skills
- react-patterns: Test all 4 component states
- systematic-debugging: Write reproducing test before fixing bugs
- state-management: Mocking stores and query clients
Other versions52 projects use a version of this.
Word for word · 0
None found.
Edited · 0
None found.
Wrote their own version · 52
- anthropics/knowledge-work-plugins★ 34ksame name
- chthollyphile/folia-major★ 11ksame name
- Community-Access/accessibility-agents★ 409same name
- AnastasiyaW/codex-claude-code-config★ 213same name
- AnastasiyaW/claude-code-config★ 209same name
- irahardianto/awesome-agv★ 157same name
- Blushyes/reef★ 84same name
- shinpr/agentic-code★ 51same name
- addxai/enterprise-harness-engineering★ 44same name
- drafthq/draft★ 40same name
42 more not listed
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
Used alongsideProjects with it also use deploy-checklist, tech-debt and 8 more.
Other files people use alongside this one.
Files found in the same public projects as a version of this one, more often than they turn up anywhere else. Each project counts once, large collections count for less, and this file's own repository is left out.
AnthropicSkilldeploy-checklist
Pre-deployment verification checklist. Use when about to ship a release, deploying a change with database migrations or feature flags, verifying CI status and approvals before going to production, or documenting rollback triggers ahead of time.
Also in 4 projects that use this
AnthropicSkilltech-debt
Identify, categorize, and prioritize technical debt. Trigger with "tech debt", "technical debt audit", "what should we refactor", "code health", or when the user asks about code quality, refactoring priorities, or maintenance backlog.
Also in 4 projects that use this
MicrosoftSkillapi-design
Guide for designing and documenting RESTful APIs. Use when asked to design an API, create endpoints, or document an API.
Also in 8 projects that use this
MicrosoftSkilldeep-review
Multi-agent deep code review for regorus. Three diverse parallel discovery agents with context asymmetry, risk-triggered micro-passes, adversarial gap-finder, and verification with disproval mandates. Use for high-stakes changes.
Also in 3 projects that use this
OpenAISkillobservability
Vercel Observability expert guidance — Drains (logs, traces, speed insights, web analytics), Web Analytics, Speed Insights, runtime logs, custom events, OpenTelemetry integration, and monitoring dashboards. Use when instrumenting, debugging, or optimizing application performance and user experience on Vercel.
Also in 3 projects that use this
OpenAISkillverification-before-completion
Use when about to claim work is complete, fixed, or passing, before committing or creating PRs - requires running verification commands and confirming output before making any success claims; evidence before assertions always
Also in 5 projects that use this
- +4 more from anthropics
In this repository18 other files it gives its agents.
- CLAUDE.mdCLAUDE.md
- accessibilitySkill
- api-layerSkill
- auth-patternsSkill
- core-web-vitalsSkill
- css-architectureSkill
- design-intelligenceSkill
- error-handlingSkill
- frontend-designSkill
- i18nSkill
- monorepo-patternsSkill
- performance-optimizationSkill
- react-patternsSkill
- security-auditSkill
- seo-fundamentalsSkill
- state-managementSkill
- structured-dataSkill
- systematic-debuggingSkill
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
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.

