Step 2: Update Jest Configuration
Modify package.json
:
Create a setup file jest.setup.js
(for additional configurations if needed):
3. Writing Unit Tests in React Native
Testing a Simple Function
Create a utility function sum.js
:
Create a test file sum.test.js
:
Run the test:
4. Testing a React Native Component
Create a simple componentButton.js
:
Create a test file Button.test.js
:
5. Mocking Dependencies in React Native Tests
Mock external libraries like Axios:
Mock Async Storage:
6. Running and Debugging Tests
Run Jest tests:
Run tests with watch mode for continuous updates:
Run a specific test file:
Debug failing tests:
7. Best Practices for Unit Testing in React Native
✔️ Write small, independent tests
✔️ Use test IDs (testID
prop) for selecting UI elements
✔️ Mock network requests to avoid API calls in tests
✔️ Ensure 100% code coverage for critical logic
Conclusion
Unit testing in React Native improves code quality and prevents regressions. By using Jest and Testing Library, you can write reliable tests for both UI components and business logic.