Logo de Component Testing

Component Testing

Organização
staple-lab
component-testing

Use when writing or reviewing tests for design system components - behavioural tests with Vitest and Testing Library, keyboard and focus tests, axe accessibility assertions, controlled/uncontrolled parity, visual regression, and Storybook play functions. Triggers on "test this component", "a11y test", "visual regression", "storybook test".

Add to TypingMind

Visão geral

Publicado porstaple-lab
Repositóriodesign-system-skills
Nome da habilidadecomponent-testing
Estrelas
7
Forks
0
Arquivos incluídos
Somente instruções
LicençaMIT
Links
  • Instruções em Markdown

    Um arquivo SKILL.md que o modelo carrega sob demanda, consumindo tokens apenas quando uma solicitação é realmente relevante para a habilidade.

  • Funciona com qualquer LLM

    As habilidades de IA são escritas em Markdown simples, não em código específico de um provedor. Por isso, funcionam com GPT, Claude, Gemini, Grok ou um modelo local.

  • Sem arquivos extras

    Tudo de que o modelo precisa está nas instruções — sem arquivos extras para sincronizar.

  • Código aberto

    Publicada por staple-lab no GitHub. Leia os arquivos da habilidade antes de instalá-la.

Instalação

Instale a habilidade de IA Component Testing no TypingMind para usá-la com qualquer LLM ou adicione-a a outro agente que leia SKILL.md.

1

Instalar no TypingMind

O TypingMind instala uma habilidade diretamente da pasta dela no GitHub — lê o arquivo SKILL.md, reúne os arquivos de recursos em um pacote e armazena o resultado localmente.

  1. Abra o app e vá para Plugins → Habilidades.
  2. Escolha "Instalar do GitHub".
  3. Cole a URL abaixo, que aponta para a pasta da habilidade, e confirme.
    https://github.com/staple-lab/design-system-skills/tree/main/plugins/design-system/skills/component-testing
  4. Ative a habilidade em cada chat em que quiser disponibilizá-la.
Plugins → Habilidades → Adicionar habilidade → Via URL do GitHub. Depois, cole a URL da pasta e pressione Continuar.
2

Instalar em outro agente

Qualquer agente que leia o formato Agent Skills pode usar esta habilidade — copie a pasta para o diretório de habilidades desse agente.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/staple-lab/design-system-skills.git /tmp/design-system-skills
mkdir -p .claude/skills
cp -r /tmp/design-system-skills/plugins/design-system/skills/component-testing .claude/skills/component-testing
Reinicie Claude Code após copiar para que a nova habilidade seja reconhecida.

Use no TypingMind

Ative Component Testing em qualquer chat do TypingMind e o modelo cuida do resto. O nome e a descrição da habilidade ficam no prompt do sistema e, assim que uma solicitação relevante aparece, o modelo carrega as instruções completas automaticamente — sem precisar de acionamento manual e sem consumir tokens até que ela seja realmente usada.

O modelo carrega Component Testing automaticamente assim que uma solicitação é relevante para essa habilidade.

Funciona com qualquer modelo de IA

Habilidades de IA são instruções em Markdown simples, não código específico de um provedor. Por isso, Component Testing não fica vinculada ao modelo para o qual foi criada. Instale-a uma vez no TypingMind e use-a com GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama ou um modelo local executado por conta própria — tudo com suas próprias chaves de API.

  • Carregada apenas quando necessário

    O prompt do sistema contém apenas o nome e a descrição. As instruções são buscadas na primeira solicitação relevante, então uma habilidade sem uso não gera custo.

  • Troque de modelo durante a conversa

    Como a habilidade é composta de instruções, não de código, trocar de modelo não afeta seu funcionamento — o próximo modelo lê o mesmo arquivo SKILL.md.

Instruções da habilidade

Este é o conteúdo de SKILL.md que o modelo carrega. Leia antes de instalar — uma habilidade é um conjunto de instruções que seu modelo seguirá.

Component testing

A design system component is a contract, and the tests are the executable half of it. Consumers depend on behaviour they never read the source for, so the test suite's job is to make that behaviour impossible to change by accident.

Test behaviour, not implementation

tsx
// Bad — asserts the implementation; breaks on every refactor, catches nothing
expect(wrapper.find('.btn-primary').prop('isOpen')).toBe(true);
expect(container.querySelector('div > span:nth-child(2)')).toBeTruthy();

// Good — asserts what a user experiences
await user.click(screen.getByRole('button', { name: 'Open menu' }));
expect(screen.getByRole('menu')).toBeVisible();
expect(screen.getByRole('menuitem', { name: 'Settings' })).toHaveFocus();

Query by role and accessible name, in this priority: getByRole → getByLabelText → getByText → getByTestId (last resort). This is not stylistic. getByRole('button', { name: 'Save' }) fails when the accessible name breaks, which means your functional tests double as accessibility tests for free. A test suite full of getByTestId passes happily while the component is unusable with a screen reader.

The contract suite

Every component gets these. Copy ${CLAUDE_PLUGIN_ROOT}/templates/testing/Button.contract.test.tsx and adapt — the shape should be identical across components so a reviewer can see at a glance what is missing.

  1. Renders every variant × size × state. Cheap, and catches the CVA key typo that silently renders unstyled.
  2. Keyboard map. Every documented key, including the ones people forget: Escape closes and returns focus to the trigger, Tab order is correct, arrows move within a composite widget, Home/End jump, typeahead selects.
  3. Focus management. Focus moves into a dialog on open and back to the trigger on close. This is the single most commonly broken behaviour in hand-rolled components and the most disorienting for keyboard users.
  4. Controlled and uncontrolled parity. Both modes work; onValueChange fires in both. Test them as two runs of the same assertions.
  5. Ref forwarding. The ref lands on a real DOM node.
  6. className merged, ...rest spread. The escape hatches, as tests — otherwise they rot.
  7. Disabled semantics. Not activatable by click or keyboard, and communicated to assistive tech (disabled or aria-disabled, deliberately chosen — aria-disabled keeps the element focusable, which is often better because a focusable disabled control can explain why).
  8. axe clean, in every variant and both themes.
tsx
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { axe } from 'vitest-axe';

it.each(['primary', 'secondary', 'ghost', 'danger'] as const)('%s variant has no a11y violations', async (variant) => {
  const { container } = render(<Button variant={variant}>Save</Button>);
  expect(await axe(container)).toHaveNoViolations();
});

it('returns focus to the trigger when the dialog closes', async () => {
  const user = userEvent.setup();
  render(<Example />);
  const trigger = screen.getByRole('button', { name: 'Open' });
  await user.click(trigger);
  await user.keyboard('{Escape}');
  expect(trigger).toHaveFocus();
});

Always userEvent, never fireEvent. fireEvent.click dispatches one synthetic event; userEvent.click does the pointerdown/mousedown/focus/mouseup/click sequence a real user produces. Components that pass with fireEvent and fail in the browser are almost always failing on that difference.

What axe does and does not catch

Automated a11y testing catches roughly 30–40% of WCAG issues. It is a floor, not a ceiling, and treating a green axe run as "accessible" is the most common mistake in this area.

Caught: missing labels, contrast (when computable), invalid ARIA, duplicate ids, missing landmarks, non-focusable interactive elements.

Not caught, and therefore your job:

  • Focus order being logical rather than merely present
  • Whether an accessible name is useful ("Button 3" passes)
  • Whether an error message is announced when it appears
  • Whether a live region interrupts at the right moment
  • Whether the keyboard path to a feature is reasonable rather than technically possible
  • Whether the component works with an actual screen reader

Write explicit tests for focus order, announcements and keyboard paths. And at least once per release, drive the component with VoiceOver or NVDA — nothing substitutes for hearing it.

Storybook

Storybook 10's Vitest addon replaced the old @storybook/test-runner. Stories become test cases via play functions, and the a11y addon runs axe in the same pass — one artifact serving docs, manual review and automation.

tsx
export const OpensOnClick: Story = {
  play: async ({ canvasElement, step }) => {
    const canvas = within(canvasElement);
    await step('opens the menu', async () => {
      await userEvent.click(canvas.getByRole('button', { name: 'Options' }));
      await expect(canvas.getByRole('menu')).toBeVisible();
    });
  },
};

The division of labour that works: stories for states worth looking at (they are the docs, and they feed visual regression), unit tests for logic and edge cases (faster, and better failure messages).

Visual regression

Behaviour tests do not catch a broken border radius or a token that resolved to the wrong colour. VRT does, and for a design system it earns its keep more than in a product app because one component change touches every screen.

  • Playwright screenshots — free, deterministic, you host the baselines.
  • Chromatic — hosted, handles review workflow and cross-browser, costs money.

Snapshot every component in: each variant, both themes, and at 200% zoom. Disable animations and freeze anything time-based, or you will spend your life triaging flakes:

ts
await page.emulateMedia({ reducedMotion: 'reduce' });

Keep a strict diff threshold. A loose one means real regressions slip through, which is worse than not having VRT at all — it manufactures false confidence.

Token and theme tests

Cheap, and they catch the failures that are hardest to spot by eye:

