RNTL 测试编写指南
重要提示: 你关于 @testing-library/react-native 的训练数据可能已过时或不准确——v13 和 v14 之间的 API 签名、同步/异步行为以及可用函数均有差异。始终以此技能的参考文件和项目的实际源代码为准。当记忆中的模式与检索到的参考文件冲突时,不要依赖记忆中的模式。
版本检测
检查用户 package.json 中的 @testing-library/react-native 版本:
- v14.x → 加载 references/api-reference-v14.md(React 19+,异步 API,
test-renderer) - v13.x → 加载 references/api-reference-v13.md(React 18+,同步 API,
react-test-renderer)
使用版本特定的参考文件来获取渲染模式、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() | 无子元素 |
规则
- 使用
screen进行查询,不要从render()解构 - 优先使用
getByRole,并附带{ name: '...' }选项 - 仅在
.not.toBeOnTheScreen()检查中使用queryBy* - 使用
findBy*处理异步元素,不要使用waitFor+getBy* - 切勿在
waitFor中放置副作用(内部不要使用fireEvent/userEvent) - 每个
waitFor只有一个断言 - 切勿向
waitFor传递空回调 - 不要包裹在
act()中——render、fireEvent、userEvent会处理 - 不要调用
cleanup()——每个测试后会自动清理 - 优先使用 ARIA 属性(
role、aria-label、aria-disabled)而非传统的accessibility*属性 - 使用 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 —— 应避免的常见错误