testing-library

Use Testing Library to test UI components via user interactions, querying by role, text, and labels rather than implementation details; applicable to testing React components, user-centered tests, accessibility assertions, user-event simulation, asynchronous tests, and related query methods.

Last repository push
GitHub Stars
219
Forks
38
Issues / PRs
1

Installation

Review the source and dependencies with a prompt. A package is available to download.

Install with an AI assistant

Copy the prompt so your assistant can review the pinned revision and dependencies first.

View promptHide prompt
Check whether SkillPI Skill Finder is installed for your current agent. If it is missing, install and enable it using the official instructions at https://github.com/Findskills/skillpi. Then use Skill Finder to locate and install "testing-library" from this exact SkillPI detail page: https://skillpi.com/skills/deepskill-0152adc7f7c97b15fc72a7d57a092a33e735d6f65670956f06291dcc13bbda3a. Verify the upstream source and version against https://github.com/TerminalSkills/skills before installing. If they do not match, stop and report the mismatch. Report the installed path and source version.

Source and setup

github.com

Setup guidance pending

See the original source for supported tools, dependencies, and permissions.

Installation test pending

Use Testing Library to test UI components via user interactions, querying by role, text, and labels rather than implementation details; applicable to testing React components, user-centered tests, accessibility assertions, user-event simulation, asynchronous tests, and related query methods.

0 Downloads

Introduction source: third_party · TerminalSkills · 1.0.0 Reference

SkillPi interpretation

