๐Ÿงช Unit Testing in React Native

 If you’re a React Native developer and unit testing feels confusing, optional, or “something seniors do later” — you’re not alone.

Most React Native apps work fine without tests
until one day they don’t.

This blog explains unit testing from scratch, so that:

  • Beginners can start without fear

  • Intermediate devs can test correctly

  • Seniors can align on best practices


๐Ÿง  What Is Unit Testing? (Simple Definition)

Unit testing means testing the smallest testable part of your code, in isolation.

A unit can be:

  • A function

  • A component

  • A utility

  • A hook

๐Ÿ‘‰ The key idea:
Test one thing at a time, without dependencies.


๐Ÿค” Why Unit Testing Is Important

Unit tests help you answer questions like:

  • Did my change break existing logic?

  • Can I refactor safely?

  • Will this bug come back again?

  • Can a junior change this code confidently?

Real benefits:

  • Catches bugs early

  • Makes refactoring safer

  • Improves code quality

  • Acts as documentation

  • Saves time in the long run

What unit testing is NOT:

  • It does NOT guarantee bug-free apps

  • It does NOT replace manual testing

  • It does NOT test real APIs or servers


๐Ÿงฉ Common Unit Testing Terms (Explained Simply)

1️⃣ Test

A piece of code that checks if something works as expected.

expect(sum(2, 3)).toBe(5);

2️⃣ Test Suite

A group of related tests.

describe("sum function", () => { // tests live here });

3️⃣ Assertion

A condition you expect to be true.

expect(result).toEqual(10);

4️⃣ Mock

A fake version of something real (API, timer, module).

๐Ÿ‘‰ Used to remove dependencies.


5️⃣ Coverage

A measure of how much of your code is executed by tests.


๐Ÿ› ️ Which Library Should You Use?

For React Native, the standard setup is:

✅ Required Libraries

  1. Jest

  • Test runner

  • Assertion library

  • Comes preconfigured with React Native

  1. @testing-library/react-native

  • Tests components like a user would

  • Encourages good testing practices

๐Ÿ“Œ This combo is officially recommended by the React Native community.


⚙️ How to Set Up Unit Testing

Most RN projects already include Jest.

Install Testing Library:

npm install --save-dev @testing-library/react-native

That’s it. No complex setup required.


๐Ÿงช What Should Be Unit Tested?

✅ Good candidates for unit tests

  • Utility functions

  • Business logic

  • Conditional rendering

  • Button clicks

  • Form validation

  • Hooks

  • Component behavior

❌ Avoid unit testing

  • Navigation library internals

  • Third-party libraries

  • Styles only

  • Platform code (Android/iOS)


๐Ÿ”ข Example 1: Testing a Simple Function

Code

export function add(a, b) { return a + b; }

Test

import { add } from "./math"; test("adds two numbers", () => { expect(add(2, 3)).toBe(5); });

✔ No UI
✔ No React
✔ Pure logic
This is a perfect unit test.


๐Ÿงฑ Example 2: Testing a React Native Component

Component

function Greeting({ name }) { return <Text>Hello {name}</Text>; }

Test

import { render } from "@testing-library/react-native"; import Greeting from "./Greeting"; test("shows greeting message", () => { const { getByText } = render(<Greeting name="Vikrant" />); expect(getByText("Hello Vikrant")).toBeTruthy(); });

๐Ÿ‘‰ We test what the user sees, not internal implementation.


๐Ÿ” Testing Static vs Dynamic Values

Static value test

expect(getByText("Submit")).toBeTruthy();

Dynamic value test

expect(getByText(`Hello ${name}`)).toBeTruthy();

As long as you control the input, the output is testable.


๐ŸŒ Should API Calls Be Unit Tested?

Short answer: ❌ No

Unit tests should not call real APIs.

Why?

  • APIs are slow

  • APIs can fail

  • APIs are not “units”


๐Ÿงช What If Logic Depends on API Response?

๐Ÿ‘‰ You mock the API.

Example Component

useEffect(() => { fetchUser().then(setUser); }, []);

Mocking API

jest.mock("./api", () => ({ fetchUser: jest.fn(() => Promise.resolve({ name: "Vikrant" }) ), }));

Test

expect(await findByText("Vikrant")).toBeTruthy();

✔ API logic tested
✔ No real network call
✔ Fast & reliable


⚠️ Precautions While Writing Unit Tests

1️⃣ Don’t test implementation details

Test behavior, not internal state.

❌ Bad:

expect(component.state.value).toBe(1);

✅ Good:

expect(getByText("1")).toBeTruthy();

2️⃣ Don’t over-mock

Too many mocks = fragile tests.


3️⃣ Don’t chase 100% coverage blindly

Coverage ≠ quality.


๐Ÿ“Š How Much Test Coverage Is Enough?

Realistic targets:

  • 60–70% for most apps

  • Focus on critical logic

  • Focus on bug-prone areas

Better to have:
✔ 10 meaningful tests
than
❌ 50 shallow tests


⚖️ Merits of Unit Testing

✅ Pros

  • Confidence in changes

  • Safer refactoring

  • Faster debugging

  • Better code design

❌ Cons

  • Initial learning curve

  • Time investment

  • Can be misused


๐Ÿง  Beginner → Expert Mindset Shift

Beginner thinks:

“Tests slow me down.”

Expert knows:

“Tests let me move fast without fear.”


๐Ÿ Final Takeaway

Unit testing in React Native is not about tools.
It’s about thinking in small, testable pieces.

If you remember just one thing:

Test behaviour, not implementation.
Mock what you don’t own.
Keep tests simple and meaningful.

Once you get this right, testing stops being scary — and starts being powerful.

Comments

Popular posts from this blog

Monorepo Setup Guide

๐ŸŒ Why console.log Slows Down React Native Apps

๐Ÿง  React Native New Architecture Explained