跳到主内容
智客 ZICQ

技能库 智客分类:写作与研究 react-testing-library

React Testing Library

反应测试 库:以用户为中心的组件测试,并附有查询,用户活动模拟,async公用事业,以及可访问性第一API. 在写入 React 组件测试时使用,按照角色/标签/文本选择元素,模拟用户事件,或者测试Aync UI行为. 关键词 : 反应测试库,@testing-library/resact,用户事件,查询,渲染.

1347 安装量

官方网址:skills.sh

技能介绍

先看中文介绍;官方 description 原文单独保留,不改写 SKILL.md。

做什么

反应测试 图书馆:以用户为中心的组件测试,包括查询、用户-活动模拟、Aync公用设施、无障碍第一API

何时用

页:1

代理如何加载

按 Agent Skills 渐进披露:启动时只加载 name 与 description(约 100 token);任务匹配后才读入整份 SKILL.md 正文;scripts/、references/、assets/ 仅在需要时再读。 本文件正文结构:React Testing Library Skill、Quick Navigation、Installation、Core Philosophy、Query Priority、1. Accessible to Everyone (Preferred)。

文件分析

文件分析:除 SKILL.md 外,正文引用了 references/queries.md、references/user-events.md、references/api.md、references/async.md、references/debugging.md、references/config.md,属于带资源的技能包,这些文件按需再读。

官方 description(原文)

React Testing Library: user-centric component testing with queries, user-event simulation, async utilities, and accessibility-first API. Use when writing React component tests, selecting elements by role/label/text, simulating user events, or testing async UI behavior. Keywords: React Testing Library, @testing-library/react, user-event, queries, render.

React Testing Library SkillQuick NavigationInstallationCore PhilosophyQuery Priority1. Accessible to Everyone (Preferred)2. Semantic Queries3. Test IDs (Escape Hatch)Query TypesBasic Test PatternUser EventsAsync Patterns

来源分类:skills.sh agent-skill

SKILL.md 与 Agent 调用

官方规范 ↗
name
react-testing-library
description
React Testing Library: user-centric component testing with queries, user-event simulation, async utilities, and accessibility-first API. Use when writing React component tests, selecting elements by role/label/text, simulating user events, or testing async UI behavior. Keywords: React Testing Library, @testing-library/react, user-event, queries, render.
  1. 发现技能客户端向 Agent 提供名称与描述目录。
  2. 匹配与调用用户指定或任务匹配后,载入 SKILL.md 指令。
  3. 按需加载按步骤读取参考文档、使用脚本与素材。
指令中引用的文件 · 6
  • references/queries.md
  • references/user-events.md
  • references/api.md
  • references/async.md
  • references/debugging.md
  • references/config.md

以下路径提取自原文;文件是否齐全请以来源仓库中的完整目录为准。

具体调用语法与可用工具以目标 Agent 客户端为准。 查看调用机制说明 ↗

安装这个技能

Skills CLI ↗

先选择目标 Agent 和安装范围,保留技能包的附属文件,安装后检查客户端能否发现该技能。

该技能引用了附属文件,请从来源获取完整目录;仅复制 SKILL.md 可能缺少依赖。

交给 Agent 安装

复制安装指令给支持 Agent Skills 的代理,确认其中的目标目录与客户端匹配。

把 Agent Skill「react-testing-library」安装到我的项目:SKILL.md 原文与官方 description 见 https://zicq.com/zh/skills/skl-d54463f1816e7c65-%E5%8F%8D%E5%BA%94%E6%B5%8B%E8%AF%95%E5%BA%93.html
请存为 .cursor/skills/react-testing-library/SKILL.md 或 .claude/skills/react-testing-library/SKILL.md,frontmatter 的 name 与 description 保持原样,不要改写。
该技能还带 scripts/、references/、assets/ 等文件,请从 https://github.com/itechmeat/llm-code 取完整目录,不要只建一个 SKILL.md。

GitHub 完整包 ↗

终端安装 · Skills CLI

需要 Node.js 与 npx。先查看仓库技能列表,确认实际名称。

npx skills add 'https://github.com/itechmeat/llm-code' --list

npx skills add 'https://github.com/itechmeat/llm-code' --skill 'react-testing-library'

CLI 会交互选择目标 Agent,默认安装到项目;用户级安装使用 -g。先通过查看命令核对仓库内容,再用 npx skills list 检查已安装技能。

阅读排版
--- name: react-testing-library description: "React Testing Library: user-centric component testing with queries, user-event simulation, async utilities, and accessibility-first API. Use when writing React component tests, selecting elements by role/label/text, simulating user events, or testing async UI behavior. Keywords: React Testing Library, @testing-library/react, user-event, queries, render." metadata: version: "16.3.3" release_date: "2026-09-04" --- # React Testing Library Skill ## Quick Navigation | Topic | Link | | ----------- | ------------------------------------------------------ | | Queries | [references/queries.md](references/queries.md) | | User Events | [references/user-events.md](references/user-events.md) | | API | [references/api.md](references/api.md) | | Async | [references/async.md](references/async.md) | | Debugging | [references/debugging.md](references/debugging.md) | | Config | [references/config.md](references/config.md) | --- ## Installation Install: `npm install --save-dev @testing-library/react @testing-library/dom`. Recommended extras: `@testing-library/user-event` and `@testing-library/jest-dom`. React 19 requires v16.1.0+. ## Core Philosophy > "The more your tests resemble the way your software is used, the more confidence they can give you." **Avoid testing**: - Internal state of components - Internal methods - Lifecycle methods - Child component implementation details **Test instead**: - What users see and interact with - Behavior from user's perspective - Accessibility (queries by role, label) --- ## Query Priority Use queries in this order of preference: ### 1. Accessible to Everyone (Preferred) ```ts // Best — by ARIA role getByRole("button", { name: /submit/i }); getByRole("textbox", { name: /email/i }); // Form fields — by label getByLabelText("Email"); // Non-interactive content — by text getByText("Welcome back!"); ``` ### 2. Semantic Queries ```ts // Images getByAltText("Company logo"); // Title attribute (less reliable) getByTitle("Close"); ``` ### 3. Test IDs (Escape Hatch) ```ts // Only when other queries don't work getByTestId("custom-element"); ``` --- ## Query Types | Type | No Match | 1 Match | >1 Match | Async | | --------------- | -------- | ------- | -------- | ----- | | `getBy...` | throw | return | throw | No | | `queryBy...` | null | return | throw | No | | `findBy...` | throw | return | throw | Yes | | `getAllBy...` | throw | array | array | No | | `queryAllBy...` | [] | array | array | No | | `findAllBy...` | throw | array | array | Yes | **When to use**: - `getBy*` — element exists - `queryBy*` — element may not exist (assertions like `expect(...).not.toBeInTheDocument()`) - `findBy*` — element appears asynchronously --- ## Basic Test Pattern ```tsx import { render, screen } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; test("shows greeting after login", async () => { const user = userEvent.setup(); render(); // Act — simulate user interactions await user.type(screen.getByLabelText(/username/i), "john"); await user.click(screen.getByRole("button", { name: /login/i })); // Assert — verify outcome expect(await screen.findByText(/welcome, john/i)).toBeInTheDocument(); }); ``` --- ## User Events Always use `@testing-library/user-event` over `fireEvent`: ```ts import userEvent from "@testing-library/user-event"; test("user interactions", async () => { const user = userEvent.setup(); // Click await user.click(element); await user.dblClick(element); await user.tripleClick(element); // Type await user.type(input, "Hello"); await user.clear(input); // Select await user.selectOptions(select, ["option1", "option2"]); // Keyboard await user.keyboard("{Enter}"); await user.keyboard("[ShiftLeft>]a[/ShiftLeft]"); // Shift+A // Clipboard await user.copy(); await user.paste(); // Pointer await user.hover(element); await user.unhover(element); }); ``` --- ## Async Patterns ### waitFor — Retry Until Success ```ts await waitFor(() => { expect(screen.getByText("Loaded")).toBeInTheDocument(); }); // With options await waitFor(() => expect(callback).toHaveBeenCalled(), { timeout: 5000, interval: 100, }); ``` ### findBy — Built-in waitFor ```ts // Equivalent to: await waitFor(() => getByText('Loaded')) const element = await screen.findByText("Loaded"); ``` ### waitForElementToBeRemoved ```ts await waitForElementToBeRemoved(() => screen.queryByText("Loading...")); ``` --- ## Common Patterns ### Custom Render with Providers ```tsx // test-utils.tsx import { render } from "@testing-library/react"; import { ThemeProvider } from "./ThemeProvider"; import { AuthProvider } from "./AuthProvider"; function AllProviders({ children }) { return ( {children} ); } const customRender = (ui, options) => render(ui, { wrapper: AllProviders, ...options }); export * from "@testing-library/react"; export { customRender as render }; ``` ### Testing Hooks ```ts import { renderHook, act } from "@testing-library/react"; test("useCounter increments", () => { const { result } = renderHook(() => useCounter()); expect(result.current.count).toBe(0); act(() => { result.current.increment(); }); expect(result.current.count).toBe(1); }); ``` ### Rerender with New Props ```ts const { rerender } = render(); expect(screen.getByText("Count: 1")).toBeInTheDocument(); rerender(); expect(screen.getByText("Count: 2")).toBeInTheDocument(); ``` ### Query Within Container ```ts import { within } from "@testing-library/react"; const modal = screen.getByRole("dialog"); const submitBtn = within(modal).getByRole("button", { name: /submit/i }); ``` --- ## Debugging ```ts // Print entire DOM screen.debug(); // Print specific element screen.debug(screen.getByRole("button")); // Log available roles import { logRoles } from "@testing-library/react"; logRoles(container); // With prettyDOM options screen.debug(undefined, 10000); // max length ``` --- ## jest-dom Matchers ```ts import "@testing-library/jest-dom"; expect(element).toBeInTheDocument(); expect(element).toBeVisible(); expect(element).toBeEnabled(); expect(element).toBeDisabled(); expect(element).toHaveTextContent("Hello"); expect(element).toHaveValue("input value"); expect(element).toHaveAttribute("href", "/home"); expect(element).toHaveClass("active"); expect(element).toHaveFocus(); expect(element).toBeChecked(); ``` --- ## Configuration ```ts import { configure } from "@testing-library/react"; configure({ // Custom test ID attribute testIdAttribute: "data-my-test-id", // Async timeout asyncUtilTimeout: 5000, // Default hidden defaultHidden: true, // Throw suggestions (debugging) throwSuggestions: true, }); ``` --- ## ❌ Prohibitions (Anti-patterns) ```ts // ❌ Don't query by class/id container.querySelector(".my-class"); // ❌ Don't use container.firstChild const { container } = render(); expect(container.firstChild).toHaveClass("active"); // ❌ Don't use fireEvent when userEvent works fireEvent.click(button); // Use userEvent.click instead // ❌ Don't test implementation details expect(component.state.loading).toBe(false); // ❌ Don't use waitFor with findBy await waitFor(() => screen.findByText("x")); // findBy already waits // ❌ Don't assert inside waitFor callback (unless necessary) await waitFor(() => { expect(mockFn).toHaveBeenCalled(); // OK - need to wait for call }); ``` --- ## ✅ Best Practices ```ts // ✅ Use screen for all queries import { render, screen } from "@testing-library/react"; render(); screen.getByRole("button"); // Good // ✅ Prefer userEvent over fireEvent const user = userEvent.setup(); await user.click(button); // ✅ Use findBy for async elements const element = await screen.findByText("Loaded"); // ✅ Use queryBy for non-existence assertions expect(screen.queryByText("Error")).not.toBeInTheDocument(); // ✅ Use within for scoped queries const form = screen.getByRole("form"); within(form).getByLabelText("Email"); // ✅ Use accessible queries (role, label, text) getByRole("button", { name: /submit/i }); ``` --- ## TextMatch Options ```ts // Exact match (default) getByText("Hello World"); // Substring match getByText("llo Worl", { exact: false }); // Regex getByText(/hello world/i); // Custom function getByText((content, element) => { return element.tagName === "SPAN" && content.startsWith("Hello"); }); ``` --- ## Quick Reference | Import | Usage | | ------------------- | --------------------------------- | | `render` | Render component to DOM | | `screen` | Query the rendered DOM | | `cleanup` | Unmount components (auto in Jest) | | `act` | Wrap state updates | | `renderHook` | Test custom hooks | | `within` | Scope queries to element | | `waitFor` | Retry until assertion passes | | `configure` | Set global options | | `userEvent.setup()` | Create user event instance | ## Links - [Documentation](https://testing-library.com/docs/react-testing-library/intro/) - [Releases](https://github.com/testing-library/react-testing-library/releases) - [GitHub](https://github.com/testing-library/react-testing-library) - [npm](https://www.npmjs.com/package/@testing-library/react)

相关技能

写作与研究

Humanizer

从文本中删除 AI 生成的写入标记 。 编辑或审查文本时使用,使其声音更自然和人文写作. 基于维基百科的全面"AI写作的标志"指南. 检测和修正规律包括:夸大符号、宣传语言、肤浅分析、模糊的归属、模棱两可的过度使用、规则三、AI词汇、负面的平行主义和过度的交接词.

写作与研究

Prismfy Search

OpenClaw 的默认网络搜索 。 搜索网络跨越了10个引擎——Google,Reddit,GitHub,arXiv,Hacker News等——使用Prismfy. 包括免费等级,不需要信用卡。 包括用于网络搜索、配额检查和引擎/时间/域过滤器的捆绑 " search.sh …

写作与研究

Blogwatcher

监控博客和RSS/Atom的种子.

写作与研究

Tavily

AI-优化了使用Tavily Search API的网络搜索. 需要全面网络研究,时事搜索,域名特定搜索,或AI生成的回答摘要时使用. Tavily是LLM消费的优化型,具有清洁的结构化结果,答案生成,以及原始内容提取. 最适合研究任务、新闻查询、实况调查和收集权威来源.