agentleFS
Piyush8296Piyush8296/claude-workspace/.claude/skills/testing-strategy/SKILL.md

testing-strategy

Skill2 starsChanged 7 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.

37 other projects use a version of this.

Adopted by

Most recently taken up by

Used with

Projects with it also use api-design, observability and 7 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.
  • MicrosoftSkill

    api-design

    Guide for designing and documenting RESTful APIs. Use when asked to design an API, create endpoints, or document an API.

    Also in 10 projects that use this

  • OpenAISkill

    observability

    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 5 projects that use this

  • Microsoft AzureSkill

    git-workflow

    Squad branching model: dev-first workflow with insiders preview channel

    Also in 6 projects that use this

  • CloudAI-XSkill

    database-design

    Designs database schemas, indexing strategies, query optimization, and migration patterns for SQL and NoSQL databases. Use when designing tables, optimizing queries, fixing N+1 problems, planning migrations, or when asked about database performance, normalization, ORMs, or data modeling.

    Also in 3 projects that use this

  • OpenAISkill

    verification-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 6 projects that use this

  • CloudflareSkill

    receiving-code-review

    Use when receiving code review feedback, before implementing suggestions, especially if feedback seems unclear or technically questionable - requires technical rigor and verification, not performative agreement or blind implementation

    Also in 3 projects that use this

  • +3 more from openai

The file

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 33 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
  1. Distinctive:

    TDD when practical: Write the failing test first.

    line 11
  2. Distinctive:

    react-patterns: Test all 4 component states

    line 227
  3. Distinctive:

    systematic-debugging: Write reproducing test before fixing bugs

    line 228

“Common” is measured: kept by at least 6 in 10 of the 33 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.

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

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 tests

Factory 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

AreaTargetNotes
Utilities95%+Pure functions, easy to test fully
Hooks90%+All branches including error paths
Components80%+All states: loading, error, empty, success
Pages/Routes70%+Integration level, key user flows
E2ECritical pathsAuth, checkout, core CRUD only

Anti-Patterns

BadGoodWhy
Testing mock behaviorTesting rendered outputMock is not the product
await sleep(1000)await waitFor(() => ...)Deterministic, not timing-dependent
Snapshot tests for logicExplicit assertionsSnapshots don't explain intent
Testing useState directlyTesting through UI interactionImplementation detail
One mega test fileFocused describe blocksEasier 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

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.