0
0
React Nativemobile~5 mins

React Native Testing Library

Choose your learning style9 modes available
Introduction

Testing your app helps you catch mistakes early. React Native Testing Library makes it easy to check if your app shows what it should.

You want to check if a button appears and works.
You want to make sure text shows up after a user action.
You want to test if a screen changes when you tap something.
You want to avoid bugs before users find them.
Syntax
React Native
import { render, fireEvent } from '@testing-library/react-native';

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

fireEvent.press(getByText('Click me'));

expect(getByTestId('result')).toBeTruthy();

render shows your component in a test environment.

fireEvent simulates user actions like taps.

Examples
This checks if the text 'Hello' is shown.
React Native
import { render } from '@testing-library/react-native';
import React from 'react';
import { Text } from 'react-native';

const { getByText } = render(<Text>Hello</Text>);

getByText('Hello');
This simulates pressing a button labeled 'Press me'.
React Native
import { render, fireEvent } from '@testing-library/react-native';
import React from 'react';
import { Button } from 'react-native';

const { getByText } = render(<Button title="Press me" onPress={() => {}} />);

fireEvent.press(getByText('Press me'));
Sample App

This test shows a counter starting at 0. When the 'Add' button is pressed, the count increases by 1. The test checks if the text updates correctly.

React Native
import React, { useState } from 'react';
import { Text, Button, View } from 'react-native';
import { render, fireEvent } from '@testing-library/react-native';

function Counter() {
  const [count, setCount] = useState(0);
  return (
    <View>
      <Text testID="count">Count: {count}</Text>
      <Button title="Add" onPress={() => setCount(count + 1)} />
    </View>
  );
}

// Test
const { getByText, getByTestId } = render(<Counter />);

fireEvent.press(getByText('Add'));

const countText = getByTestId('count').props.children.join('');
OutputSuccess
Important Notes

Use testID props to find elements easily in tests.

Always test what the user sees or does, not internal details.

Run tests often to catch problems early.

Summary

React Native Testing Library helps test UI like a user would.

Use render to show components and fireEvent to simulate taps.

Check if elements appear or change after actions.