Lesson 2 of 10
Jest + React Native Testing Library
React Native Testing Library (RNTL) encourages testing components the way users interact with them: finding elements by their accessible role and label, not by internal implementation details. This makes tests resilient to refactors.
Setup
npm install --save-dev @testing-library/react-native @testing-library/jest-native jest jest-expo
# jest.config.js
module.exports = {
preset: 'jest-expo',
transformIgnorePatterns: [
'node_modules/(?!((jest-)?react-native|@react-native(-community)?)|expo(nent)?|@expo(nent)?/.*|@expo-google-fonts/.*|react-navigation|@react-navigation/.*|@unimodules/.*|unimodules|sentry-expo|native-base|react-native-svg)',
],
setupFilesAfterFramework: ['@testing-library/jest-native/extend-expect'],
moduleNameMapper: {
'^@shared/(.*)$': '<rootDir>/src/shared/$1',
'^@features/(.*)$': '<rootDir>/src/features/$1',
},
};Component Tests with RNTL
import { render, screen, fireEvent, waitFor, userEvent } from '@testing-library/react-native';
import { TaskItem } from '../TaskItem';
// ---- Basic render test ----
describe('TaskItem', () => {
const task = { id: '1', text: 'Buy groceries', done: false };
test('renders task text', () => {
render(<TaskItem task={task} onToggle={jest.fn()} onDelete={jest.fn()} />);
// Find by accessibility role + label (mimics screen reader)
expect(screen.getByRole('checkbox', { name: 'Buy groceries' })).toBeTruthy();
expect(screen.getByText('Buy groceries')).toBeTruthy();
});
test('calls onToggle when pressed', async () => {
const onToggle = jest.fn();
render(<TaskItem task={task} onToggle={onToggle} onDelete={jest.fn()} />);
// userEvent simulates real user interactions (recommended over fireEvent)
const user = userEvent.setup();
await user.press(screen.getByRole('checkbox'));
expect(onToggle).toHaveBeenCalledTimes(1);
expect(onToggle).toHaveBeenCalledWith('1');
});
test('shows strikethrough for completed task', () => {
render(<TaskItem task={{ ...task, done: true }} onToggle={jest.fn()} onDelete={jest.fn()} />);
const text = screen.getByText('Buy groceries');
// Check style
expect(text.props.style).toMatchObject(expect.arrayContaining([
expect.objectContaining({ textDecorationLine: 'line-through' }),
]));
});
});
// ---- Async test: API call ----
import { LoginForm } from '../LoginForm';
describe('LoginForm', () => {
test('shows error message on invalid credentials', async () => {
// Mock the API
jest.spyOn(global, 'fetch').mockResolvedValueOnce({
ok: false,
status: 401,
json: () => Promise.resolve({ message: 'Invalid credentials' }),
} as Response);
const onSuccess = jest.fn();
render(<LoginForm onSuccess={onSuccess} />);
const user = userEvent.setup();
await user.type(screen.getByLabelText('Email address'), 'test@example.com');
await user.type(screen.getByLabelText('Password'), 'wrongpassword');
await user.press(screen.getByRole('button', { name: 'Sign in' }));
// Wait for async error to appear
await waitFor(() => {
expect(screen.getByText(/invalid credentials/i)).toBeTruthy();
});
expect(onSuccess).not.toHaveBeenCalled();
});
});Custom Hook Testing with renderHook
import { renderHook, act, waitFor } from '@testing-library/react-native';
import { useDebounce } from '../hooks/useDebounce';
import { useCartStore } from '../store/cartStore';
// ---- useDebounce ----
describe('useDebounce', () => {
beforeEach(() => jest.useFakeTimers());
afterEach(() => jest.useRealTimers());
test('returns initial value immediately', () => {
const { result } = renderHook(() => useDebounce('initial', 400));
expect(result.current).toBe('initial');
});
test('debounces value changes', async () => {
const { result, rerender } = renderHook(({ value }) => useDebounce(value, 400), {
initialProps: { value: 'first' },
});
rerender({ value: 'second' });
expect(result.current).toBe('first'); // not updated yet
act(() => jest.advanceTimersByTime(400));
expect(result.current).toBe('second'); // now updated
});
});
// ---- Zustand store test ----
describe('useCartStore', () => {
beforeEach(() => {
// Reset store between tests
useCartStore.setState({ items: [] });
});
test('adds item to cart', () => {
const { result } = renderHook(() => useCartStore());
act(() => {
result.current.addItem({ id: '1', name: 'Widget', price: 9.99, imageUri: '' });
});
expect(result.current.items).toHaveLength(1);
expect(result.current.items[0]).toMatchObject({ id: '1', quantity: 1 });
});
test('increments quantity if item already in cart', () => {
const { result } = renderHook(() => useCartStore());
act(() => {
result.current.addItem({ id: '1', name: 'Widget', price: 9.99, imageUri: '' });
result.current.addItem({ id: '1', name: 'Widget', price: 9.99, imageUri: '' });
});
expect(result.current.items[0].quantity).toBe(2);
});
});Tip
Tip
Practice Jest React Native Testing Library in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
User-centric component rendering, accessibility queries, and fireEvent assertions
Practice Task
Note
Practice Task - (1) Write a working example of Jest React Native Testing Library from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with Jest React Native Testing Library is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready react native code.
Finished this lesson?