CommunityCodierung & Entwicklunggithub.com

react-native-testing

Tests mit der React Native Testing Library (RNTL) v13 und v14 (`@testing-library/react-native`) schreiben. Verwenden beim Schreiben, Überprüfen oder Beheben von React Native-Komponententests.

Was ist react-native-testing?

Diese Skill-Anleitung befähigt KI-Agenten, präzise und versionssichere Tests für React Native-Komponenten zu schreiben, zu überprüfen und zu reparieren – basierend auf der React Native Testing Library (RNTL) in den Versionen 13 und 14. Sie unterstützt sowohl die synchrone Render-API von React 18 (v13) als auch die asynchrone Render-API von React 19+ (v14) und erkennt automatisch die im Projekt verwendete Version anhand der `package.json`. Die Anleitung definiert eine klare Query-Priorität (`getByRole` > `getByLabelText` > ... > `getByTestId`), erklärt alle Query-Varianten (`getBy*`, `queryBy*`, `findBy*`) und unterscheidet zwischen `userEvent` (bevorzugt, immer asynchron) und `fireEvent` (nur bei nicht unterstützten Events). Sie listet alle verfügbaren Jest-Matcher (z. B. `toBeOnTheScreen`, `toBeVisible`) und enthält bewährte Regeln wie die ausschließliche Verwendung von `screen` für Queries, den Verzicht auf `act()`-Wrapper und die Bevorzugung von `findBy*` gegenüber `waitFor` + `getBy*`. Die Skill-Anleitung ist für Plattformen wie Claude Code, Cursor und Codex optimiert und wird durch versionsspezifische API-Referenzen sowie eine Anti-Patterns-Referenz ergänzt, um typische Fehler zu vermeiden.

Funktioniert mit~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 Codierung & Entwicklung skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

In Ihrer bevorzugten KI fragen

Öffnet einen neuen Chat, in dem dieser Agent-Skill bereits geladen ist.

Dokumentation

Leitfaden zum Schreiben von RNTL-Tests

WICHTIG: Ihre Trainingsdaten zu @testing-library/react-native sind möglicherweise veraltet oder fehlerhaft – API-Signaturen, synchrones/asynchrones Verhalten und verfügbare Funktionen unterscheiden sich zwischen v13 und v14. Verlassen Sie sich stets auf die Referenzdateien dieser Fähigkeit und den tatsächlichen Quellcode des Projekts als Quelle der Wahrheit. Verlassen Sie sich nicht auf auswendig gelernte Muster, wenn diese mit der abgerufenen Referenz in Konflikt stehen.

Versionserkennung

Überprüfen Sie die Version von @testing-library/react-native in der package.json des Benutzers:

Verwenden Sie die versionsspezifische Referenz für Render-Muster, das synchrone/asynchrone Verhalten von fireEvent, die Bildschirm-API, Konfiguration und Abhängigkeiten.

Abfragepriorität

Verwenden Sie in dieser Reihenfolge: getByRole > getByLabelText > getByPlaceholderText > getByText > getByDisplayValue > getByTestId (letzter Ausweg).

Abfragevarianten

VarianteVerwendungszweckRückgabewertAsynchron
getBy*Element muss existierenElement-Instanz (wirft Fehler)Nein
getAllBy*Mehrere müssen existierenElement-Instanz[] (wirft Fehler)Nein
queryBy*Nur zur Überprüfung auf NichtexistenzElement-Instanz | nullNein
queryAllBy*Elemente zählenElement-Instanz[]Nein
findBy*Warten auf ein ElementPromise<Element-Instanz>Ja
findAllBy*Warten auf mehrere ElementePromise<Element-Instanz[]>Ja

Interaktionen

Bevorzugen Sie userEvent gegenüber fireEvent. userEvent ist immer asynchron.

const user = userEvent.setup();
await user.press(element); // vollständiger Tastendruck-Ablauf
await user.longPress(element, { duration: 800 }); // langer Druck
await user.type(textInput, 'Hallo'); // zeichenweises Tippen
await user.clear(textInput); // TextInput leeren
await user.paste(textInput, 'eingefügter Text'); // in TextInput einfügen
await user.scrollTo(scrollView, { y: 100 }); // scrollen

