On-device mocking of REST APIs in React Native
13th Mar 2020
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!
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:
The last step for setup is to install
unmock-browser - the library that enables us to use Unmock with React Native:
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
Below is the
App.js file generated by Expo version 3.13.1:
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:
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-browser, the first six lines instruct Unmock to mock our API, and the remaining code is an exact replica of the code above.
Finally, go back to your terminal and run:
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.
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!