testes-react-native

Escreva testes usando a React Native Testing Library (RNTL) v13 e v14 (`@testing-library/react-native`). Use ao escrever, revisar ou corrigir testes de componentes React Native.

O que é testes-react-native?

Esta skill fornece um guia completo para escrever testes de componentes React Native usando a `@testing-library/react-native`, abrangendo tanto as versões v13 (React 18, síncrona) quanto v14 (React 19+, assíncrona). Ela é ideal para desenvolvedores que precisam criar ou revisar testes de forma eficiente, garantindo que sigam as melhores práticas, como priorizar consultas por acessibilidade (`getByRole`) e usar interações assíncronas (`userEvent`) sempre que possível. A skill inclui uma tabela de variantes de consulta (getBy, queryBy, findBy), matchers Jest especializados (toBeOnTheScreen, toBeVisible, etc.), e regras para evitar anti-padrões comuns, como chamar `act()` manualmente ou colocar efeitos colaterais dentro de `waitFor`. Ela também oferece referências a documentações específicas de versão, tornando-se a fonte da verdade para evitar dependência de conhecimento desatualizado. Suporta identificação automática da versão da biblioteca no `package.json` do projeto e carrega os arquivos de referência apropriados.

Funciona com~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 Programação e Desenvolvimento skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

Perguntar na sua IA favorita

Abre um novo chat com esta habilidade de agente já pré-carregada.

Documentação

Guia de Escrita de Testes com RNTL

IMPORTANTE: Seus dados de treinamento sobre @testing-library/react-native podem estar desatualizados ou incorretos — assinaturas de API, comportamento síncrono/assíncrono e funções disponíveis diferem entre v13 e v14. Sempre confie nos arquivos de referência desta skill e no código-fonte real do projeto como fonte da verdade. Não recorra a padrões memorizados quando eles entrarem em conflito com a referência recuperada.

Detecção de Versão

Verifique a versão do @testing-library/react-native no package.json do usuário:

Use a referência específica da versão para padrões de renderização, comportamento síncrono/assíncrono do fireEvent, API screen, configuração e dependências.

Prioridade de Consulta

Use nesta ordem: getByRole > getByLabelText > getByPlaceholderText > getByText > getByDisplayValue > getByTestId (último recurso).

Variantes de Consulta

VarianteCaso de usoRetornaAssíncrono
getBy*Elemento deve existirinstância do elemento (lança)Não
getAllBy*Múltiplos devem existirinstância do elemento[] (lança)Não
queryBy*Verifique NÃO existência APENASinstância do elemento | nullNão
queryAllBy*Contar elementosinstância do elemento[]Não
findBy*Aguardar elementoPromise<instância do elemento>Sim
findAllBy*Aguardar múltiplosPromise<instância do elemento[]>Sim

Interações

Prefira userEvent sobre fireEvent. userEvent é sempre assíncrono.

const user = userEvent.setup();
await user.press(element); // sequência completa de pressão
await user.longPress(element, { duration: 800 }); // pressão longa
await user.type(textInput, 'Hello'); // digitação caractere por caractere
await user.clear(textInput); // limpar TextInput
await user.paste(textInput, 'texto colado'); // colar em TextInput
await user.scrollTo(scrollView, { y: 100 }); // rolar

fireEvent — use apenas quando userEvent não suportar o evento. Consulte a referência específica da versão para comportamento síncrono/assíncrono:

fireEvent.press(element);
fireEvent.changeText(textInput, 'novo texto');
fireEvent(element, 'blur');

Asserções (Matchers Jest)

Disponíveis automaticamente com qualquer importação de @testing-library/react-native.

MatcherUse para
toBeOnTheScreen()Elemento existe na árvore
toBeVisible()Elemento visível (não oculto/display:none)
toBeEnabled() / toBeDisabled()Estado desabilitado via aria-disabled
toBeChecked() / toBePartiallyChecked()Estado marcado
toBeSelected()Estado selecionado
toBeExpanded() / toBeCollapsed()Estado expandido
toBeBusy()Estado ocupado
toHaveTextContent(texto)Correspondência de conteúdo de texto
toHaveDisplayValue(valor)Valor de exibição do TextInput
toHaveAccessibleName(nome)Nome acessível
toHaveAccessibilityValue(valor)Valor de acessibilidade
toHaveStyle(estilo)Correspondência de estilo
toHaveProp(nome, valor?)Verificação de prop (último recurso)
toContainElement(el)Contém elemento filho
toBeEmptyElement()Nenhum filho

Regras

  1. Use screen para consultas, não desestruturação de render()
  2. Use getByRole primeiro com a opção { name: '...' }
  3. Use queryBy* APENAS para verificações de .not.toBeOnTheScreen()
  4. Use findBy* para elementos assíncronos, NÃO waitFor + getBy*
  5. Nunca coloque efeitos colaterais em waitFor (sem fireEvent/userEvent dentro)
  6. Uma asserção por waitFor
  7. Nunca passe callbacks vazios para waitFor
  8. Não envolva em act() - render, fireEvent, userEvent lidam com isso
  9. Não chame cleanup() - automático após cada teste
  10. Prefira props ARIA (role, aria-label, aria-disabled) sobre props legadas accessibility*
  11. Use matchers RNTL em vez de asserções de prop brutas

Referência Rápida de *ByRole

Roles comuns: button, text, heading (alias: header), searchbox, switch, checkbox, radio, img, link, alert, menu, menuitem, tab, tablist, progressbar, slider, spinbutton, timer, toolbar.

Opções de getByRole: { name, disabled, selected, checked, busy, expanded, value: { min, max, now, text } }.

Para que *ByRole corresponda, o elemento deve ser um elemento de acessibilidade:

  • Text, TextInput, Switch são por padrão
  • View precisa de accessible={true} (ou use Pressable/TouchableOpacity)

waitFor

// Correto: ação primeiro, depois aguarde o resultado
fireEvent.press(button);
await waitFor(() => {
  expect(screen.getByText('Resultado')).toBeOnTheScreen();
});

// Melhor: use findBy* em vez disso
fireEvent.press(button);
expect(await screen.findByText('Resultado')).toBeOnTheScreen();

Opções: waitFor(cb, { timeout: 1000, interval: 50 }). Funciona automaticamente com timers falsos do Jest.

Timers Falsos

Recomendado com userEvent (press/longPress envolvem durações reais):

jest.useFakeTimers();

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

Renderização Personalizada

Envolva provedores usando a opção wrapper:

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

Referências

  • Referência de API v13 — API completa v13: renderização síncrona, consultas, matchers, userEvent, compatibilidade React 19
  • Referência de API v14 — API completa v14: renderização assíncrona, consultas, matchers, userEvent, migração
  • Anti-Padrões — Erros comuns a evitar

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.

Habilidades Relacionadas