Skip to content

Instantly share code, notes, and snippets.

@randym
Created July 22, 2025 23:54
Show Gist options
  • Save randym/178df9b88ec0269f7ce90f18aef42c13 to your computer and use it in GitHub Desktop.
Save randym/178df9b88ec0269f7ce90f18aef42c13 to your computer and use it in GitHub Desktop.
testing-library/react-native.md

React Native Testing Library 完全ガイド

コアレンダリングメソッド

render(component)

Reactコンポーネントをレンダリングし、テストユーティリティを返す

import { render } from '@testing-library/react-native'

const { getByText, getByTestId } = render(<MyComponent />)

renderHook(hook)

カスタムフックをレンダリングし、その結果とユーティリティを返す

import { renderHook } from '@testing-library/react-native'

const { result } = renderHook(() => useMyHook())
expect(result.current.value).toBe('expected')

クエリメソッド(要素の検索)

getByText(text)

テキストコンテンツで要素を検索

const element = getByText('Submit')
expect(element).toBeTruthy()

getByTestId(testId)

testIDプロパティで要素を検索

const button = getByTestId('submit-button')
fireEvent.press(button)

getByLabelText(label)

アクセシビリティラベルで要素を検索

const input = getByLabelText('Email address')
fireEvent.changeText(input, '[email protected]')

getByPlaceholderText(placeholder)

プレースホルダーテキストで入力要素を検索

const input = getByPlaceholderText('Enter your email')
fireEvent.changeText(input, '[email protected]')

getByRole(role)

アクセシビリティロールで要素を検索

const button = getByRole('button')
const link = getByRole('link')

getByDisplayValue(value)

値で入力要素を検索

const input = getByDisplayValue('current value')
expect(input).toBeTruthy()

全要素クエリメソッド(複数要素)

getAllByText(text)

テキストを持つ全要素を検索

const buttons = getAllByText('Save')
expect(buttons).toHaveLength(2)

getAllByTestId(testId)

testIDを持つ全要素を検索

const items = getAllByTestId('list-item')
expect(items).toHaveLength(5)

getAllByLabelText(label)

アクセシビリティラベルを持つ全要素を検索

const inputs = getAllByLabelText('Name')
expect(inputs).toHaveLength(3)

非同期クエリメソッド

findByText(text)

getByTextの非同期版

const element = await findByText('Loading complete')
expect(element).toBeTruthy()

findByTestId(testId)

getByTestIdの非同期版

const element = await findByTestId('async-content')
expect(element).toBeTruthy()

findAllByText(text)

getAllByTextの非同期版

const elements = await findAllByText('Item')
expect(elements).toHaveLength(3)

ユーザーインタラクションメソッド

fireEvent.press(element)

要素のタップ/プレスをシミュレート

const button = getByTestId('submit-button')
fireEvent.press(button)
expect(onSubmit).toHaveBeenCalled()

fireEvent.changeText(element, text)

テキスト入力の値を変更

const input = getByTestId('email-input')
fireEvent.changeText(input, '[email protected]')
expect(input.props.value).toBe('[email protected]')

fireEvent.scroll(element, eventData)

スクロールイベントをシミュレート

const scrollView = getByTestId('scroll-view')
fireEvent.scroll(scrollView, {
  nativeEvent: { contentOffset: { y: 100 } }
})

fireEvent.focus(element)

要素にフォーカス

const input = getByTestId('search-input')
fireEvent.focus(input)
expect(input.props.style).toContain('focused')

fireEvent.blur(element)

要素からフォーカスを外す

const input = getByTestId('search-input')
fireEvent.blur(input)
expect(onBlur).toHaveBeenCalled()

ユーティリティメソッド

waitFor(callback)

非同期操作の完了を待機

await waitFor(() => {
  expect(getByText('Data loaded')).toBeTruthy()
})

waitForElementToBeRemoved(element)

要素が消えるまで待機

const loading = getByText('Loading...')
await waitForElementToBeRemoved(loading)

act(callback)

テスト用に状態更新をactでラップ

act(() => {
  setState(newValue)
})

cleanup()

各テスト後にクリーンアップ(新しいバージョンでは自動実行)

afterEach(() => {
  cleanup()
})

デバッグメソッド

debug()

コンポーネントツリーをコンソールに出力

const { debug } = render(<MyComponent />)
debug() // コンポーネントツリーを表示

toJSON()

コンポーネントツリーのJSON表現を取得

const { toJSON } = render(<MyComponent />)
const tree = toJSON()
expect(tree).toMatchSnapshot()

unmount()

レンダリングされたコンポーネントをアンマウント

const { unmount } = render(<MyComponent />)
unmount()

実践的なテスト例

フォームテスト

test('form submission works correctly', async () => {
  const onSubmit = jest.fn()
  const { getByTestId, getByText } = render(
    <LoginForm onSubmit={onSubmit} />
  )

  const emailInput = getByTestId('email-input')
  const passwordInput = getByTestId('password-input')
  const submitButton = getByTestId('submit-button')

  fireEvent.changeText(emailInput, '[email protected]')
  fireEvent.changeText(passwordInput, 'password123')
  fireEvent.press(submitButton)

  await waitFor(() => {
    expect(onSubmit).toHaveBeenCalledWith({
      email: '[email protected]',
      password: 'password123'
    })
  })
})

非同期コンポーネントテスト

test('loads and displays data', async () => {
  const { getByText, findByText } = render(<DataList />)

  // 初期状態
  expect(getByText('Loading...')).toBeTruthy()

  // データ読み込み完了を待機
  const dataElement = await findByText('Data loaded')
  expect(dataElement).toBeTruthy()
})

リストアイテムテスト

test('renders all list items', () => {
  const items = ['Item 1', 'Item 2', 'Item 3']
  const { getAllByTestId } = render(<ItemList items={items} />)

  const listItems = getAllByTestId('list-item')
  expect(listItems).toHaveLength(3)
})

このガイドは React Native Testing Library の主要なメソッドをカバーしています。実際のテストでは、これらのメソッドを組み合わせて効果的なテストを作成してください。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment