agentleFS
digital-go-jpdigital-go-jp/design-system-example-components-react/.agents/skills/write-tests/SKILL.md

write-tests

Skill685 starsChanged 26 days agoMITView on GitHub

Write tests for components in this project. Covers Storybook-based UI tests (composeStories + vitest-browser-react), unit tests for hooks/utils, and the conventions that keep tests deterministic and meaningful.

79 other projects use a version of this.

Adopted by

Most recently taken up by

Used with

Projects with it also use close-spec, design-with-images and 10 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.
  • dzhngSkill

    close-spec

    When a spec under specs/<feature>/ is done shipping (a write-spec build, or any planned task that produced a spec), archive it to specs/done/ and rewrite it from a build-plan into a durable rationale — the why, the principles, the invariants — pointing back to the real code for the how. Use when implementation has landed and the plan no longer matches what shipped, or the user says a feature/spec is finished. Pairs with [write-spec](../write-spec/SKILL.md) (the plan this closes) and [review](../review/SKILL.md) (run before closing).

    Also in 5 projects that use this

  • dzhngSkill

    design-with-images

    Explore UI and visual design with image generation, then iterate the real implementation against the user-selected concept. Use when brainstorming visual directions, offering mockup variants, or implementing an approved generated design; do not stop at the mockups or the first code approximation.

    Also in 5 projects that use this

  • transitive-bullshitSkill

    compare-screenshots

    Compare screenshots against the intended design, distinguishing approved references from historical baselines. Use for iterative implementation matching, before/after visual review, objective image telemetry, or checking a lone capture for flat, empty, or badly framed content.

    Also in 5 projects that use this

  • LucasMatuszewskiSkill

    audit-agents

    Audit and maintain agent configuration files (.claude/agents, AGENTS.md, CLAUDE.md, agent-memory). Checks for duplicates, outdated info, naming conflicts, wrong technical facts, and files over 200 lines. Fixes all issues and commits.

    Also in 5 projects that use this

  • wolverin0Skill

    audit-decisions

    Standardize remediation decisions, baseline-policy entries, and legal-review banners for accepted, deferred, or policy-blocked audit findings.

    Also in 4 projects that use this

  • rhnfzlSkill

    explore-unknowns

    Walk the user through mapping the unknowns of a task before, during, and after they build it, and hand them a four-quadrant map (settled ground, open decisions, taste, and landmines) they keep. Reach for this eagerly whenever a request is ambiguous or underspecified, the codebase or domain is unfamiliar, the user will "know it when they see it", a reference implementation must be understood before porting, a build-queue or architecture-changing task is about to start, a mid-build deviation needs capturing, or a finished change needs buy-in or verified understanding before merge. Trigger even when the skill is not named: "do a blindspot pass", "find my unknown unknowns", "interview me about this change", "brainstorm the approach for a task I am about to build", "help me scope this", "what am I missing here", "plan this before I build", "I know nothing about X in this codebase". When a territory profile is present it reads memory and the graph first and feeds the map into the build pipeline; without one it degrades to a plain general map. Not for trivial or mechanical tasks with clear acceptance criteria, single-fact lookups, pure debugging of a known symptom, or pure code review, those have their own tools. Do not use it to run the build itself; the map is the deliverable and implementation remains a separate task, whether it has not started or is already underway.

    Also in 5 projects that use this

  • +5 more from dzhng

The file

We split this skill into the rules it gives an agent

