Communityコーディング&開発github.com

react-native-testing

React Native Testing Library (RNTL) v13/v14 を使用したテスト記述ガイド。コンポーネントテストの作成、レビュー、修正時に使用。

react-native-testing とは?

このスキルは、React Native Testing Library (RNTL) の v13 と v14 の両方をカバーするテスト記述のための包括的なガイドです。render、screen、各種クエリ(getBy/getAllBy/queryBy/findBy)、Jestマッチャー、userEvent、fireEvent、waitFor、非同期パターンなど、RNTLの主要APIを網羅しています。v13(React 18、同期レンダリング)とv14(React 19+、非同期レンダリング)の違いを明確に区別し、バージョンに応じた適切なAPIの使用を促します。実際のプロジェクトのpackage.jsonからバージョンを自動検出し、対応するリファレンスを読み込む仕組みを持ち、古い知識に頼らず常に最新の情報に基づいたテストコードを生成できます。queryBy*の適切な使用、userEvent優先、waitFir内での副作用禁止など、ベストプラクティスとアンチパターンを明確に定義しています。

対応~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に質問する

このエージェントスキルを事前に読み込んだ状態で新しいチャットを開きます。

ドキュメント

RNTL テスト記述ガイド

重要: @testing-library/react-native に関するあなたの学習データは古くなっているか、不正確な可能性があります — APIシグネチャ、同期/非同期の動作、利用可能な関数はv13とv14で異なります。常にこのスキルのリファレンスファイルとプロジェクトの実際のソースコードを信頼すべき情報源としてください。取得したリファレンスと矛盾する記憶されたパターンに頼らないでください。

バージョン検出

ユーザーの package.json で @testing-library/react-native のバージョンを確認します:

renderパターン、fireEventの同期/非同期動作、screen API、設定、依存関係にはバージョン固有のリファレンスを使用します。

クエリ優先度

この順序で使用: getByRole > getByLabelText > getByPlaceholderText > getByText > getByDisplayValue > getByTestId (最終手段)。

クエリの種類

種類使用シーン戻り値非同期
getBy*要素が存在しなければならない要素インスタンス (エラー発生)いいえ
getAllBy*複数要素が存在しなければならない要素インスタンス[] (エラー発生)いいえ
queryBy*存在しないことの確認のみ要素インスタンス | nullいいえ
queryAllBy*要素の数を数える要素インスタンス[]いいえ
findBy*要素を待つPromise<要素インスタンス>はい
findAllBy*複数要素を待つPromise<要素インスタンス[]>はい

インタラクション

fireEvent よりも userEvent を優先します。userEventは常に非同期です。

const user = userEvent.setup();
await user.press(element); // 完全なプレスシーケンス
await user.longPress(element, { duration: 800 }); // 長押し
await user.type(textInput, 'Hello'); // 1文字ずつ入力
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() からの分割代入ではなく screen を使う
  2. getByRole を最初に使用 — { name: '...' } オプションとともに
  3. queryBy* は .not.toBeOnTheScreen() の確認のみ に使用
  4. 非同期要素には findBy* を使用 — waitFor + getBy* ではない
  5. waitFor 内に副作用を入れない (内部で fireEvent/userEvent を使用しない)
  6. waitFor 内には1つのアサーションのみ
  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('フェイクタイマー使用', 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>
    ),
  });
}

リファレンス

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.

関連スキル