0
0
React Nativemobile~20 mins

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

Choose your learning style9 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.