react-native-testing
使用React Native Testing Library (RNTL) v13和v14编写测试。
npx skills add callstack/react-native-testing-library --skill react-native-testingBefore / After 效果对比
1 组React Native应用测试缺乏统一标准,导致测试代码质量参差不齐,难以维护。应用稳定性受影响。
运用React Native Testing Library编写测试,确保测试代码规范高效。显著提升了应用质量和开发信心。
description SKILL.md
name: react-native-testing
description: >
Write tests using React Native Testing Library (RNTL) v13 and v14 (@testing-library/react-native).
Use when writing, reviewing, or fixing React Native component tests.
Covers: render, screen, queries (getBy/getAllBy/queryBy/findBy), Jest matchers,
userEvent, fireEvent, waitFor, and async patterns.
Supports v13 (React 18, sync render) and v14 (React 19+, async render).
Triggers on: test files for React Native components, RNTL imports, mentions of
"testing library", "write tests", "component tests", or "RNTL".
RNTL Test Writing Guide
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.
Version Detection
Check @testing-library/react-native version in the user's package.json:
- v14.x → load references/api-reference-v14.md (React 19+, async APIs,
test-renderer) - v13.x → load references/api-reference-v13.md (React 18+, sync APIs,
react-test-renderer)
Use the version-specific reference for render patterns, fireEvent sync/async behavior, screen API, configuration, and dependencies.
Query Priority
Use in this order: getByRole > getByLabelText > getByPlaceholderText > getByText > getByDisplayValue > getByTestId (last resort).
Query Variants
| 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 | No |
queryAllBy* | Count elements | element instance[] | No |
findBy* | Wait for element | Promise<element instance> | Yes |
findAllBy* | Wait for multiple | Promise<element instance[]> | Yes |
Interactions
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');
Assertions (Jest Matchers)
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 |
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 |
Rules
- Use
screenfor queries, not destructuring fromrender() - Use
getByRolefirst with{ name: '...' }option - Use
queryBy*ONLY for.not.toBeOnTheScreen()checks - Use
findBy*for async elements, NOTwaitFor+getBy* - Never put side-effects in
waitFor(nofireEvent/userEventinside) - One assertion per
waitFor - Never pass empty callbacks to
waitFor - Don't wrap in
act()-render,fireEvent,userEventhandle it - Don't call
cleanup()- automatic after each test - Prefer ARIA props (
role,aria-label,aria-disabled) over legacyaccessibility*props - Use RNTL matchers over raw prop assertions
*ByRole Quick Reference
Common roles: button, text, heading (alias: header), searchbox, switch, checkbox, radio, img, link, alert, menu, menuitem, tab, tablist, progressbar, slider, spinbutton, timer, toolbar.
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,Switchare by defaultViewneedsaccessible={true}(or usePressable/TouchableOpacity)
waitFor
// 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.
Fake Timers
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'));
// ...
});
Custom Render
Wrap providers using wrapper option:
function renderWithProviders(ui: React.ReactElement) {
return render(ui, {
wrapper: ({ children }) => (
<ThemeProvider>
<AuthProvider>{children}</AuthProvider>
</ThemeProvider>
),
});
}
References
- v13 API Reference — Complete v13 API: sync render, queries, matchers, userEvent, React 19 compat
- v14 API Reference — Complete v14 API: async render, queries, matchers, userEvent, migration
- Anti-Patterns — Common mistakes to avoid
forum用户评价 (0)
发表评价
暂无评价,来写第一条吧
统计数据
用户评分
为此 Skill 评分