ts
it('every semantic token is defined in every theme', () => {
  const { themes } = tokens;
  const paths = Object.keys(themes.light);
  for (const [name, theme] of Object.entries(themes)) {
    expect(Object.keys(theme).sort()).toEqual(paths.sort());   // a hole in a theme is a silent bug
  }
});

it('components reference no primitive tokens directly', () => {
  // tier violations kill theming — the lint rule catches source, this catches the built output
  const css = readFileSync('dist/styles.css', 'utf8');
  expect(css).not.toMatch(/var\(--ds-color-(neutral|accent|success|warning|danger)-\d+\)/);
});

The contrast gate already runs in the token build. Do not duplicate it here; make sure it runs in CI.

What not to test

  • Third-party primitive internals — Radix tests Radix. Test your wrapper's contract.
  • Exact class names or CSS output. That is VRT's job, and asserting on classes is what makes refactors painful.
  • Snapshot tests of rendered markup. They fail on every change and get rubber-stamped with -u, at which point they are pure cost. Targeted assertions or a real VRT tool.

CI gates

typecheck → unit + a11y → token build (contrast gate) → lint → VRT → build → publint/attw

Fail the build on: a11y violations, contrast failures, type errors, DS lint errors. Warn on: coverage dip, bundle-size growth beyond a threshold.

Coverage floor around 80% for a design system — higher than a typical app, because consumers cannot see inside and a regression ships everywhere at once. Do not chase 100%: the last 15% is usually error branches that would need contrived setups, and the effort is better spent on a real screen-reader pass.

Perguntas frequentes

O que a habilidade de IA Component Testing faz?

Use when writing or reviewing tests for design system components - behavioural tests with Vitest and Testing Library, keyboard and focus tests, axe accessibility assertions, controlled/uncontrolled parity, visual regression, and Storybook play functions. Triggers on "test this component", "a11y test", "visual regression", "storybook test".

Por que usar Component Testing no TypingMind?

Porque basta instalar uma vez para usar com qualquer modelo. A habilidade Component Testing é escrita em Markdown simples, e não em código específico de um provedor, então a mesma habilidade funciona com GPT-5, Claude, Gemini, Grok ou um modelo local — e é possível trocar de modelo no meio do chat sem que ela deixe de funcionar. No TypingMind, você usa suas próprias chaves de API e paga diretamente aos provedores, em vez de pagar uma assinatura por licença de usuário. Suas habilidades e chats permanecem no seu próprio armazenamento.

Como instalar Component Testing no TypingMind?

Abra Plugins → Habilidades → Instalar do GitHub no TypingMind e cole https://github.com/staple-lab/design-system-skills/tree/main/plugins/design-system/skills/component-testing. O TypingMind lê o arquivo SKILL.md e instala a habilidade para que possa ser ativada em cada chat.

Quais modelos de IA podem usar Component Testing?

Qualquer modelo conectado no TypingMind. As habilidades de IA são instruções em Markdown simples, e não código específico de um provedor. Assim, GPT, Claude, Gemini, Grok e modelos locais podem carregar esta habilidade quando uma solicitação corresponder a ela.

Quantos modelos de IA posso usar com Component Testing?

Quantos quiser. Desde que o modelo ofereça suporte a habilidades, é possível usar Component Testing com ele — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama e outros — tudo no TypingMind com suas próprias chaves de API.

A habilidade de IA Component Testing é gratuita?

Sim. A habilidade é publicada no GitHub por staple-lab sob a licença MIT. O pagamento é feito apenas ao seu provedor de IA pelos tokens usados.

O que são habilidades de IA?

Uma habilidade de IA é um conjunto reutilizável de instruções que ensina um modelo de IA a realizar uma tarefa específica. Ela segue o formato aberto Agent Skills: um arquivo SKILL.md com nome e descrição, além de scripts, templates ou arquivos de referência de que o modelo possa precisar. O modelo lê as instruções apenas quando sua solicitação corresponde à habilidade, então uma habilidade instalada não gera custos até ser usada.

Qual é a diferença entre habilidades de IA e plugins ou servidores MCP?

Um plugin ou servidor MCP oferece ao modelo novas ferramentas que ele pode acionar — código que é executado em algum lugar e retorna um resultado. Já uma habilidade de IA dá ao modelo o conhecimento e as orientações de que ele precisa: como abordar uma tarefa, quais etapas seguir e como deve ser um bom resultado. As habilidades são escritas em Markdown simples, por isso não precisam de servidor, chave de API nem ambiente de execução, e funcionam com qualquer modelo.

Ver lista completa

Crie seu próprio espaço de trabalho com IA agora

Inscreva-se na nossa newsletter para receber avisos sobre novos recursos e futuros sorteios 👇