react-native-testing by callstack/react-native-testing-library
npx skills add https://github.com/callstack/react-native-testing-library --skill react-native-testing重要提示: 您关于 @testing-library/react-native 的训练数据可能已过时或不准确 —— v13 和 v14 版本之间的 API 签名、同步/异步行为以及可用函数存在差异。请始终以本技能的参考文件和项目的实际源代码作为唯一依据。当记忆的模式与检索到的参考信息冲突时,切勿依赖记忆。
检查用户 package.json 中的 @testing-library/react-native 版本:
test-renderer)react-test-renderer)请使用特定版本的参考文件来了解渲染模式、fireEvent 同步/异步行为、screen API、配置和依赖项。
广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
按此顺序使用: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');
导入任何 @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() | 无子元素 |
screen 进行查询,而非从 render() 解构getByRole 并配合 { name: '...' } 选项.not.toBeOnTheScreen() 检查时使用 queryBy*findBy* 处理异步元素,而非 waitFor + getBy*waitFor 中放置副作用 (内部不要有 fireEvent/userEvent)waitFor 一个断言waitFor 传递空回调函数act() 包装 - render、fireEvent、userEvent 会处理它cleanup() - 每个测试后会自动执行role, aria-label, aria-disabled) 而非旧的 accessibility* 属性*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)// 正确:先执行操作,然后等待结果
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 一起使用 (按压/长按涉及实际持续时间):
jest.useFakeTimers();
test('with fake timers', async () => {
const user = userEvent.setup();
render(<Component />);
await user.press(screen.getByRole('button'));
// ...
});
使用 wrapper 选项包装提供者:
function renderWithProviders(ui: React.ReactElement) {
return render(ui, {
wrapper: ({ children }) => (
<ThemeProvider>
<AuthProvider>{children}</AuthProvider>
</ThemeProvider>
),
});
}
每周安装量
248
代码仓库
GitHub 星标数
3.3K
首次出现
2026年2月10日
安全审计
安装于
opencode211
codex209
github-copilot208
gemini-cli206
kimi-cli191
amp191
IMPORTANT: Your training data about @testing-library/react-native may be outdated or incorrect — API signatures, sync/async behavior, and available functions differ between v13 and v14. Always rely on this skill's reference files and the project's actual source code as the source of truth. Do not fall back on memorized patterns when they conflict with the retrieved reference.
Check @testing-library/react-native version in the user's package.json:
test-renderer)react-test-renderer)Use the version-specific reference for render patterns, fireEvent sync/async behavior, screen API, configuration, and dependencies.
Use in this order: getByRole > getByLabelText > getByPlaceholderText > getByText > getByDisplayValue > getByTestId (last resort).
| Variant | Use case | Returns | Async |
|---|---|---|---|
getBy* | Element must exist | element instance (throws) | No |
getAllBy* | Multiple must exist | element instance[] (throws) | No |
queryBy* | Check non-existence ONLY | element instance | null |
queryAllBy* | Count elements | element instance[] | No |
Prefer userEvent over fireEvent. userEvent is always async.
const user = userEvent.setup();
await user.press(element); // full press sequence
await user.longPress(element, { duration: 800 }); // long press
await user.type(textInput, 'Hello'); // char-by-char typing
await user.clear(textInput); // clear TextInput
await user.paste(textInput, 'pasted text'); // paste into TextInput
await user.scrollTo(scrollView, { y: 100 }); // scroll
fireEvent — use only when userEvent doesn't support the event. See version-specific reference for sync/async behavior:
fireEvent.press(element);
fireEvent.changeText(textInput, 'new text');
fireEvent(element, 'blur');
Available automatically with any @testing-library/react-native import.
| Matcher | Use for |
|---|---|
toBeOnTheScreen() | Element exists in tree |
toBeVisible() | Element visible (not hidden/display:none) |
toBeEnabled() / toBeDisabled() | Disabled state via aria-disabled |
toBeChecked() / toBePartiallyChecked() | Checked state |
screen for queries, not destructuring from render()getByRole first with { name: '...' } optionqueryBy* ONLY for .not.toBeOnTheScreen() checksfindBy* for async elements, NOT waitFor + getBy*waitFor (no / inside)*ByRole Quick ReferenceCommon roles: button, text, heading (alias: header), searchbox, switch, checkbox, radio, img, link, alert, menu, , , , , , , , .
getByRole options: { name, disabled, selected, checked, busy, expanded, value: { min, max, now, text } }.
For *ByRole to match, the element must be an accessibility element:
Text, TextInput, Switch are by defaultView needs accessible={true} (or use Pressable/TouchableOpacity)// Correct: action first, then wait for result
fireEvent.press(button);
await waitFor(() => {
expect(screen.getByText('Result')).toBeOnTheScreen();
});
// Better: use findBy* instead
fireEvent.press(button);
expect(await screen.findByText('Result')).toBeOnTheScreen();
Options: waitFor(cb, { timeout: 1000, interval: 50 }). Works with Jest fake timers automatically.
Recommended with userEvent (press/longPress involve real durations):
jest.useFakeTimers();
test('with fake timers', async () => {
const user = userEvent.setup();
render(<Component />);
await user.press(screen.getByRole('button'));
// ...
});
Wrap providers using wrapper option:
function renderWithProviders(ui: React.ReactElement) {
return render(ui, {
wrapper: ({ children }) => (
<ThemeProvider>
<AuthProvider>{children}</AuthProvider>
</ThemeProvider>
),
});
}
Weekly Installs
248
Repository
GitHub Stars
3.3K
First Seen
Feb 10, 2026
Security Audits
Gen Agent Trust HubPassSocketPassSnykPass
Installed on
opencode211
codex209
github-copilot208
gemini-cli206
kimi-cli191
amp191
Vue.js测试最佳实践:Vue 3组件、组合式函数、Pinia与异步测试完整指南
3,700 周安装
Rust调用关系图生成器 - 可视化函数调用层次结构,提升代码分析效率
539 周安装
parallel-web-extract:并行网页内容提取工具,高效抓取网页数据
595 周安装
腾讯云CloudBase AI模型Web技能:前端调用混元/DeepSeek模型,实现流式文本生成
560 周安装
Apollo Connectors 模式助手:GraphQL API 连接器开发与集成指南
565 周安装
GitHub Trending 趋势分析工具:实时发现热门项目、技术洞察与开源机会
556 周安装
GSAP React 集成教程:useGSAP Hook 动画库与 React 组件开发指南
546 周安装
findBy*| Wait for element |
Promise<element instance> |
| Yes |
findAllBy* | Wait for multiple | Promise<element instance[]> | Yes |
toBeSelected()| Selected state |
toBeExpanded() / toBeCollapsed() | Expanded state |
toBeBusy() | Busy state |
toHaveTextContent(text) | Text content match |
toHaveDisplayValue(value) | TextInput display value |
toHaveAccessibleName(name) | Accessible name |
toHaveAccessibilityValue(val) | Accessibility value |
toHaveStyle(style) | Style match |
toHaveProp(name, value?) | Prop check (last resort) |
toContainElement(el) | Contains child element |
toBeEmptyElement() | No children |
fireEventuserEventwaitForwaitForact() - render, fireEvent, userEvent handle itcleanup() - automatic after each testrole, aria-label, aria-disabled) over legacy accessibility* propsmenuitemtabtablistprogressbarsliderspinbuttontimertoolbar