Community코딩 & 개발github.com

react-native-testing

React Native Testing Library (RNTL) v13 및 v14를 사용하여 테스트를 작성합니다. React Native 컴포넌트 테스트를 작성, 검토 또는 수정할 때 사용하세요.

react-native-testing란 무엇인가요?

이 스킬은 React Native Testing Library (RNTL)의 v13과 v14를 모두 지원하는 포괄적인 테스트 작성 가이드입니다. 개발자가 render, screen, 다양한 쿼리(getBy/getAllBy/queryBy/findBy), Jest 매처, userEvent, fireEvent, waitFor 및 비동기 패턴을 올바르게 사용할 수 있도록 돕습니다. 특히 버전 간 차이(v13은 동기 렌더, v14는 비동기 렌더)를 명확히 구분하여 최신 API에 맞는 테스트 코드를 작성할 수 있게 합니다. 쿼리 우선순위(getByRole 우선), userEvent 우선 사용, waitFor 사용 규칙 등 모범 사례를 제시하며, ARIA 속성 사용과 같은 현대적인 접근 방식을 강조합니다. Jest 페이크 타이머와의 통합, custom render 패턴 등 실제 프로젝트에서 바로 적용 가능한 실용적인 예제를 제공합니다.

지원 대상~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에 대한 학습 데이터가 오래되었거나 부정확할 수 있습니다. v13과 v14 간 API 시그니처, 동기/비동기 동작, 사용 가능한 함수가 다릅니다. 항상 이 스킬의 참조 파일과 프로젝트의 실제 소스 코드를 진실의 원천으로 삼으세요. 검색된 참조와 충돌할 때 암기된 패턴을 사용하지 마세요.

버전 감지

사용자의 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'); // 문자별 입력
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. queryBy*는 .not.toBeOnTheScreen() 확인에만 사용
  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'));
  // ...
});

Custom Render

wrapper 옵션을 사용하여 Provider를 감쌉니다:

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

참조

  • v13 API 참조 — 전체 v13 API: 동기 render, 쿼리, 매처, userEvent, React 19 호환
  • v14 API 참조 — 전체 v14 API: 비동기 render, 쿼리, 매처, 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.

관련 스킬