Audience
Testing React/Vue/Svelte components Want tests that survive refactoring (no CSS selectors or internal state checks) Need to verify accessibility (ARIA roles, labels) Testing user interactions (clicks, typing, form submission) Integration testing of component behavior (not snapshot testing)
Software, accounts and paid services
```bash npm install -D @testing-library/react @testing-library/jest-dom @testing-library/user-event
Testing
Not tested

Browse files

Browse files at the source ↗

Original SKILL.md

Open original ↗
Frontmatter
name: testing-library
description: >-
  Test UI components the way users interact with them using Testing Library —
  query by role, text, and label instead of implementation details. Use when
  someone asks to "test React components", "Testing Library", "user-centric
  testing", "test accessibility", "test without implementation details", or
  "render and query components in tests". Covers React Testing Library,
  queries, user events, async testing, and accessibility assertions.
license: Apache-2.0
compatibility: "React, Vue, Svelte, Angular, Preact. Vitest/Jest."
metadata:
  author: terminal-skills
  version: "1.0.0"
  category: development
  tags: ["testing", "react", "components", "accessibility", "testing-library"]

Testing Library

Overview

Testing Library tests UI components from the user's perspective — find elements by their accessible role, text content, or label, not by CSS class or test ID. If a user can't find a button, your test shouldn't find it either. This approach catches accessibility issues by default, survives refactors (rename a CSS class and tests still pass), and produces tests that actually prove the UI works.

When to Use

  • Testing React/Vue/Svelte components
  • Want tests that survive refactoring (no CSS selectors or internal state checks)
  • Need to verify accessibility (ARIA roles, labels)
  • Testing user interactions (clicks, typing, form submission)
  • Integration testing of component behavior (not snapshot testing)

Instructions

Setup

npm install -D @testing-library/react @testing-library/jest-dom @testing-library/user-event
# For Vitest:
npm install -D @testing-library/react vitest happy-dom
// vitest.config.ts
import { defineConfig } from "vitest/config";

export default defineConfig({
  test: {
    environment: "happy-dom",
    setupFiles: ["./tests/setup.ts"],
  },
});
// tests/setup.ts — Global test setup
import "@testing-library/jest-dom/vitest";

Query Priority

Testing Library has a priority order for queries — use the highest priority that works:

// Priority 1: Accessible roles (best — tests accessibility too)
screen.getByRole("button", { name: "Submit" });
screen.getByRole("textbox", { name: "Email" });
screen.getByRole("heading", { level: 1 });

// Priority 2: Label text (forms)
screen.getByLabelText("Email address");

// Priority 3: Placeholder text
screen.getByPlaceholderText("Search...");

// Priority 4: Text content
screen.getByText("Welcome back!");

// Priority 5: Display value
screen.getByDisplayValue("user@example.com");

// Priority 6: Alt text (images)
screen.getByAltText("Company logo");

// Last resort: test IDs (avoid if possible)
screen.getByTestId("complex-widget");

Testing Component Behavior

// LoginForm.test.tsx — Test a login form from the user's perspective
import { render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { LoginForm } from "./LoginForm";

describe("LoginForm", () => {
  it("submits the form with email and password", async () => {
    const onSubmit = vi.fn();
    const user = userEvent.setup();

    render(<LoginForm onSubmit={onSubmit} />);

    // Find elements by their accessible role/label
    await user.type(screen.getByLabelText("Email"), "kai@example.com");
    await user.type(screen.getByLabelText("Password"), "secret123");
    await user.click(screen.getByRole("button", { name: "Sign in" }));

    expect(onSubmit).toHaveBeenCalledWith({
      email: "kai@example.com",
      password: "secret123",
    });
  });

  it("shows validation error for invalid email", async () => {
    const user = userEvent.setup();
    render(<LoginForm onSubmit={vi.fn()} />);

    await user.type(screen.getByLabelText("Email"), "not-an-email");
    await user.click(screen.getByRole("button", { name: "Sign in" }));

    expect(screen.getByRole("alert")).toHaveTextContent("Invalid email address");
  });

  it("disables submit while loading", async () => {
    render(<LoginForm onSubmit={() => new Promise(() => {})} />);
    const user = userEvent.setup();

    await user.type(screen.getByLabelText("Email"), "kai@example.com");
    await user.type(screen.getByLabelText("Password"), "secret123");
    await user.click(screen.getByRole("button", { name: "Sign in" }));

    expect(screen.getByRole("button", { name: /signing in/i })).toBeDisabled();
  });
});

Async Testing

// UserProfile.test.tsx — Testing async data fetching
import { render, screen, waitFor } from "@testing-library/react";
import { UserProfile } from "./UserProfile";

it("loads and displays user data", async () => {
  render(<UserProfile userId="123" />);

  // Loading state
  expect(screen.getByText("Loading...")).toBeInTheDocument();

  // Wait for data to load
  await waitFor(() => {
    expect(screen.getByRole("heading")).toHaveTextContent("Kai Chen");
  });

  expect(screen.getByText("kai@example.com")).toBeInTheDocument();
});

it("shows error state on failure", async () => {
  // Mock API failure
  server.use(http.get("/api/users/123", () => HttpResponse.error()));

  render(<UserProfile userId="123" />);

  await waitFor(() => {
    expect(screen.getByRole("alert")).toHaveTextContent("Failed to load");
  });
});

Examples

Example 1: Test a complex form with validation

User prompt: "Write tests for a multi-step registration form with validation."

The agent will write tests that fill each step from the user's perspective, verify validation errors appear on invalid input, and confirm successful submission.

Example 2: Test an accessible data table

User prompt: "Test a sortable data table — verify sorting, filtering, and pagination work."

The agent will query table headers by role, click to sort, verify row order changes, type into filter input, and navigate pages.

Guidelines

  • Query by role first — getByRole tests accessibility for free
  • userEvent over fireEvent — simulates real user behavior (focus, type, blur)
  • userEvent.setup() at test start — creates a user instance for the test
  • waitFor for async — wait for elements to appear after data fetching
  • Avoid getByTestId — if you need it, the component might have accessibility issues
  • screen is global — no need to destructure render result
  • toBeInTheDocument() from jest-dom — readable assertions
  • Don't test implementation — state values, effect triggers, re-render counts
  • Test behavior, not structure — "user sees error" not "error div has class active"

Current listing version

1.0.0

Verify the source revision ↗

Safety and assessment details

Quality assessment

Out of 100 · Assessment report from SkillPi LAB.

Scenario Value85/100

Highlights

  • 提供 Testing Library 的完整实践指南,覆盖 React/Vue/Svelte 等主流框架
  • 强调用户视角和可访问性测试,具有广泛实用价值
Trigger Precision90/100

Highlights

  • 触发词覆盖全面,包括多种常见测试场景表述
  • 边界清晰,不易与其他 Skill 混淆
Structure and Standards95/100

Highlights

  • 结构完整,包含安装、查询优先级、行为测试、异步测试等关键章节
  • 提供端到端示例和最佳实践指南
Execution Reliability90/100

Areas to improve

  • description写错位置 Reported severity: Minor

    顶层 description 字段为空,实际描述内容位于 skill_body 内部的 frontmatter 中

    Recommendation: 建议将 description 内容移至顶层字段,确保触发机制能正确读取

Highlights

  • 工具来源明确,参数正确,覆盖主要异常场景
  • 提供完整的测试设置和断言示例
Evidence Verifiability (mean of the first four)90/100

The arithmetic mean of the first four original scores, rounded to a whole number.

Static text checks

100 / 100 · skillpi-20261123-no-r3-v1

No current rules matched the text.

This score reflects rule matches in the text and is provided for reference before use. It excludes attachments and runtime behavior.

Permissions and checks before use

Automatically summarized from this main document. Matches may be examples or defensive advice; they are not actual permission declarations. Attachments, external dependencies and runtime behavior are not covered.

  • Install or fetch external dependencies

    Use official sources and pin versions. Check install scripts in an isolated environment. This document check does not cover code downloaded later.

    Mentioned in main document · lines 38, 40

These notices grant no permissions. Your host tool must still confirm file changes, secrets, external transfers or costs as needed.

Security rating and access scope

safe · Static evidence review; not a runtime safety guarantee.

```bash npm install -D @testing-library/react @testing-library/jest-dom @testing-library/user-event

Before use, confirm and authorize actual file access, external services and network destinations in your host. This review grants no runtime permissions.