Mocking requests with React Native
Mimic allows you to see and mock all networks requests coming from your React native application. In this guide we will see how we can easily install Mimic into our application and mock our first request.
You can also check our example repository on GitHub.
react-native init myApp
cd myApp
npm install --save-dev mimic
npm install -g mimic-remote
# In application code
import connect from 'mimic/react-native';
connect();
# In a new terminal tab
mimic-remote
First lets create a new react-native application. If you've never worked with react native before please head to the React Native Website for installation instructions.
Once you've finished installing you can generate a new app by running the following commands in your terminal:
# Generate React Native Application
react-native init myApp
# Enter the application directory
cd myApp
Now that we're in our application we need to install Mimic in our project as well as installing Mimic remote server.
# Install Mimic library locally in our project
npm install --save-dev mimic
# Installing Mimic remote debugger agent globally in our system
npm install -g mimic-remote
To use mimic we need to import it on our main application entry point. In most cases this is index.ios.js or index.android.js.
Once we imported the module we can use the connect function to connect to our local Mimic server.
# Import Mimic into our project
import connect from 'mimic/react-native';
# connect to Mimic Server
connect();
# You can also specify a custom host and port to connect to
connect({ host: 'localhost', port: 5000 });
You can also check our example repository on GitHub.
# Full example
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
Button
} from 'react-native';
import connect from 'mimic/react-native';
connect();
export default class mimicReactNative extends Component {
render() {
return // my view;
}
}
Now your application is ready to go, all you now need is to start up the Mimic server and start mocking!
To start the Mimic server run:
# Running Mimic server
mimic-remote
# You can also run it on a different port (by default 5000)
mimic-remote --port 4000
# Or use shorthand syntax
mimic-remote -p 4000
We're all finished with installation, point your browser to http://localhost:5000 and start mocking.
It is important to note that Mimic will hold off all your application requests until Mimic is open in your browser window.
This is a current limitation of the implementation to allow you to mock any request that goes out at the start of the application.