Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

A local server configurable at runtime to develop, test, and prototype your React Native app.

License

NotificationsYou must be signed in to change notification settings

mutualmobile/react-native-barricade

Repository files navigation

Code CoverageLicenseNPM VersionKnown Vulnerabilities

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.

Why Barricade?

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.

Example App

How does Barricade help?

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.

Features

  • 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.

Installation

$ npm install --save @mutualmobile/react-native-barricade# --- or ---$ yarn add @mutualmobile/react-native-barricade

Usage

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.

⚠️ Make sure to do this in index.js so that you can start Barricade before hitting any API.

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.

⚠️ Make sure you add BarricadeView at the end so that it overlays the entire app.

import{BarricadeView}from'@mutualmobile/react-native-barricade';constApp=()=>{return(<View>      /* Rest of your app */<BarricadeView/></View>);};

BarricadeView:

PropertyDescriptionType
themeUse 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);

⚠️ Make sure to call theregisterRequest 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:

PropertyDescriptionType
labelString used by developer to identify the request in BarricadeView.string
methodRequest method type. It can beDelete,Get,Head,Options,Patch,Post orPut.Method
pathEvaluationData used to identify the current API triggered from the list of RequestConfigs.PathEvaluation
responseHandlerList of mocked responses the current API can return with. By default, the first response from the list is selected.ResponseHandler[]
delayThe time (in milliseconds) Barricade needs to wait before responding with the mocked response. This is optional and by default it's400.number /undefined
disabledBoolean used to enable/disable mocking of the current API. This is optional and by default it'sundefined.boolean /undefined

PathEvaluation:

PropertyDescriptionType
pathRequest URL endpoint.string
typeType of evaluation that needs to be done on path/request to identify the RequestConfig. It can beCallback,Include orSuffix.PathEvaluationType
callbackFunction used to identify if this requestConfig needs to be used for resolving the current API with the help of theRequest argument.function

PathEvaluationType:

Enum OptionsDescriptionType
CallbackUse this when you cannot identify the RequestConfig with just the help ofpath property. With this type, you need to pass acallback function inpathEvaluation.number
IncludesUse this when thepath passed inpathEvaluation can be anywhere within the Request URL.number
SuffixUse this when thepath passed inpathEvaluation must be at the end of the Request URL.number

ResponseHandler:

PropertyDescriptionType
labelString used by developer to identify the response in BarricadeView.string
handlerFunction that returns the mocked response for the current API call. It can also tweak the response with the help of theRequest argument.function
isSelectedUsed to identify the selected response from theResponseHandler[]. This is optional and by default Barricade selects the first response on the list.boolean /undefined

Example

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',}),};};

Build and run the example app

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

Selection Interface

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.

Developer MenuList ViewDetail View

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.

⚠️ The Developer Menu is disabled in release (production) builds.

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.

Generate Build with Barricade

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 with jest

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"]}

Credits

Barricade was created byPrajna Boloor atMutual Mobile.

A special shout-out to the React Native team at Mutual Mobile for their feedback.

License

Distributed under the MIT License. SeeLICENSE.txt for more information.

Support Us

If this project has helped you out, please support us with a star 🌟.

Acknowledgements

About

A local server configurable at runtime to develop, test, and prototype your React Native app.

Topics

Resources

License

Code of conduct

Stars

Watchers

Forks

Packages

No packages published

Contributors2

  •  
  •  

[8]ページ先頭

©2009-2025 Movatter.jp