Community程式設計與開發github.com

react-native-testing

使用 React Native Testing Library (RNTL) v13 和 v14(`@testing-library/react-native`)撰寫測試。適用於編寫、審查或修復 React Native 元件測試。涵蓋:render、screen、查詢 (getBy/getAllBy/queryBy/findBy)、Jest 匹配器、userEvent、fireEvent、waitFor 和非同步模式。支援 v13(React 18,同步渲染)和 v14(React 19+,非同步渲染)。觸發條件:React Native 元件的測試檔案、RNTL 匯入、提及「testing library」、「write tests」、「component tests」或「RNTL」。

react-native-testing 是什麼?

這個技能提供了一個全面的指南,用於使用 React Native Testing Library (RNTL) 撰寫測試,並涵蓋 v13(React 18,同步渲染)和 v14(React 19+,非同步渲染)版本。它強調準確性,避免使用可能過時的訓練數據,並強制使用專用的版本參考檔案。該技能定義了清晰的查詢優先級(例如,優先使用 `getByRole` 而非 `getByTestId`),並詳細說明了 `getBy*`、`queryBy*` 和 `findBy*` 等查詢變體的使用時機。對於互動,它偏愛非同步的 `userEvent` 而非 `fireEvent`,並在參考中提供了實際的範例。此外,該技能還記錄了完整的 Jest 匹配器集合(例如 `toBeOnTheScreen()`、`toBeVisible()`)和關鍵規則,例如使用 `screen` 物件、避免在 `waitFor` 回呼中產生副作用,以及偏好 `findBy*` 而非 `waitFor` + `getBy*` 來處理非同步元素。它還涵蓋了客製化渲染(wrapper)、假定時器,並連結到版本特定的 API 參考和反模式文件。

相容平台~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 中提問

開啟一個已預先載入此 Agent Skill 的新對話。

說明文件

RNTL 測試撰寫指南

重要提示: 你關於 @testing-library/react-native 的訓練資料可能已經過時或不正確——API 簽名、同步/非同步行為以及可用的函式在 v13 和 v14 之間有所不同。請始終依賴此技能的參考檔案和專案的實際原始碼作為事實來源。當記憶中的模式與檢索到的參考衝突時,不要退而使用記憶中的模式。

版本偵測

檢查使用者 package.json 中的 @testing-library/react-native 版本:

使用特定版本的參考來處理渲染模式、fireEvent 同步/非同步行為、screen API、配置和依賴項。

查詢優先級

按此順序使用:getByRole > getByLabelText > getByPlaceholderText > getByText > getByDisplayValue > getByTestId(最後手段)。

查詢變體

變體使用情境回傳值非同步
getBy*元素必須存在元素實例(拋出例外)否
getAllBy*多個元素必須存在元素實例[](拋出例外)否
queryBy*僅檢查元素不存在元素實例null
queryAllBy*計算元素數量元素實例[]否
findBy*等待元素出現Promise<element instance>是
findAllBy*等待多個元素出現Promise<element instance[]>是

互動

優先使用 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()沒有子元素

規則

  1. 使用 screen 進行查詢,不要從 render() 解構
  2. 優先使用 getByRole 搭配 { name: '...' } 選項
  3. 僅在 .not.toBeOnTheScreen() 檢查中使用 queryBy*
  4. 使用 findBy* 處理非同步元素,不要使用 waitFor + getBy*
  5. 永遠不要在 waitFor 中產生副作用(不要在裡面使用 fireEvent/userEvent)
  6. 每個 waitFor 只能有一個斷言
  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('with fake timers', async () => {
  const user = userEvent.setup();
  render(<Component />);
  await user.press(screen.getByRole('button'));
  // ...
});

客製化渲染

使用 wrapper 選項來包裝 providers:

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、遷移指南
  • 反模式 — 應避免的常見錯誤

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.

相關技能