{"id":20115544,"url":"https://github.com/mutualmobile/react-native-barricade","last_synced_at":"2025-06-13T19:05:29.905Z","repository":{"id":65720485,"uuid":"571912958","full_name":"mutualmobile/react-native-barricade","owner":"mutualmobile","description":"A local server configurable at runtime to develop, test, and prototype your React Native app.","archived":false,"fork":false,"pushed_at":"2024-05-16T20:24:45.000Z","size":39868,"stargazers_count":9,"open_issues_count":4,"forks_count":0,"subscribers_count":3,"default_branch":"main","last_synced_at":"2025-06-13T19:05:15.778Z","etag":null,"topics":["mockapi","react-native","typescipt"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/mutualmobile.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":".github/CODEOWNERS","security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2022-11-29T06:38:51.000Z","updated_at":"2024-09-04T09:39:30.000Z","dependencies_parsed_at":"2024-11-13T18:48:35.436Z","dependency_job_id":null,"html_url":"https://github.com/mutualmobile/react-native-barricade","commit_stats":{"total_commits":41,"total_committers":2,"mean_commits":20.5,"dds":0.07317073170731703,"last_synced_commit":"a9a290ae79511d686d4b3ea99698228bd9f671ae"},"previous_names":[],"tags_count":4,"template":false,"template_full_name":null,"purl":"pkg:github/mutualmobile/react-native-barricade","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mutualmobile%2Freact-native-barricade","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mutualmobile%2Freact-native-barricade/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mutualmobile%2Freact-native-barricade/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mutualmobile%2Freact-native-barricade/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/mutualmobile","download_url":"https://codeload.github.com/mutualmobile/react-native-barricade/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mutualmobile%2Freact-native-barricade/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":259704411,"owners_count":22898858,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["mockapi","react-native","typescipt"],"created_at":"2024-11-13T18:35:36.302Z","updated_at":"2025-06-13T19:05:29.881Z","avatar_url":"https://github.com/mutualmobile.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# @mutualmobile/react-native-barricade\n\n![Code Coverage](https://img.shields.io/static/v1?label=coverage\u0026message=95\u0026color=brightgreen)\n[![License](https://img.shields.io/github/license/mutualmobile/react-native-barricade)](https://github.com/mutualmobile/react-native-barricade/blob/main/LICENSE)\n[![NPM Version](https://img.shields.io/npm/v/@mutualmobile/react-native-barricade)](https://www.npmjs.com/package/@mutualmobile/react-native-barricade)\n[![Known Vulnerabilities](https://snyk.io/test/github/mutualmobile/react-native-barricade/badge.svg)](https://snyk.io/test/github/mutualmobile/react-native-barricade)\n\nA 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.\n\n`Barricade` works by replacing the global `XMLHttpRequest` and `fetch` object with the `MockedXMLHttpRequest`. 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.\n\n## Why Barricade?\n\nMost 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.\n\n\u003cp align=\"center\"\u003e\n\u003cimg src=\"https://github.com/mutualmobile/react-native-barricade/blob/main/docs/media/demo.gif?raw=true\" alt=\"Example App\" width=\"231\" height=\"500\" /\u003e\n\u003c/p\u003e\n\n## How does Barricade help?\n\nDuring **development**, 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.\n\nBarricade also helps you test edge cases better during **unit and integration testing** as it can easily let you toggle each predefined response to a request.\n\n## Features\n\n- Mock API responses.\n- Change mocked API responses at runtime.\n- Disable/Enable mocking API responses at runtime.\n- Support both Android and iOS platforms.\n- Built-in TypeScript definitions.\n\n## Installation\n```bash\n$ npm install --save @mutualmobile/react-native-barricade\n# --- or ---\n$ yarn add @mutualmobile/react-native-barricade\n```\n\n## Usage\n\n**1. Create and start Barricade**\n\nCreate an instance of Barricade with the help of the `createBarricade` function. While calling this function, you can pass an array of `RequestConfig`(optional) to register the request configs. You can also register a request config later by making use of the `registerRequest` method on the barricade instance.\n\n**:warning: Make sure to do this in index.js so that you can start Barricade before hitting any API.**\n\n```tsx\nimport { createBarricade } from '@mutualmobile/react-native-barricade';\n\nconst requestConfig = []; // Optional: Array of RequestConfigs for all the APIs that needs to be mocked\nconst barricade = createBarricade(requestConfig);\nbarricade.start(); // Start the Barricade\n\nAppRegistry.registerComponent('App', () =\u003e App);\n```\n\n**2. Add BarricadeView**\n\nAdd `BarricadeView` 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.\n\n**:warning: Make sure you add BarricadeView at the end so that it overlays the entire app.**\n\n```tsx\nimport { BarricadeView } from '@mutualmobile/react-native-barricade';\n\nconst App = () =\u003e {\n  return (\n    \u003cView\u003e\n      /* Rest of your app */\n      \u003cBarricadeView /\u003e\n    \u003c/View\u003e\n  );\n};\n```\n**BarricadeView:**  \n| Property              | Description                                                                                                                                                            | Type                      |\n| --------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------- |\n| **`theme`**           | Use this to select the preferred color scheme. It can be `dark` or `light`. This is optional and by default it's `light`.                                              | `ThemeType` / `undefined` |\n\n**3. Create RequestConfigs**\n\nCreate a `RequestConfig` 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 the `registerRequest` method as shown below.\n\n```tsx\nimport { getBarricadeInstance } from '@mutualmobile/react-native-barricade';\n\nconst apiRequestConfig = {}; // RequestConfig for a particular API that you wish to mock.\ngetBarricadeInstance()?.registerRequest(apiRequestConfig);\n```\n\n**:warning: Make sure to call the `registerRequest` method only after the Barricade instance is created.**\n\nIn case you want to unregister a config programmatically, you can do this by calling the `unregisterRequest` method similar to the registerRequest method.\n\n```tsx\nimport { getBarricadeInstance } from '@mutualmobile/react-native-barricade';\n\nconst apiRequestConfig = {}; // RequestConfig object that was previously used for registering\ngetBarricadeInstance()?.unregisterRequest(apiRequestConfig);\n```\n\n**RequestConfig:**  \n| Property              | Description                                                                                                                                                            | Type                      |\n| --------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------- |\n| **`label`**           | String used by developer to identify the request in BarricadeView.                                                                                                     | `string`                  |\n| **`method`**          | Request method type. It can be `Delete`, `Get`, `Head`, `Options`, `Patch`, `Post` or `Put`.                                                                           | `Method`                  |\n| **`pathEvaluation`**  | Data used to identify the current API triggered from the list of RequestConfigs.                                                                                       | `PathEvaluation`          |\n| **`responseHandler`** | List of mocked responses the current API can return with. By default, the first response from the list is selected.                                                    | `ResponseHandler[]`       |\n| **`delay`**           | The time (in milliseconds) Barricade needs to wait before responding with the mocked response. This is optional and by default it's `400`.                             | `number` / `undefined`    |\n| **`disabled`**        | Boolean used to enable/disable mocking of the current API. This is optional and by default it's `undefined`.                                                           | `boolean` / `undefined`   |\n\n**PathEvaluation:**  \n| Property              | Description                                                                                                                                                            | Type                      |\n| --------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------- |\n| **`path`**            | Request URL endpoint.                                                                                                                                                  | `string`                  |\n| **`type`**            | Type of evaluation that needs to be done on path/request to identify the RequestConfig. It can be `Callback`, `Include` or `Suffix`.                                   | `PathEvaluationType`      |\n| **`callback`**        | Function used to identify if this requestConfig needs to be used for resolving the current API with the help of the `Request` argument.                                | `function`                |\n\n**PathEvaluationType:**  \n| Enum Options          | Description                                                                                                                                                            | Type                      |\n| --------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------- |\n| **`Callback`**        | Use this when you cannot identify the RequestConfig with just the help of `path` property. With this type, you need to pass a `callback` function in `pathEvaluation`. | `number`                  |\n| **`Includes`**        | Use this when the `path` passed in `pathEvaluation` can be anywhere within the Request URL.                                                                            | `number`                  |\n| **`Suffix`**          | Use this when the `path` passed in `pathEvaluation` must be at the end of the Request URL.                                                                             | `number`                  |\n\n**ResponseHandler:**  \n| Property              | Description                                                                                                                                                            | Type                      |\n| --------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------- |\n| **`label`**           | String used by developer to identify the response in BarricadeView.                                                                                                    | `string`                  |\n| **`handler`**         | Function that returns the mocked response for the current API call. It can also tweak the response with the help of the `Request` argument.                            | `function`                |\n| **`isSelected`**      | Used to identify the selected response from the `ResponseHandler[]`. This is optional and by default Barricade selects the first response on the list.                 | `boolean` / `undefined`   |\n\n## Example\n\nIn this example, we will setup Barricade to be able to respond to the `flickr search` API with one of two possible responses. It also shows how to mock an API that is requested using libraries like `axios` that depend on `XMLHttpRequest`\n\n```tsx\nconst SearchApiRequestConfig: RequestConfig = {\n  label: 'Search',\n  method: Method.Get,\n  pathEvaluation: {\n    path: '/services/rest?method=flickr.photos.search',\n    type: PathEvaluationType.Includes,\n  },\n  responseHandler: [\n    {\n      label: 'Success',\n      handler: successResponseHandler, // function that returns success data based on some computation\n    },\n    {\n      label: 'Failure',\n      handler: () =\u003e {\n        return {\n          status: HttpStatusCode.BAD_REQUEST,\n          headers: { 'Content-Type': 'application/json' },\n          response: JSON.stringify(errorData), // JSON formatted error response.\n        };\n      },\n    },\n  ],\n};\n```\n\nEverytime we hit the above API, Barricade executes the `successResponseHandler` 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.\n\n```tsx\nconst successResponseHandler = (request: Request) =\u003e {\n  const { page } = request.params ?? {};\n  const response = page === '1' ? searchPageOne : searchPageTwo; // JSON responses\n\n  return {\n    status: HttpStatusCode.OK,\n    headers: { 'Content-Type': 'application/json' },\n    response: JSON.stringify(response),\n  };\n};\n```\n\n**Using fetch:**\n \nIf you are using `fetch` to make an API request, then the response needs of type Blob.\n\n```tsx\nconst successResponseHandler = (request: Request) =\u003e {\n  const { page } = request.params ?? {};\n  const response = page === '1' ? searchPageOne : searchPageTwo; // JSON responses\n\n  return {\n    status: HttpStatusCode.OK,\n    headers: { 'Content-Type': 'application/json' },\n    response: new Blob([JSON.stringify(response)], {\n      type: 'application/json',\n    }),\n  };\n};\n```\n\n## Build and run the example app\n\nTo run the example app,\n\n**1. Clone the [react-native-barricade](https://github.com/mutualmobile/react-native-barricade) GitHub repository to your computer to get the example application.**\n\n**2. Install all the dependencies**\n```bash\n$ yarn\n```\n**3. Go to example folder and install all the dependencies**\n```bash\n$ cd example\n$ yarn\n```\n\n**4. Install the pods**\n```bash\n$ cd ios \u0026\u0026 pod install \u0026\u0026 cd ..\n```\n\n**5. Generate and Add your Flickr API key**\n\nGenerate your Flickr API key from [here](https://www.flickr.com/services/api/misc.api_keys.html).\nThen add your API key to `flickrKey` property in `example/src/config/dev.ts` and `example/src/config/prod.ts` files.\n\n**6. Run the app in android or iOS**\n```bash\n$ yarn android\n# --- or ---\n$ yarn ios\n```\n\n## Selection Interface\n\nBarricade 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 the `BarricadeView` mentioned in Step 2 under **Usage**.\n\n\u003cp align=\"center\"\u003e\n\u003cimg src=\"https://github.com/mutualmobile/react-native-barricade/blob/main/docs/screenshots/developer-menu.png?raw=true\" alt=\"Developer Menu\" width=\"231\" height=\"500\"/\u003e\n\u003cimg src=\"https://github.com/mutualmobile/react-native-barricade/blob/main/docs/screenshots/request-list.png?raw=true\" alt=\"List View\" width=\"231\" height=\"500\"/\u003e\n\u003cimg src=\"https://github.com/mutualmobile/react-native-barricade/blob/main/docs/screenshots/response-list.png?raw=true\" alt=\"Detail View\" width=\"231\" height=\"500\"/\u003e\n\u003c/p\u003e\n\nWith this in place and the device shaken, you'll be able to see an option for `Barricade` in React Native's developer menu. On tapping the `Barricade` option, you’ll be redirected to a screen with the list of mocked APIs.\n\n**:warning: The Developer Menu is disabled in release (production) builds.**\n\n**Note:** In BarricadeView, apart from changing the selected response for any of the listed APIs, we can also:\n- 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.\n- 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.\n- Reset all the changes done to the list of selected responses.\n\n## Generate Build with Barricade\n\nYou can enable Barricade only in __DEV__ 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.\n\nIf you want to generate a build with Barricade enabled for testing purpose, you will need to create a `debug` build. Follow the below steps to generate a debug build.\n\n**Android:**\n\n\u003cdetails\u003e\n  \u003csummary\u003e\u003cb\u003eFor react-native version \u003c 0.71\u003c/b\u003e\u003c/summary\u003e\n\nIn your **android/app/build.gradle** configuration file, look for the `project.ext.react` map and add the `bundleInDebug: true` and `devDisabledInDebug: false` entries to the map:\n\n```java\nproject.ext.react = [\n    ...\n    bundleInDebug: true, // Will start bundling of .JS bundle and the assets in debug build\n    devDisabledInDebug: false, // Makes sure that __DEV__ is true\n    ...\n]\n```\n\u003c/details\u003e\n\nIn your **android/app/build.gradle** configuration file, inside the `react` configuration block add the below options:\n\n```java\nreact {\n    ...\n    debuggableVariants=[], // Will stop from skipping bundling of JS bundle and the assets in debug build.\n    extraPackagerArgs=[\"--dev\", \"true\"], // Makes sure that __DEV__ is true.\n    ...\n}\n```\n\nNow generate build using the below command.\n\n```bash\ncd android \u0026\u0026 ./gradlew assembleDebug\n```\n\n**iOS:**\n\nFirst set the build configuration to Debug. To do this, go to `Product → Scheme → Edit Scheme (cmd + \u003c)`, select the `Archive` tab from the side, and set the Build Configuration dropdown to `Debug`.\n\nNext tap on `Product → Archive` to archive and then distribute the app.\n\n## Testing with jest\n\nTesting code which uses this library requires some setup since we might need to mock `XMLHttpRequest` and `fetch`.\n\nTo add the mocks, create a file jestSetup.ts (or any other file name) containing the following code:\n\n```tsx\njest.mock(\"@mutualmobile/react-native-barricade\", () =\u003e {\n\treturn {\n\t\tfetch: jest.fn(),\n\t\tHeaders: jest.fn(),\n\t\tRequest: jest.fn(),\n\t\tResponse: jest.fn(),\n\t\tXMLHttpRequest: jest.fn()\n\t};\n});\n```\n\nAfter that, we need to add the setup file in the jest config. You can add it under setupFiles option in your jest config file:\n\n```json\n{\n  \"setupFiles\": [\"\u003crootDir\u003e/jestSetup.ts\"]\n}\n```\n\n## Credits\n\nBarricade was created by [Prajna Boloor](https://www.linkedin.com/in/prajna-boloor/) at [Mutual Mobile](http://www.mutualmobile.com).\n\nA special shout-out to the React Native team at Mutual Mobile for their feedback.\n\n## License\n\nDistributed under the MIT License. See [LICENSE.txt](https://github.com/mutualmobile/react-native-barricade/blob/feature/readme/LICENSE) for more information.\n\n\n## Support Us\n\nIf this project has helped you out, please support us with a star 🌟.\n\n## Acknowledgements\n\n- [Pretender](https://github.com/pretenderjs/pretender)\n- [FakeXMLHttpRequest](https://github.com/pretenderjs/FakeXMLHttpRequest)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmutualmobile%2Freact-native-barricade","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmutualmobile%2Freact-native-barricade","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmutualmobile%2Freact-native-barricade/lists"}