- Notifications
You must be signed in to change notification settings - Fork0
A local server configurable at runtime to develop, test, and prototype your React Native app.
License
mutualmobile/react-native-barricade
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
A local server configurable at runtime to develop, test, and prototype your React Native app. Using just mock responses, Barricade can build the whole app without getting blocked by the unavailability of APIs.
Barricade
works by replacing the globalXMLHttpRequest
andfetch
object with theMockedXMLHttpRequest
. It blocks all outgoing network calls that are configured with Barricade and returns a registered local response without requiring any changes to the existing network code.
Most other local server implementations only support a single response per request, but Barricade supports multiple responses per request. This allows us to present the user with an interface to modify the selected mock response for a request at runtime.
Duringdevelopment, Barricade is useful for easily exercising all edge cases of a feature while you are building it without needing to frequently adjust the live server state.
Barricade also helps you test edge cases better duringunit and integration testing as it can easily let you toggle each predefined response to a request.
- Mock API responses.
- Change mocked API responses at runtime.
- Disable/Enable mocking API responses at runtime.
- Support both Android and iOS platforms.
- Built-in TypeScript definitions.
$ npm install --save @mutualmobile/react-native-barricade# --- or ---$ yarn add @mutualmobile/react-native-barricade
1. Create and start Barricade
Create an instance of Barricade with the help of thecreateBarricade
function. While calling this function, you can pass an array ofRequestConfig
(optional) to register the request configs. You can also register a request config later by making use of theregisterRequest
method on the barricade instance.
import{createBarricade}from'@mutualmobile/react-native-barricade';constrequestConfig=[];// Optional: Array of RequestConfigs for all the APIs that needs to be mockedconstbarricade=createBarricade(requestConfig);barricade.start();// Start the BarricadeAppRegistry.registerComponent('App',()=>App);
2. Add BarricadeView
AddBarricadeView
to the root component (App.tsx) of your app. This shows the list of mocked APIs and is used to change the selected response at runtime.
import{BarricadeView}from'@mutualmobile/react-native-barricade';constApp=()=>{return(<View> /* Rest of your app */<BarricadeView/></View>);};
BarricadeView:
Property | Description | Type |
---|---|---|
theme | Use this to select the preferred color scheme. It can bedark orlight . This is optional and by default it'slight . | ThemeType /undefined |
3. Create RequestConfigs
Create aRequestConfig
for each API you want to mock. Then, add these to the list of request configs shown in Step 1 or register them individually by calling theregisterRequest
method as shown below.
import{getBarricadeInstance}from'@mutualmobile/react-native-barricade';constapiRequestConfig={};// RequestConfig for a particular API that you wish to mock.getBarricadeInstance()?.registerRequest(apiRequestConfig);
registerRequest
method only after the Barricade instance is created.
In case you want to unregister a config programmatically, you can do this by calling theunregisterRequest
method similar to the registerRequest method.
import{getBarricadeInstance}from'@mutualmobile/react-native-barricade';constapiRequestConfig={};// RequestConfig object that was previously used for registeringgetBarricadeInstance()?.unregisterRequest(apiRequestConfig);
RequestConfig:
Property | Description | Type |
---|---|---|
label | String used by developer to identify the request in BarricadeView. | string |
method | Request method type. It can beDelete ,Get ,Head ,Options ,Patch ,Post orPut . | Method |
pathEvaluation | Data used to identify the current API triggered from the list of RequestConfigs. | PathEvaluation |
responseHandler | List of mocked responses the current API can return with. By default, the first response from the list is selected. | ResponseHandler[] |
delay | The time (in milliseconds) Barricade needs to wait before responding with the mocked response. This is optional and by default it's400 . | number /undefined |
disabled | Boolean used to enable/disable mocking of the current API. This is optional and by default it'sundefined . | boolean /undefined |
PathEvaluation:
Property | Description | Type |
---|---|---|
path | Request URL endpoint. | string |
type | Type of evaluation that needs to be done on path/request to identify the RequestConfig. It can beCallback ,Include orSuffix . | PathEvaluationType |
callback | Function used to identify if this requestConfig needs to be used for resolving the current API with the help of theRequest argument. | function |
PathEvaluationType:
Enum Options | Description | Type |
---|---|---|
Callback | Use this when you cannot identify the RequestConfig with just the help ofpath property. With this type, you need to pass acallback function inpathEvaluation . | number |
Includes | Use this when thepath passed inpathEvaluation can be anywhere within the Request URL. | number |
Suffix | Use this when thepath passed inpathEvaluation must be at the end of the Request URL. | number |
ResponseHandler:
Property | Description | Type |
---|---|---|
label | String used by developer to identify the response in BarricadeView. | string |
handler | Function that returns the mocked response for the current API call. It can also tweak the response with the help of theRequest argument. | function |
isSelected | Used to identify the selected response from theResponseHandler[] . This is optional and by default Barricade selects the first response on the list. | boolean /undefined |
In this example, we will setup Barricade to be able to respond to theflickr search
API with one of two possible responses. It also shows how to mock an API that is requested using libraries likeaxios
that depend onXMLHttpRequest
constSearchApiRequestConfig:RequestConfig={label:'Search',method:Method.Get,pathEvaluation:{path:'/services/rest?method=flickr.photos.search',type:PathEvaluationType.Includes,},responseHandler:[{label:'Success',handler:successResponseHandler,// function that returns success data based on some computation},{label:'Failure',handler:()=>{return{status:HttpStatusCode.BAD_REQUEST,headers:{'Content-Type':'application/json'},response:JSON.stringify(errorData),// JSON formatted error response.};},},],};
Everytime we hit the above API, Barricade executes thesuccessResponseHandler
function and returns the response data. This function will be useful in cases like the one below, where we have to return the paginated response to the same API call.
constsuccessResponseHandler=(request:Request)=>{const{ page}=request.params??{};constresponse=page==='1' ?searchPageOne :searchPageTwo;// JSON responsesreturn{status:HttpStatusCode.OK,headers:{'Content-Type':'application/json'},response:JSON.stringify(response),};};
Using fetch:
If you are usingfetch
to make an API request, then the response needs of type Blob.
constsuccessResponseHandler=(request:Request)=>{const{ page}=request.params??{};constresponse=page==='1' ?searchPageOne :searchPageTwo;// JSON responsesreturn{status:HttpStatusCode.OK,headers:{'Content-Type':'application/json'},response:newBlob([JSON.stringify(response)],{type:'application/json',}),};};
To run the example app,
1. Clone thereact-native-barricade GitHub repository to your computer to get the example application.
2. Install all the dependencies
$ yarn
3. Go to example folder and install all the dependencies
$cd example$ yarn
4. Install the pods
$cd ios&& pod install&&cd ..
5. Generate and Add your Flickr API key
Generate your Flickr API key fromhere.Then add your API key toflickrKey
property inexample/src/config/dev.ts
andexample/src/config/prod.ts
files.
6. Run the app in android or iOS
$ yarn android# --- or ---$ yarn ios
Barricade comes packaged with an in-app interface that allows you to select the network responses at runtime. For this to be visible, you need to add theBarricadeView
mentioned in Step 2 underUsage.
With this in place and the device shaken, you'll be able to see an option forBarricade
in React Native's developer menu. On tapping theBarricade
option, you’ll be redirected to a screen with the list of mocked APIs.
Note: In BarricadeView, apart from changing the selected response for any of the listed APIs, we can also:
- Disable/Enable Barricade. This will stop/start mocking all the registered API calls and lets you check the app with the actual/mocked API responses at runtime.
- Disable/Enable API Mock. This will stop/start mocking the current API calls and lets you check the app with the actual/mocked API response at runtime.
- Reset all the changes done to the list of selected responses.
You can enable Barricade only inDEV mode. Due to this, the release builds that we usually create for testing and for uploading to store will not be able to access Barricade.
If you want to generate a build with Barricade enabled for testing purpose, you will need to create adebug
build. Follow the below steps to generate a debug build.
Android:
For react-native version < 0.71
In yourandroid/app/build.gradle configuration file, look for theproject.ext.react
map and add thebundleInDebug: true
anddevDisabledInDebug: false
entries to the map:
project.ext.react = [ ...bundleInDebug:true,// Will start bundling of .JS bundle and the assets in debug builddevDisabledInDebug:false,// Makes sure that __DEV__ is true ...]
In yourandroid/app/build.gradle configuration file, inside thereact
configuration block add the below options:
react { ...debuggableVariants=[],// Will stop from skipping bundling of JS bundle and the assets in debug build.extraPackagerArgs=["--dev", "true"],// Makes sure that __DEV__ is true. ...}
Now generate build using the below command.
cd android&& ./gradlew assembleDebug
iOS:
First set the build configuration to Debug. To do this, go toProduct → Scheme → Edit Scheme (cmd + <)
, select theArchive
tab from the side, and set the Build Configuration dropdown toDebug
.
Next tap onProduct → Archive
to archive and then distribute the app.
Testing code which uses this library requires some setup since we might need to mockXMLHttpRequest
andfetch
.
To add the mocks, create a file jestSetup.ts (or any other file name) containing the following code:
jest.mock("@mutualmobile/react-native-barricade",()=>{return{fetch:jest.fn(),Headers:jest.fn(),Request:jest.fn(),Response:jest.fn(),XMLHttpRequest:jest.fn()};});
After that, we need to add the setup file in the jest config. You can add it under setupFiles option in your jest config file:
{"setupFiles": ["<rootDir>/jestSetup.ts"]}
Barricade was created byPrajna Boloor atMutual Mobile.
A special shout-out to the React Native team at Mutual Mobile for their feedback.
Distributed under the MIT License. SeeLICENSE.txt for more information.
If this project has helped you out, please support us with a star 🌟.
About
A local server configurable at runtime to develop, test, and prototype your React Native app.
Topics
Resources
License
Code of conduct
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Packages0
Uh oh!
There was an error while loading.Please reload this page.
Contributors2
Uh oh!
There was an error while loading.Please reload this page.