0
0
React Nativemobile~5 mins

Mocking native modules in React Native

Choose your learning style9 modes available
Introduction

Sometimes, native parts of a React Native app are hard to test or develop with. Mocking native modules lets you pretend those parts exist so you can work smoothly.

When you want to test your app without running on a real device.
When a native feature is not ready but you want to build the app UI.
When you want to speed up development by skipping slow native calls.
When you want to write automated tests that don't depend on native code.
Syntax
React Native
jest.mock('NativeModuleName', () => ({
  methodName: jest.fn(() => returnValue),
}));
Use jest.mock to replace native modules with fake versions.
Inside the mock, define methods as functions that return test values.
Examples
This mocks the getDeviceName method to always return 'Mocked Device'.
React Native
jest.mock('react-native-device-info', () => ({
  getDeviceName: jest.fn(() => Promise.resolve('Mocked Device')),
}));
This mocks the play and stop methods of a sound module with empty functions.
React Native
jest.mock('react-native-sound', () => ({
  play: jest.fn(),
  stop: jest.fn(),
}));
Sample App

This example shows how to mock the getSystemName method from a native module to return 'MockOS'. When you run this code, it prints the mocked value instead of calling the real native code.

React Native
jest.mock('react-native-device-info', () => ({
  getSystemName: jest.fn(() => 'MockOS'),
}));

import DeviceInfo from 'react-native-device-info';

// Use the mocked module
const systemName = DeviceInfo.getSystemName();

console.log(systemName);
OutputSuccess
Important Notes

Always mock native modules in your test setup files or at the top of your test files.

Mocked methods can return promises if the real native method is asynchronous.

Use mocks to keep tests fast and reliable without needing a real device.

Summary

Mocking native modules helps you test and develop without real native code.

Use jest.mock to replace native methods with fake ones.

Mocked methods can return simple values or promises depending on the real method.