0
0
React Nativemobile~3 mins

Why Mocking native modules in React Native? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could test your app's camera without ever touching a real camera?

The Scenario

Imagine you are building a React Native app that uses the device camera or GPS. You want to test your app's features, but the real device hardware is not always available or reliable during testing.

The Problem

Testing with real native modules manually is slow and tricky. You must have the actual device ready, and tests can fail because of hardware issues or environment differences. This makes debugging frustrating and wastes time.

The Solution

Mocking native modules lets you replace real device features with simple fake versions during testing. This way, you can run tests quickly and reliably without needing the actual hardware.

Before vs After
Before
import Camera from 'react-native-camera';
// Tests fail if camera not available
After
jest.mock('react-native-camera', () => ({
  Camera: {
    takePictureAsync: jest.fn(() => Promise.resolve({ uri: 'fake.jpg' }))
  }
}));
What It Enables

Mocking native modules enables fast, reliable testing of app features that depend on device hardware, even when the hardware is not accessible.

Real Life Example

When building a photo app, you can mock the camera module to simulate taking pictures in tests, so you can focus on app logic without needing a real camera every time.

Key Takeaways

Manual testing with real native modules is slow and unreliable.

Mocking replaces real modules with simple fakes for testing.

This makes tests faster, stable, and easier to run anywhere.