Bird
Raised Fist0
React Nativemobile~20 mins

Mocking native modules in React Native - Mini App: Build & Ship

Choose your learning style10 modes available
Build: Native Module Mock Demo
This screen demonstrates how to mock a native module in React Native for testing purposes. It shows a button to fetch device info using a native module and displays the result.
Target UI
-------------------------
| Native Module Mock Demo |
|-----------------------|
| Device Info:          |
| [Not fetched yet]     |
|                       |
| [Fetch Device Info]   |
-------------------------
Create a button labeled 'Fetch Device Info'.
When pressed, call a mocked native module method to get device info.
Display the returned device info text below the label 'Device Info:'.
Use React Native's NativeModules to mock the native module.
Ensure the UI updates with the mocked data after button press.
Starter Code
React Native
import React, { useState } from 'react';
import { View, Text, Button, NativeModules, StyleSheet } from 'react-native';

// TODO: Mock the native module here

export default function NativeModuleMockDemo() {
  const [deviceInfo, setDeviceInfo] = useState('Not fetched yet');

  const fetchDeviceInfo = () => {
    // TODO: Call the mocked native module method and update state
  };

  return (
    <View style={styles.container}>
      <Text style={styles.title}>Native Module Mock Demo</Text>
      <Text style={styles.label}>Device Info:</Text>
      <Text style={styles.info}>{deviceInfo}</Text>
      <Button title="Fetch Device Info" onPress={fetchDeviceInfo} />
    </View>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, justifyContent: 'center', alignItems: 'center', padding: 20 },
  title: { fontSize: 20, fontWeight: 'bold', marginBottom: 20 },
  label: { fontSize: 16, marginTop: 10 },
  info: { fontSize: 16, marginBottom: 20, color: 'blue' }
});
Task 1
Task 2
Solution
React Native
import React, { useState } from 'react';
import { View, Text, Button, NativeModules, StyleSheet } from 'react-native';

// Mocking the native module
NativeModules.DeviceInfoModule = {
  getDeviceInfo: () => Promise.resolve('Mocked Device v1.0')
};

export default function NativeModuleMockDemo() {
  const [deviceInfo, setDeviceInfo] = useState('Not fetched yet');

  const fetchDeviceInfo = async () => {
    try {
      const info = await NativeModules.DeviceInfoModule.getDeviceInfo();
      setDeviceInfo(info);
    } catch (e) {
      setDeviceInfo('Error fetching device info');
    }
  };

  return (
    <View style={styles.container}>
      <Text style={styles.title}>Native Module Mock Demo</Text>
      <Text style={styles.label}>Device Info:</Text>
      <Text style={styles.info}>{deviceInfo}</Text>
      <Button title="Fetch Device Info" onPress={fetchDeviceInfo} />
    </View>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, justifyContent: 'center', alignItems: 'center', padding: 20 },
  title: { fontSize: 20, fontWeight: 'bold', marginBottom: 20 },
  label: { fontSize: 16, marginTop: 10 },
  info: { fontSize: 16, marginBottom: 20, color: 'blue' }
});

We create a mock native module by assigning an object to NativeModules.DeviceInfoModule. This object has a method getDeviceInfo that returns a promise resolving to a mocked string. In the fetchDeviceInfo function, we call this mocked method asynchronously and update the state with the returned string. This updates the UI to show the mocked device info. This approach helps test native module integration without needing the real native code.

Final Result
Completed Screen
-------------------------
| Native Module Mock Demo |
|-----------------------|
| Device Info:          |
| Mocked Device v1.0    |
|                       |
| [Fetch Device Info]   |
-------------------------
User taps 'Fetch Device Info' button.
App calls mocked native module method.
Device info text updates to 'Mocked Device v1.0'.
Stretch Goal
Add an error simulation button that calls a mocked native module method which rejects the promise, and display an error message.
💡 Hint
Create another method in the mocked native module that returns Promise.reject('Failed to fetch'). Call it on button press and catch the error to update the UI.

Practice

(1/5)
1. What is the main purpose of mocking native modules in React Native testing?
easy
A. To replace native code with fake implementations for easier testing
B. To speed up the app in production
C. To add new native features automatically
D. To convert JavaScript code into native code

Solution

  1. Step 1: Understand mocking concept

    Mocking replaces real native code with fake versions to isolate tests from native dependencies.
  2. Step 2: Identify purpose in testing

    This helps test JavaScript logic without needing actual native modules running.
  3. Final Answer:

    To replace native code with fake implementations for easier testing -> Option A
  4. Quick 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
A. mock('NativeModuleExample', () => ({ method: jest.fn() }));
B. jest.mock('NativeModuleExample', { method: jest.fn });
C. jest.mock NativeModuleExample { method: jest.fn() };
D. jest.mock('NativeModuleExample', () => ({ method: jest.fn() }));

Solution

  1. Step 1: Recall Jest mock syntax

    Jest uses jest.mock(moduleName, factoryFunction) to mock modules.
  2. Step 2: Check correct usage

    jest.mock('NativeModuleExample', () => ({ method: jest.fn() })); correctly uses jest.mock with a factory returning an object with mocked methods.
  3. Final Answer:

    jest.mock('NativeModuleExample', () => ({ method: jest.fn() })); -> Option D
  4. Quick 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
A. Promise { 'mocked' }
B. undefined
C. mocked
D. Error: getValue is not a function

Solution

  1. Step 1: Understand the mock function

    The mocked getValue returns a resolved Promise with string 'mocked'.
  2. Step 2: Analyze the then callback

    The then callback logs the resolved value, which is 'mocked'.
  3. Final Answer:

    mocked -> Option C
  4. Quick 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
A. jest.mock cannot mock functions
B. jest.fn is missing parentheses, so getData is not a mock function instance
C. NativeModule is not imported correctly
D. getData should return a Promise, not jest.fn

Solution

  1. Step 1: Check jest.fn usage

    jest.fn is a function that must be called as jest.fn() to create a mock function.
  2. 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.
  3. Final Answer:

    jest.fn is missing parentheses, so getData is not a mock function instance -> Option B
  4. Quick 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
A. jest.mock('NativeModule', () => ({ fetchData: () => Promise.resolve({ id: 1, name: 'Test' }) }));
B. jest.mock('NativeModule', () => ({ fetchData: () => ({ id: 1, name: 'Test' }) }));
C. jest.mock('NativeModule', () => ({ fetchData: jest.fn(() => 'Test') }));
D. jest.mock('NativeModule', () => ({ fetchData: jest.fn(() => Promise.reject('Error')) }));

Solution

  1. Step 1: Understand original method behavior

    fetchData returns a Promise resolving to an object, so mock must do the same.
  2. Step 2: Evaluate options

    jest.mock('NativeModule', () => ({ fetchData: () => Promise.resolve({ id: 1, name: 'Test' }) })); returns Promise.resolve with correct object, matching original behavior.
  3. Final Answer:

    jest.mock('NativeModule', () => ({ fetchData: () => Promise.resolve({ id: 1, name: 'Test' }) })); -> Option A
  4. Quick 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 strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard