Component testing helps check if parts of your app work right by themselves. It finds mistakes early so your app stays strong.
0
0
Component testing in React Native
Introduction
When you want to check if a button works before adding it to the app.
When you build a new screen and want to make sure it shows the right text.
When you fix a bug and want to confirm the fix works.
When you want to test how a component looks with different data.
When you want to avoid breaking other parts of the app after changes.
Syntax
React Native
import { render } from '@testing-library/react-native'; import MyComponent from './MyComponent'; test('description of what to test', () => { const { getByText } = render(<MyComponent />); expect(getByText('Hello')).toBeTruthy(); });
Use render to create the component in a test environment.
Use queries like getByText to find elements inside the component.
Examples
This test checks if the Button component shows the label passed as a prop.
React Native
import { render } from '@testing-library/react-native'; import Button from './Button'; test('button shows correct label', () => { const { getByText } = render(<Button label="Click me" />); expect(getByText('Click me')).toBeTruthy(); });
This test checks if the Greeting component displays the correct name.
React Native
import { render } from '@testing-library/react-native'; import Greeting from './Greeting'; test('greeting shows user name', () => { const { getByText } = render(<Greeting name="Anna" />); expect(getByText('Hello, Anna!')).toBeTruthy(); });
Sample App
This example shows a simple Welcome component that greets a user by name. The test checks if the greeting text appears correctly when the component is rendered with a user prop.
React Native
import React from 'react'; import { Text, View } from 'react-native'; export default function Welcome(props) { return ( <View> <Text>Welcome, {props.user}!</Text> </View> ); } // Test file import React from 'react'; import { render } from '@testing-library/react-native'; import Welcome from './Welcome'; test('Welcome component shows user name', () => { const { getByText } = render(<Welcome user="Sam" />); expect(getByText('Welcome, Sam!')).toBeTruthy(); });
OutputSuccess
Important Notes
Always test one thing at a time in your component tests.
Use descriptive test names to know what each test checks.
Component tests run fast and help catch UI bugs early.
Summary
Component testing checks small parts of your app alone.
It uses tools like @testing-library/react-native to render and check components.
Good tests help keep your app working well as it grows.