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.
Mocking native modules in React Native
Introduction
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
getDeviceName method to always return 'Mocked Device'.React Native
jest.mock('react-native-device-info', () => ({ getDeviceName: jest.fn(() => Promise.resolve('Mocked Device')), }));
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);
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.
Practice
1. What is the main purpose of mocking native modules in React Native testing?
easy
Solution
Step 1: Understand mocking concept
Mocking replaces real native code with fake versions to isolate tests from native dependencies.Step 2: Identify purpose in testing
This helps test JavaScript logic without needing actual native modules running.Final Answer:
To replace native code with fake implementations for easier testing -> Option AQuick Check:
Mocking = Replace native code for testing [OK]
Hint: Mocking means faking native code to test JS easily [OK]
Common Mistakes:
- Thinking mocking speeds up production
- Confusing mocking with adding features
- Believing mocking converts JS to native
2. Which syntax correctly mocks a native module named
NativeModuleExample using Jest?easy
Solution
Step 1: Recall Jest mock syntax
Jest uses jest.mock(moduleName, factoryFunction) to mock modules.Step 2: Check correct usage
jest.mock('NativeModuleExample', () => ({ method: jest.fn() })); correctly uses jest.mock with a factory returning an object with mocked methods.Final Answer:
jest.mock('NativeModuleExample', () => ({ method: jest.fn() })); -> Option DQuick Check:
jest.mock with factory function = jest.mock('NativeModuleExample', () => ({ method: jest.fn() })); [OK]
Hint: Use jest.mock('module', () => ({})) syntax [OK]
Common Mistakes:
- Omitting jest. before mock
- Passing object directly instead of factory function
- Using wrong parentheses or braces
3. Given this mock setup:
jest.mock('NativeModule', () => ({ getValue: () => Promise.resolve('mocked') }));
NativeModule.getValue().then(result => console.log(result));
What will be logged to the console?medium
Solution
Step 1: Understand the mock function
The mocked getValue returns a resolved Promise with string 'mocked'.Step 2: Analyze the then callback
The then callback logs the resolved value, which is 'mocked'.Final Answer:
mocked -> Option CQuick Check:
Promise resolves to 'mocked' logged [OK]
Hint: Promises resolve before then logs value [OK]
Common Mistakes:
- Expecting the Promise object to be logged
- Forgetting to return a Promise in mock
- Confusing undefined with resolved value
4. You wrote this mock:
jest.mock('NativeModule', () => ({ getData: jest.fn }));
But NativeModule.getData.mockReturnValue('test') throws an error. What is the problem?medium
Solution
Step 1: Check jest.fn usage
jest.fn is a function that must be called as jest.fn() to create a mock function.Step 2: Identify error cause
Without parentheses, getData is assigned the function jest.fn itself, not a mock function instance, causing error when using mock methods like mockReturnValue.Final Answer:
jest.fn is missing parentheses, so getData is not a mock function instance -> Option BQuick Check:
Use jest.fn() to create mock function [OK]
Hint: Always call jest.fn() with parentheses [OK]
Common Mistakes:
- Assigning jest.fn without ()
- Assuming jest.mock auto-mocks functions
- Ignoring import errors
5. You want to mock a native module method
fetchData that normally returns a Promise resolving to an object. Which mock implementation correctly simulates this behavior?hard
Solution
Step 1: Understand original method behavior
fetchData returns a Promise resolving to an object, so mock must do the same.Step 2: Evaluate options
jest.mock('NativeModule', () => ({ fetchData: () => Promise.resolve({ id: 1, name: 'Test' }) })); returns Promise.resolve with correct object, matching original behavior.Final Answer:
jest.mock('NativeModule', () => ({ fetchData: () => Promise.resolve({ id: 1, name: 'Test' }) })); -> Option AQuick Check:
Mock Promise resolve with object = jest.mock('NativeModule', () => ({ fetchData: () => Promise.resolve({ id: 1, name: 'Test' }) })); [OK]
Hint: Mock async methods with Promise.resolve returning expected data [OK]
Common Mistakes:
- Returning object directly instead of Promise
- Mocking with rejected Promise when success expected
- Returning string instead of object
Recommended
Ready to prove it?
Pass the test and this pattern moves unknown
10 questions ~5 mineasy hard