11 rules. 0 are common, 3 are distinctive, and 8 are very specific to this project.

  • 0

    Common

    Most of the 74 edited versions we read keep these.

  • 3

    Distinctive

    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:

    Not every component needs a <Name>.test.tsx.

    line 29
  2. Distinctive:

    Add tests when the component has actual behavior to verify: focus trapping, keyboard nav, event payloads, controlled state, conditional …

    line 37
  3. Very specific:

    Prefer semantic queries. Fall back to document.querySelector only for things without an accessible name (internal data-* attributes, …

    line 68
  4. Very specific:

    Use expect.element(locator).toXxx() for async DOM updates (rerenders, animations) — it retries.

    line 85
  5. Very specific:

    Use expect(value).toXxx() for synchronous values.

    line 86
  6. Very specific:

    Use userEvent from vitest/browser — it dispatches real keystrokes via CDP.

    line 117
  7. Very specific:

    After a re-render, locators auto-refresh, but raw DOM references go stale — re-query with document.querySelector.

    line 131
  8. Very specific:

    If the component reads new Date() (calendars, "today" highlighting, formatting), freeze the clock.

    line 137
  9. Distinctive:

    Add a comment near the top of the file describing what state the fake date implies (e.g.

    line 156
  10. Very specific:

    When a component splits out a hook (useFooAnnouncer.ts) or a util (fooHelpers.ts), test it directly with Vitest.

    line 164
  11. Distinctive:

    Before declaring tests done:

    line 201

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

Test runner setup

This project runs all Vitest tests in browser mode via Playwright + Chromium. There are two projects in vite.config.ts:

  • storybook — Storybook-driven test runs (npm run test:storybook)
  • unit — src/**/*.test.{ts,tsx} (npm run test:unit)

Both projects use the same browser provider — there is no jsdom setup. Hook / util tests therefore also run in the browser. If you need to verify pure logic without a DOM, you can still write a .test.ts under the unit project; it will execute in Chromium but jsdom-style globals are simply unused.

Test categories

Two buckets, decided by what is being verified:

CategoryFileProjectVerifies
UI / interaction<Name>.test.tsxstorybook (or unit for non-Story tests)Rendering, ARIA, focus, keyboard nav, drag & drop, event handlers
Unit<Name>.test.ts (hook/util)unitPure functions, hook logic in isolation
Visual(covered by Storybook docs page + manual review)—Mirrors the HTML reference; verified manually via npm run storybook

There is no VRT pipeline in this project — visual parity is checked manually against the HTML reference. Do not invent VRT setup.

When to skip tests entirely

Not every component needs a <Name>.test.tsx. Skip it when all of the following are true:

  • The component has no JS behavior — no event handlers, no state, no focus management beyond browser defaults.
  • It is a pass-through wrapper around native elements with data-* attributes for styling, with no logic in the body.
  • The HTML reference has no behavior tests of its own (only VRT under *.test.js calling resetCssVrt).

In those cases, visual parity via Storybook + the component's .mdx docs page is sufficient. Adding assertions like "data-current is set when current=true" only re-tests JSX prop-passing — the build's type check already covers it.

Add tests when the component has actual behavior to verify: focus trapping, keyboard nav, event payloads, controlled state, conditional rendering driven by interaction, etc.

Reference

  • src/components/FileUpload/FileUpload.test.tsx — canonical example of a UI test that reuses Stories via composeStories.

UI / interaction tests

Reuse Stories via composeStories

Tests reuse Storybook Stories so that the demo and the test stay aligned. Do not write a separate test-only render.

import { composeStories } from '@storybook/react-vite';
import { describe, expect, test } from 'vitest';
import { page, userEvent } from 'vitest/browser';
import { render } from 'vitest-browser-react';
import * as stories from './Foo.stories';

const { Playground } = composeStories(stories);

describe('Foo', () => {
  test('renders the trigger', async () => {
    render(<Playground />);
    await expect.element(page.getByRole('button', { name: '開く' })).toBeVisible();
  });
});

Querying elements

Prefer semantic queries. Fall back to document.querySelector only for things without an accessible name (internal data-* attributes, structural assertions).

NeedUse
Element with a role / accessible namepage.getByRole('button', { name: '送信' })
Element by visible textpage.getByText('メッセージ')
Internal state node, attribute checkdocument.querySelector('[data-state="open"]')
Repeated queries in one fileDefine DOM helper functions at the top of the file
const getRoot = () => document.querySelector('.group\\/foo') as HTMLElement;
const getOpenItems = () =>
  Array.from(document.querySelectorAll('[data-state="open"]'));

Assertions

  • Use expect.element(locator).toXxx() for async DOM updates (rerenders, animations) — it retries.
  • Use expect(value).toXxx() for synchronous values.
  • Always assert against a concrete expected value. "Changed from initial" tells you nothing about correctness.
// DO: concrete expected value
await page.getByRole('button', { name: '前の月' }).click();
expect(getCurrentMonth()).toBe('5月');

// DON'T: just "it changed"
const initial = getCurrentMonth();
await page.getByRole('button', { name: '前の月' }).click();
expect(getCurrentMonth()).not.toBe(initial);

For event handlers, assert on the payload, not just that it fired:

const handler = vi.fn();
ref.current.addEventListener('date-selected', handler);

await userEvent.click(getButtonForDay(20));

expect(handler).toHaveBeenCalledOnce();
const { date } = handler.mock.calls[0][0].detail;
expect(date.getFullYear()).toBe(2025);
expect(date.getMonth()).toBe(5);
expect(date.getDate()).toBe(20);

User interaction

Use userEvent from vitest/browser — it dispatches real keystrokes via CDP.

await userEvent.keyboard('{ArrowDown}');
await userEvent.keyboard('{Escape}');
await userEvent.keyboard('{ }'); // Space
await userEvent.tab();
await userEvent.tab({ shift: true });

await page.getByRole('button', { name: '送信' }).click();

Notes:

  • Locator .click() waits for the element to be enabled. To click an aria-disabled="true" element, grab the DOM node and call element.click().
  • After a re-render, locators auto-refresh, but raw DOM references go stale — re-query with document.querySelector.

Determinism

Time-dependent components

If the component reads new Date() (calendars, "today" highlighting, formatting), freeze the clock. Otherwise tests pass on Tuesday and fail on Wednesday.

import { afterEach, beforeEach, vi } from 'vitest';

const FAKE_NOW = new Date(2025, 5, 15, 12, 0, 0); // 2025-06-15

beforeEach(() => {
  vi.useFakeTimers({ toFake: ['Date'] });
  vi.setSystemTime(FAKE_NOW);
});

afterEach(() => {
  vi.useRealTimers();
});

toFake: ['Date'] is required — without it, setTimeout and requestAnimationFrame are also faked, which breaks await new Promise(r => setTimeout(r, 0)) and similar. Always restore real timers in afterEach.

Add a comment near the top of the file describing what state the fake date implies (e.g. "2025-06-15 → calendar opens on June, day 15 is today"). It saves the next reader from recomputing.

Independence

Each test should set up its own state. Do not lean on test ordering or a shared, mutated module-level fixture.

Unit tests for hooks / utils

When a component splits out a hook (useFooAnnouncer.ts) or a util (fooHelpers.ts), test it directly with Vitest. The unit project also runs in Chromium (see Test runner setup), so DOM globals are available but not required — for pure logic just import and assert.

import { describe, expect, test } from 'vitest';
import { parseSize } from './fileSize';

describe('parseSize', () => {
  test('parses MB units', () => {
    expect(parseSize('10MB')).toBe(10 * 1024 * 1024);
  });

  test('returns null for invalid input', () => {
    expect(parseSize('abc')).toBeNull();
  });
});

For React hooks, use renderHook from vitest-browser-react, or wrap the hook in a tiny test component.

What to cover

Aim for one assertion per behavior. Use these categories as a checklist when planning tests:

CategoryExamples
Initial renderDefault state, ARIA roles, default attribute values
Conditional renderingItem count, enabled/disabled state
User interactionClick, keyboard navigation, selection toggle
EventsCustom event firing, detail payload, bubbling
Boundary behaviorOut-of-range input ignored, min/max clamping
Public APIImperative methods (if exposed), prop changes
Dynamic prop changesRe-render on prop update
Accessibilityaria-label, aria-selected, focus management, live regions
Edge casesEmpty input, leap years, unmount/remount

Pre-flight

Before declaring tests done:

  • No not.toBe(initial) style assertions — every check has a concrete expected value
  • Time-dependent code is wrapped in vi.useFakeTimers({ toFake: ['Date'] }) and restored in afterEach
  • Tests reuse Stories where the behavior is already in a Story
  • Semantic queries (getByRole, getByText) are used wherever the element has an accessible name
  • npm test passes locally

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.