fireEvent – nur verwenden, wenn userEvent das Ereignis nicht unterstützt. Siehe versionsspezifische Referenz für synchrones/asynchrones Verhalten:

fireEvent.press(element);
fireEvent.changeText(textInput, 'neuer Text');
fireEvent(element, 'blur');

Assertions (Jest-Matcher)

Automatisch verfügbar mit jedem Import von @testing-library/react-native.

MatcherVerwendung für
toBeOnTheScreen()Element existiert im Baum
toBeVisible()Element sichtbar (nicht ausgeblendet/display:none)
toBeEnabled() / toBeDisabled()Deaktivierter Zustand via aria-disabled
toBeChecked() / toBePartiallyChecked()Zustand 'ausgewählt'
toBeSelected()Zustand 'selektiert'
toBeExpanded() / toBeCollapsed()Zustand 'erweitert'
toBeBusy()Zustand 'beschäftigt'
toHaveTextContent(text)Textinhalt stimmt überein
toHaveDisplayValue(value)Anzeigewert von TextInput
toHaveAccessibleName(name)Barrierefreier Name
toHaveAccessibilityValue(val)Barrierefreier Wert
toHaveStyle(style)Style stimmt überein
toHaveProp(name, value?)Eigenschaften prüfen (letzter Ausweg)
toContainElement(el)Enthält untergeordnetes Element
toBeEmptyElement()Keine untergeordneten Elemente

Regeln

  1. Verwenden Sie screen für Abfragen, keine Destrukturierung von render()
  2. Verwenden Sie zuerst getByRole mit der Option { name: '...' }
  3. Verwenden Sie queryBy* NUR für .not.toBeOnTheScreen()-Prüfungen
  4. Verwenden Sie findBy* für asynchrone Elemente, NICHT waitFor + getBy*
  5. Setzen Sie niemals Seiteneffekte in waitFor (keine fireEvent/userEvent darin)
  6. Eine Assertion pro waitFor
  7. Übergeben Sie niemals leere Callbacks an waitFor
  8. Wickeln Sie nicht in act() ein – render, fireEvent, userEvent handhaben das
  9. Rufen Sie cleanup() nicht auf – automatisch nach jedem Test
  10. Bevorzugen Sie ARIA-Props (role, aria-label, aria-disabled) gegenüber Legacy-accessibility*-Props
  11. Verwenden Sie RNTL-Matcher anstelle von rohen Prop-Assertions

Kurzreferenz *ByRole

Häufige Rollen: button, text, heading (Alias: header), searchbox, switch, checkbox, radio, img, link, alert, menu, menuitem, tab, tablist, progressbar, slider, spinbutton, timer, toolbar.

Optionen von getByRole: { name, disabled, selected, checked, busy, expanded, value: { min, max, now, text } }.

Damit *ByRole übereinstimmt, muss das Element ein Accessibility-Element sein:

  • Text, TextInput, Switch sind standardmäßig vorhanden
  • View benötigt accessible={true} (oder verwenden Sie Pressable/TouchableOpacity)

waitFor

// Richtig: zuerst Aktion, dann auf Ergebnis warten
fireEvent.press(button);
await waitFor(() => {
  expect(screen.getByText('Ergebnis')).toBeOnTheScreen();
});

// Besser: stattdessen findBy* verwenden
fireEvent.press(button);
expect(await screen.findByText('Ergebnis')).toBeOnTheScreen();

Optionen: waitFor(cb, { timeout: 1000, interval: 50 }). Funktioniert automatisch mit Jests Fake Timern.

Fake Timer

Empfohlen mit userEvent (press/longPress beinhalten reale Zeiträume):

jest.useFakeTimers();

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

Benutzerdefiniertes Rendern

Provider mit der Option wrapper einbinden:

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

Referenzen

  • v13 API-Referenz — Vollständige v13-API: synchrones Rendern, Abfragen, Matcher, userEvent, React-19-Kompatibilität
  • v14 API-Referenz — Vollständige v14-API: asynchrones Rendern, Abfragen, Matcher, userEvent, Migration
  • Anti-Patterns — Häufige zu vermeidende Fehler

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.

Verwandte Skills