Testing
Ensuring your app works before users see it
Testing
Testing gives you the confidence to refactor code and ship features without breaking existing functionality.
1. Unit Testing
Unit tests verify that individual functions work as expected. We use Jest for this.
Example: Testing a utility function
Typescript
// utils.ts
export const formatCurrency = (amount: number) => {
return `$${amount.toFixed(2)}`;
};Typescript
// utils.test.ts
import { formatCurrency } from './utils';
test('formats currency correctly', () => {
expect(formatCurrency(10)).toBe('$10.00');
expect(formatCurrency(0)).toBe('$0.00');
});2. Component Testing
Component tests verify that your UI renders correctly and handles user interactions. We use React Native Testing Library (RNTL).
Key Philosophy: Test how the user interacts with your app, not the implementation details.
Example: Testing a Button
Tsx
// Button.tsx
export const Button = ({ onPress, title }) => (
<Pressable onPress={onPress} testID="my-button">
<Text>{title}</Text>
</Pressable>
);Tsx
// Button.test.tsx
import { render, fireEvent, screen } from '@testing-library/react-native';
import { Button } from './Button';
test('calls onPress when tapped', () => {
const mockPress = jest.fn();
render(<Button title="Click Me" onPress={mockPress} />);
// Find the button by text
const button = screen.getByText('Click Me');
// Simulate a press
fireEvent.press(button);
// Assert the function was called
expect(mockPress).toHaveBeenCalled();
});3. Mocking
Sometimes you need to fake external dependencies (like APIs or Native Modules).
Mocking a module:
Javascript
// Mock expo-router so we don't need the real navigation logic in tests
jest.mock('expo-router', () => ({
useRouter: () => ({
push: jest.fn(),
}),
}));4. Snapshot Testing
Snapshots capture the rendered output of a component and save it to a file. If the UI changes unexpectedly, the test fails.
Tsx
test('matches snapshot', () => {
const tree = render(<Button title="Snapshot" />).toJSON();
expect(tree).toMatchSnapshot();
});Summary Checklist
- Write a unit test for a helper function.
- Write a component test for a screen.
- Run
npm testto verify everything passes.