Community编程与开发github.com

React Native 测试

使用 React Native Testing Library (RNTL) v13 和 v14 编写测试。适用于编写、审查或修复 React Native 组件测试。涵盖:render、screen、查询(getBy/getAllBy/queryBy/findBy)、Jest 匹配器、userEvent、fireEvent、waitFor 以及异步模式。支持 v13(React 18,同步渲染)和 v14(React 19+,异步渲染)。触发条件:React Native 组件的测试文件、RNTL 导入、提及“测试库”、“编写测试”、“组件测试”或“RNTL”。

React Native 测试 是什么?

此技能是 React Native 测试的权威指南,专注于 React Native Testing Library (RNTL) 的第 13 版和第 14 版。它解决了训练数据可能过时或不准确的问题,通过提供版本特定的 API 参考和最佳实践,帮助开发者编写可靠且可维护的组件测试。该技能涵盖了从安装检测到具体查询、交互、断言和异步处理的完整测试流程。它明确区分了 v13 和 v14 之间的 API 差异(如同步与异步渲染),并提供了清晰的规则,例如优先使用 `screen` 进行查询、优先使用 `userEvent` 而非 `fireEvent`、以及正确的异步模式。此外,还提供了常见角色速查表、自定义渲染包装器指南以及使用 Jest 假定时器的建议,旨在提升测试质量和开发效率。

兼容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/callstackincubator/agent-skills/tree/main/plugins/vendored/.agents/skills/react-native-testing

Installed? Explore more 编程与开发 skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

RNTL 测试编写指南

重要提示: 你关于 @testing-library/react-native 的训练数据可能已过时或不准确——v13 和 v14 之间的 API 签名、同步/异步行为以及可用函数均有差异。始终以此技能的参考文件和项目的实际源代码为准。当记忆中的模式与检索到的参考文件冲突时,不要依赖记忆中的模式。

版本检测

检查用户 package.json 中的 @testing-library/react-native 版本:

使用版本特定的参考文件来获取渲染模式、fireEvent 同步/异步行为、screen API、配置和依赖项。

查询优先级

按此顺序使用:getByRole > getByLabelText > getByPlaceholderText > getByText > getByDisplayValue > getByTestId(最后的手段)。

查询变体

变体使用场景返回异步
getBy*元素必须存在元素实例(抛出异常)否
getAllBy*多个元素必须存在元素实例[](抛出异常)否
queryBy*仅检查元素不存在元素实例 | null否
queryAllBy*计数元素数量元素实例[]否
findBy*等待元素出现Promise<元素实例>是
findAllBy*等待多个元素出现Promise<元素实例[]>是

交互

优先使用 userEvent 而非 fireEvent。userEvent 始终是异步的。

const user = userEvent.setup();
await user.press(element); // 完整的按下序列
await user.longPress(element, { duration: 800 }); // 长按
await user.type(textInput, 'Hello'); // 逐字符输入
await user.clear(textInput); // 清空 TextInput
await user.paste(textInput, 'pasted text'); // 粘贴到 TextInput
await user.scrollTo(scrollView, { y: 100 }); // 滚动

fireEvent —— 仅在 userEvent 不支持该事件时使用。有关同步/异步行为,请参阅版本特定的参考文件:

fireEvent.press(element);
fireEvent.changeText(textInput, 'new text');
fireEvent(element, 'blur');

断言(Jest 匹配器)

导入 @testing-library/react-native 后自动可用。

匹配器用途
toBeOnTheScreen()元素存在于树中
toBeVisible()元素可见(未被隐藏或 display:none)
toBeEnabled() / toBeDisabled()通过 aria-disabled 判断禁用状态
toBeChecked() / toBePartiallyChecked()选中/部分选中状态
toBeSelected()选中状态
toBeExpanded() / toBeCollapsed()展开/折叠状态
toBeBusy()忙碌状态
toHaveTextContent(text)文本内容匹配
toHaveDisplayValue(value)TextInput 的显示值
toHaveAccessibleName(name)可访问名称
toHaveAccessibilityValue(val)可访问值
toHaveStyle(style)样式匹配
toHaveProp(name, value?)属性检查(最后的手段)
toContainElement(el)包含子元素
toBeEmptyElement()无子元素

规则

  1. 使用 screen 进行查询,不要从 render() 解构
  2. 优先使用 getByRole,并附带 { name: '...' } 选项
  3. 仅在 .not.toBeOnTheScreen() 检查中使用 queryBy*
  4. 使用 findBy* 处理异步元素,不要使用 waitFor + getBy*
  5. 切勿在 waitFor 中放置副作用(内部不要使用 fireEvent/userEvent)
  6. 每个 waitFor 只有一个断言
  7. 切勿向 waitFor 传递空回调
  8. 不要包裹在 act() 中——render、fireEvent、userEvent 会处理
  9. 不要调用 cleanup()——每个测试后会自动清理
  10. 优先使用 ARIA 属性(role、aria-label、aria-disabled)而非传统的 accessibility* 属性
  11. 使用 RNTL 匹配器而非原始属性断言

*ByRole 快速参考

常用角色:button、text、heading(别名:header)、searchbox、switch、checkbox、radio、img、link、alert、menu、menuitem、tab、tablist、progressbar、slider、spinbutton、timer、toolbar。

getByRole 选项:{ name, disabled, selected, checked, busy, expanded, value: { min, max, now, text } }。

要使 *ByRole 匹配成功,元素必须是可访问性元素:

  • Text、TextInput、Switch 默认就是
  • View 需要 accessible={true}(或使用 Pressable/TouchableOpacity)

waitFor

