DEV Community

Mike Solomon for Meeshkan

Posted on • Originally published at meeshkan.com

On-device mocking of REST APIs in React Native

tl;dr You can do on-device mocking of REST APIs in React Native apps using Unmock.

Unmock is a JavaScript toolkit that helps mock REST API calls. We decided to port it to React Native so that developers can test their apps without making network calls. For me, I tend to iterate my React Native apps on-device, often using Expo. In this case, I find that using Unmock to mock network calls is faster than dealing with real APIs. It also allows me to explore corner cases and issues like 404s and latency early on.

In this article, I'll give a brief overview of how to use Unmock in your React Native apps. I hope you find Unmock useful!

Setup

If you don't have an existing React Native app in which you can try out Unmock, you can bootstrap one with Expo. Run the following commands in your terminal to create a fresh Expo app:

npm install -g expo-cli
expo init unmock-example # choose the blank template
cd unmock-example

These commands will install the Expo CLI globally on your machine via npm. Then using the Expo CLI, you initialize a project called unmock-example and move into that folder.

The last step for setup is to install unmock-browser - the library that enables us to use Unmock with React Native:

npm install unmock-browser 

Usage

You can use and import Unmock wherever you make a call to an API. There are also options to turn it on for the entire app or only for select network calls. As we're using the Expo example, we'll import Unmock into our App.js file.

Below is the App.js file generated by Expo version 3.13.1:

import React from 'react';
import { StyleSheet, Text, View } from 'react-native';

export default function App() {
  return (
    <View style={styles.container}>
    <Text>Open up App.js to start working on your app!</Text>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
 },
});

Let's say that, in this app, we'd like to make a call to an API called myservice.io. It may look something like this:

import React from 'react';
import { StyleSheet, Text, View } from 'react-native';

export default class App extends React.Component {
  state = {};
  componentDidMount() {
    fetch('https://myservice.io/api/users/5')
      .then(r => r.json())
      .then(r => this.setState({ name: r.name }));
  }
  render() {
    const name = this.state.name || '';
    return (
      <View style={styles.container}>
        <Text>Hello {name}! Open up App.js to start working on your app!</Text>
      </View>
      );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
 },
});

When you're prototyping an app and want to get data in fast, it's often clunky to use a real API for several reasons:

  • The API doesn't have the data you need to test the app.
  • The API may interact with a production environment that you don't want to touch.
  • The API may be slow.
  • You may not have access to the API yet.

For all these reasons, Unmock is a great way to get started doing API coding in a React Native app.

Let's revisit the previous example using Unmock. After importing unmock from unmock-browser, the first six lines instruct Unmock to mock our API, and the remaining code is an exact replica of the code above.

import React from 'react';
import { StyleSheet, Text, View } from 'react-native'; 
import unmock from 'unmock-browser'; // import unmock

// define our mock of myservice.io
unmock.nock('https://myservice.io')
 .get('/api/users/5')
 .reply(200, { name: 'Elena' });
// turn unmock on
unmock.on();

export default class App extends React.Component {
  state = {};
  componentDidMount() {
    fetch('https://myservice.io/api/users/5')
      .then(r => r.json())
      .then(r => this.setState({ name: r.name }));
  }

  render() {
    const name = this.state.name || '';
    return (
      <View style={styles.container}> 
      <Text>Hello {name}! Open up App.js to start working on your app!</Text>    
      </View> 
    );
  }
 }  

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
 },
});

Finally, go back to your terminal and run:

npm install
expo start

Now, if you follow the given instructions and launch the Expo app, you'll see that your app says, "Hello Elena! Open up App.js to start working on your app!"

Unmock has lots more nifty features. You can read more about them on the unmock-js GitHub repository.

Conclusion

To clone or play with an example of Unmock running in React Native, check out our Expo snack and GitHub example.

We're looking forward to working more with the React Native community. If you have any feedback on Unmock, give us a shout in the comments. Also, if there are any features you think would be helpful, please let us know by opening an issue directly on unmock-js.

Happy mocking in React Native!

Top comments (0)