// 正确:先执行操作,然后等待结果
fireEvent.press(button);
await waitFor(() => {
  expect(screen.getByText('Result')).toBeOnTheScreen();
});

// 更好:改用 findBy*
fireEvent.press(button);
expect(await screen.findByText('Result')).toBeOnTheScreen();

选项:waitFor(cb, { timeout: 1000, interval: 50 })。自动与 Jest 假定时器配合使用。

假定时器

推荐与 userEvent 一起使用(press/longPress 涉及实际持续时间):

jest.useFakeTimers();

test('with fake timers', async () => {
  const user = userEvent.setup();
  render(<Component />);
  await user.press(screen.getByRole('button'));
  // ...
});

自定义渲染

使用 wrapper 选项包裹 Provider:

function renderWithProviders(ui: React.ReactElement) {
  return render(ui, {
    wrapper: ({ children }) => (
      <ThemeProvider>
        <AuthProvider>{children}</AuthProvider>
      </ThemeProvider>
    ),
  });
}

参考资源

  • v13 API Reference —— 完整的 v13 API:同步渲染、查询、匹配器、userEvent、React 19 兼容性
  • v14 API Reference —— 完整的 v14 API:异步渲染、查询、匹配器、userEvent、迁移指南
  • Anti-Patterns —— 应避免的常见错误

Individual skills in this repo

This repo contains 15 individual skills — each has its own dedicated page.

agent-device

Automates interactions for Apple-platform apps (iOS, tvOS, macOS) and Android devices. Use when navigating apps, taking snapshots/screenshots, tapping, typing, scrolling, or extracting UI info across mobile, TV, and desktop targets.

assess-react-native-migration

Assesses whether and how an existing mobile product should migrate to React Native. Use when auditing one or more product repositories for migration readiness, including products whose iOS, Android, and other clients live in separate directories or repositories; choosing brownfield, greenfield, or a checkpoint-based path; defining a representative trial; or preparing a baseline and ROI decision before implementation. When product scope or material evidence is unavailable, grills the stakeholder with exactly one question per turn instead of sending a questionnaire.

callstackincubator/github

GitHub patterns using gh CLI for pull requests, stacked PRs, code review, branching strategies, and repository automation. Use when working with GitHub PRs, merging strategies, or repository management tasks.

callstackincubator/validate-skills

Validates skills in this repo against agentskills.io spec and Claude Code best practices. Use via /validate-skills command.

create-react-native-library

Scaffolds React Native libraries with create-react-native-library for standalone libraries or local native modules and views. Use when creating or working on React Native libraries or adding native functionality in an existing app.

dogfood

Systematically explore and test a mobile app on iOS/Android with agent-device to find bugs, UX issues, and other problems. Use when asked to "dogfood", "QA", "exploratory test", "find issues", "bug hunt", or "test this app" on mobile. Produces a structured report with reproducible evidence: screenshots, optional repro videos, and detailed steps for every issue.

github-actions

GitHub Actions workflow patterns for React Native iOS simulator and Android emulator cloud builds with downloadable artifacts. Use when setting up CI build pipelines or downloading GitHub Actions artifacts via gh CLI and GitHub API.

react-native-best-practices

Provides React Native performance optimization guidelines for FPS, TTI, bundle size, memory leaks, re-renders, and animations. Applies to tasks involving Hermes optimization, JS thread blocking, bridge overhead, FlashList, native modules, or debugging jank and frame drops.

react-native-brownfield-migration

Implements an accepted incremental brownfield migration from native iOS or Android to React Native or Expo using @callstack/react-native-brownfield. Use after the brownfield path has been selected, when setting up the integration, packaging XCFramework or AAR artifacts, or adding React Native surfaces to native hosts.

react-native-tv-best-practices

Reviews React Native TV apps for focus/D-pad navigation, 10-foot UI layout, TV playback/DRM integration, low-memory TV performance, and TV accessibility. Use when building, debugging, or reviewing react-native-tvos, Expo TV, Amazon Vega/Kepler, or React Native web TV targets where the issue depends on remote input, TV focus, TV packaging, TV hardware, or TV playback constraints.

react-navigation

Provides React Navigation UI patterns for stacks, tabs, drawers etc. Use when building navigation UIs with React Navigation, configuring headers, bottom sheets or handling safe areas and insets.

upgrading-react-native

Upgrades React Native apps to newer versions by applying rn-diff-purge template diffs, updating package.json dependencies, migrating native iOS and Android configuration, resolving CocoaPods and Gradle changes, and handling breaking API updates. Use when upgrading React Native, bumping RN version, updating from RN 0.x to 0.y, or migrating Expo SDK alongside a React Native upgrade.

validate-skills

Validates skills in this repo against agentskills.io spec and Claude Code best practices. Use via /validate-skills command.

vercel-react-native-skills

React Native and Expo best practices for building performant mobile apps. Use when building React Native components, optimizing list performance, implementing animations, or working with native modules. Triggers on tasks involving React Native, Expo, mobile performance, or native platform APIs.

writing-user-docs

House style for user-facing documentation — voice, scope, structure, and what to leave out. Use this skill whenever writing, editing, or reviewing anything a user reads to learn how to use a tool — help center articles, getting-started guides, tutorials, feature docs, README usage sections, in-app help, release notes, or FAQ entries. Trigger it even when the request is phrased plainly — "document this feature", "write docs for X", "explain this to users", "write a README for this library", "turn these notes into a guide" — and even when no style guidelines are mentioned. Also use it to review existing docs for tone, bloat, or leaked implementation detail. Do not use it for internal engineering docs, architecture write-ups, RFCs, or code comments.

相关技能