├── .babelrc.json ├── .eslintrc.json ├── .gitignore ├── .npmignore ├── .travis.yml ├── .vscode └── launch.json ├── LICENSE ├── README.md ├── __mocks__ └── index.js ├── dist ├── index.js ├── response.js └── util.js ├── example ├── Basic │ ├── .buckconfig │ ├── .eslintrc.js │ ├── .flowconfig │ ├── .gitattributes │ ├── .gitignore │ ├── .prettierrc.js │ ├── .watchmanconfig │ ├── __mocks__ │ │ └── index.js │ ├── __tests__ │ │ └── App-test.js │ ├── android │ │ ├── app │ │ │ ├── BUCK │ │ │ ├── build.gradle │ │ │ ├── build_defs.bzl │ │ │ ├── debug.keystore │ │ │ ├── proguard-rules.pro │ │ │ └── src │ │ │ │ ├── debug │ │ │ │ ├── AndroidManifest.xml │ │ │ │ └── java │ │ │ │ │ └── com │ │ │ │ │ └── basic │ │ │ │ │ └── ReactNativeFlipper.java │ │ │ │ └── main │ │ │ │ ├── AndroidManifest.xml │ │ │ │ ├── java │ │ │ │ └── com │ │ │ │ │ └── basic │ │ │ │ │ ├── MainActivity.java │ │ │ │ │ └── MainApplication.java │ │ │ │ └── res │ │ │ │ ├── mipmap-hdpi │ │ │ │ ├── ic_launcher.png │ │ │ │ └── ic_launcher_round.png │ │ │ │ ├── mipmap-mdpi │ │ │ │ ├── ic_launcher.png │ │ │ │ └── ic_launcher_round.png │ │ │ │ ├── mipmap-xhdpi │ │ │ │ ├── ic_launcher.png │ │ │ │ └── ic_launcher_round.png │ │ │ │ ├── mipmap-xxhdpi │ │ │ │ ├── ic_launcher.png │ │ │ │ └── ic_launcher_round.png │ │ │ │ ├── mipmap-xxxhdpi │ │ │ │ ├── ic_launcher.png │ │ │ │ └── ic_launcher_round.png │ │ │ │ └── values │ │ │ │ ├── strings.xml │ │ │ │ └── styles.xml │ │ ├── build.gradle │ │ ├── gradle.properties │ │ ├── gradle │ │ │ └── wrapper │ │ │ │ ├── gradle-wrapper.jar │ │ │ │ └── gradle-wrapper.properties │ │ ├── gradlew │ │ ├── gradlew.bat │ │ └── settings.gradle │ ├── app.json │ ├── babel.config.js │ ├── index.js │ ├── ios │ │ ├── Basic-tvOS │ │ │ └── Info.plist │ │ ├── Basic-tvOSTests │ │ │ └── Info.plist │ │ ├── Basic.xcodeproj │ │ │ ├── project.pbxproj │ │ │ └── xcshareddata │ │ │ │ └── xcschemes │ │ │ │ ├── Basic-tvOS.xcscheme │ │ │ │ └── Basic.xcscheme │ │ ├── Basic.xcworkspace │ │ │ └── contents.xcworkspacedata │ │ ├── Basic │ │ │ ├── AppDelegate.h │ │ │ ├── AppDelegate.m │ │ │ ├── Images.xcassets │ │ │ │ ├── AppIcon.appiconset │ │ │ │ │ └── Contents.json │ │ │ │ └── Contents.json │ │ │ ├── Info.plist │ │ │ ├── LaunchScreen.storyboard │ │ │ └── main.m │ │ ├── BasicTests │ │ │ ├── BasicTests.m │ │ │ └── Info.plist │ │ ├── Podfile │ │ └── Podfile.lock │ ├── metro.config.js │ ├── package.json │ ├── src │ │ └── app.js │ └── yarn.lock └── WithMockJs │ ├── .buckconfig │ ├── .eslintrc.js │ ├── .flowconfig │ ├── .gitattributes │ ├── .gitignore │ ├── .prettierrc.js │ ├── .watchmanconfig │ ├── __mocks__ │ └── index.js │ ├── __tests__ │ └── App-test.js │ ├── android │ ├── app │ │ ├── BUCK │ │ ├── build.gradle │ │ ├── build_defs.bzl │ │ ├── debug.keystore │ │ ├── proguard-rules.pro │ │ └── src │ │ │ ├── debug │ │ │ ├── AndroidManifest.xml │ │ │ └── java │ │ │ │ └── com │ │ │ │ └── withmockjs │ │ │ │ └── ReactNativeFlipper.java │ │ │ └── main │ │ │ ├── AndroidManifest.xml │ │ │ ├── java │ │ │ └── com │ │ │ │ └── withmockjs │ │ │ │ ├── MainActivity.java │ │ │ │ └── MainApplication.java │ │ │ └── res │ │ │ ├── mipmap-hdpi │ │ │ ├── ic_launcher.png │ │ │ └── ic_launcher_round.png │ │ │ ├── mipmap-mdpi │ │ │ ├── ic_launcher.png │ │ │ └── ic_launcher_round.png │ │ │ ├── mipmap-xhdpi │ │ │ ├── ic_launcher.png │ │ │ └── ic_launcher_round.png │ │ │ ├── mipmap-xxhdpi │ │ │ ├── ic_launcher.png │ │ │ └── ic_launcher_round.png │ │ │ ├── mipmap-xxxhdpi │ │ │ ├── ic_launcher.png │ │ │ └── ic_launcher_round.png │ │ │ └── values │ │ │ ├── strings.xml │ │ │ └── styles.xml │ ├── build.gradle │ ├── gradle.properties │ ├── gradle │ │ └── wrapper │ │ │ ├── gradle-wrapper.jar │ │ │ └── gradle-wrapper.properties │ ├── gradlew │ ├── gradlew.bat │ └── settings.gradle │ ├── app.json │ ├── babel.config.js │ ├── index.js │ ├── ios │ ├── Podfile │ ├── Podfile.lock │ ├── WithMockJs-tvOS │ │ └── Info.plist │ ├── WithMockJs-tvOSTests │ │ └── Info.plist │ ├── WithMockJs.xcodeproj │ │ ├── project.pbxproj │ │ └── xcshareddata │ │ │ └── xcschemes │ │ │ ├── WithMockJs-tvOS.xcscheme │ │ │ └── WithMockJs.xcscheme │ ├── WithMockJs.xcworkspace │ │ └── contents.xcworkspacedata │ ├── WithMockJs │ │ ├── AppDelegate.h │ │ ├── AppDelegate.m │ │ ├── Images.xcassets │ │ │ ├── AppIcon.appiconset │ │ │ │ └── Contents.json │ │ │ └── Contents.json │ │ ├── Info.plist │ │ ├── LaunchScreen.storyboard │ │ └── main.m │ └── WithMockJsTests │ │ ├── Info.plist │ │ └── WithMockJsTests.m │ ├── metro.config.js │ ├── package.json │ ├── src │ └── app.js │ └── yarn.lock ├── index.js ├── package.json ├── src ├── index.js ├── response.js └── util.js ├── test ├── fallbackToNetwork.test.js ├── index.test.js └── util.test.js └── yarn.lock /.babelrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "presets": ["module:metro-react-native-babel-preset"] 3 | } -------------------------------------------------------------------------------- /.eslintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "parser": "@babel/eslint-parser", 3 | "env": { 4 | "browser": true, 5 | "es6": true 6 | }, 7 | "extends": "eslint:recommended", 8 | "rules": { 9 | "indent": [ 10 | "error", 11 | 2 12 | ], 13 | "linebreak-style": [ 14 | "error", 15 | "unix" 16 | ], 17 | "quotes": [ 18 | "error", 19 | "single" 20 | ], 21 | "semi": [ 22 | "error", 23 | "always" 24 | ] 25 | } 26 | } -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | 6 | # Runtime data 7 | pids 8 | *.pid 9 | *.seed 10 | 11 | # Directory for instrumented libs generated by jscoverage/JSCover 12 | lib-cov 13 | 14 | # Coverage directory used by tools like istanbul 15 | coverage 16 | 17 | # nyc test coverage 18 | .nyc_output 19 | 20 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 21 | .grunt 22 | 23 | # node-waf configuration 24 | .lock-wscript 25 | 26 | # Compiled binary addons (http://nodejs.org/api/addons.html) 27 | build/Release 28 | 29 | # Dependency directories 30 | node_modules 31 | jspm_packages 32 | 33 | # Optional npm cache directory 34 | .npm 35 | 36 | # Optional REPL history 37 | .node_repl_history 38 | 39 | # MACOS 40 | .DS_Store 41 | -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | logs 3 | *.log 4 | __mocks__ 5 | node_modules 6 | example 7 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | node_js: 3 | - '12.19.0' 4 | - '15.0.1' -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | // 使用 IntelliSense 了解相关属性。 3 | // 悬停以查看现有属性的描述。 4 | // 欲了解更多信息,请访问: https://go.microsoft.com/fwlink/?linkid=830387 5 | "version": "0.2.0", 6 | "configurations": [ 7 | { 8 | "type": "node", 9 | "request": "launch", 10 | "name": "Mocha Debug", 11 | "skipFiles": [ 12 | "/**" 13 | ], 14 | "program": "${workspaceFolder}/node_modules/.bin/mocha", 15 | "args": [ 16 | "--require", 17 | "@babel/register", 18 | "--reporter", 19 | "dot", 20 | "--slow", 21 | "5000", 22 | "--colors", 23 | "${workspaceFolder}/test/**/*.test.js", 24 | 25 | ], 26 | "internalConsoleOptions": "openOnSessionStart" 27 | } 28 | ] 29 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2017 WhatAKitty 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # react-native-fetch-mock 2 | [![Build Status](https://travis-ci.org/WhatAKitty/react-native-fetch-mock.svg?branch=master)](https://travis-ci.org/WhatAKitty/react-native-fetch-mock) 3 | [![Known Vulnerabilities](https://snyk.io/test/npm/react-native-fetch-mock/badge.svg)](https://snyk.io/test/npm/react-native-fetch-mock) 4 | [![npm version](https://badge.fury.io/js/react-native-fetch-mock.svg)](https://npmjs.org/package/react-native-fetch-mock) 5 | [![npm downloads](https://img.shields.io/npm/dm/react-native-fetch-mock.svg?style=flat)](https://npmjs.org/package/react-native-fetch-mock) 6 | [![Rate on Openbase](https://badges.openbase.io/js/rating/react-native-fetch-mock.svg)](https://openbase.io/js/react-native-fetch-mock?utm_source=embedded&utm_medium=badge&utm_campaign=rate-badge) 7 | 8 | fetch mock for react-native 9 | 10 | [React Version](https://github.com/WhatAKitty/react-fetch-mock) 11 | 12 | ## Why FetchMock ? 13 | No fetch mock could be used easily for react-native. 14 | So, I create one by myself. 15 | 16 | ## Requirements 17 | 18 | Nodejs >= 12.x 19 | 20 | ## Roadmap 21 | - [x] Combined with Mock.js 22 | - [x] Support exclude for some other path 23 | - [x] Proxy for other api server 24 | - [x] Delay for global and specific path 25 | - [x] Support flexible fallback to network([#6](https://github.com/WhatAKitty/react-native-fetch-mock/issues/6)) 26 | - [ ] Support inline valiation(such as: '/api/users/{userid:[a-z|A-Z]}') 27 | 28 | ## Usage 29 | 30 | __ mocks__/index.js 31 | ``` 32 | export default { 33 | '/api/path': ({ method, url, params, urlparams, headers }) => { 34 | const all = Mock.mock({ 35 | 'list|2': [{ 36 | 'id|+1': 1, 37 | 'name': '@first @last', 38 | 'age|18-54': 1, 39 | }] 40 | }).list; 41 | return all; // default status is 200 42 | }, 43 | '/api/path/{id}': ({ method, url, params, urlparams, headers }) => { 44 | const all = Mock.mock({ 45 | 'list|2': [{ 46 | 'id|+1': 1, 47 | 'name': '@first @last', 48 | 'age|18-54': 1, 49 | 'urlid': urlparams.id, 50 | }] 51 | }).list; 52 | return all; 53 | }, 54 | 'POST /api/path': ({ method, url, params, urlparams, headers }) => { 55 | return { 56 | status: 201, 57 | }; 58 | }, 59 | 'PUT /api/path/${id}': ({ method, url, params, urlparams, headers }) => { 60 | return { 61 | status: 204, 62 | id: urlparams.id, 63 | }; 64 | }, 65 | } 66 | ``` 67 | index.js 68 | ``` 69 | import FetchMock from 'react-native-fetch-mock'; 70 | 71 | if (__dev__) { 72 | global.fetch = new FetchMock(require('path/to/mocks/directory'), { 73 | delay: 200, // 200ms 74 | fetch: global.fetch, 75 | exclude: [ 76 | 'http://www.google.com', 77 | '/foo(.*)', 78 | ], 79 | fallbackToNetwork: true, // ['true', 'false', 'always'], true: Unhandled calls fall through to the network;false: Unhandled calls throw an error; 'always': All calls fall through to the network, effectively disabling react-native-fetch-mock 80 | proxy: [{ 81 | path: '/path/for/proxy(.*)', 82 | target: 'http://other.proxy.server', 83 | process: (proxied, matches) => { 84 | return `${proxied.target}${matches[1]}`, 85 | }, 86 | }], 87 | }).fetch; 88 | } 89 | 90 | // if __dev__ is true, it will back the data you defined in mock directory 91 | fetch('/api/path', options); 92 | fetch('/api/path', { 93 | delay: 2000, // /api/path will delayed after 2000ms. Most of suitation, this won't be used usually. 94 | method: 'POST', 95 | headers: { 96 | 'Content-Type': 'application/json', 97 | }, 98 | body: JSON.stringify({ 99 | name: 'John', 100 | }), 101 | }); 102 | fetch('/api/path/123', { 103 | method: 'PUT', 104 | headers: { 105 | 'Content-Type': 'application/json', 106 | }, 107 | body: JSON.stringify({ 108 | name: 'John2', 109 | }), 110 | }); 111 | ``` 112 | 113 | ## Example Runing 114 | 115 | ``` 116 | git clone git@github.com:WhatAKitty/react-native-fetch-mock.git 117 | cd react-native-fetch-mock/example/Basic 118 | npm install (attention: don't use yarn while install example dep) 119 | react-native run-ios 120 | ``` 121 | 122 | ## LICENSE 123 | 124 | MIT 125 | -------------------------------------------------------------------------------- /__mocks__/index.js: -------------------------------------------------------------------------------- 1 | import { Mock } from '../src'; 2 | 3 | export default { 4 | '/api/users': ({ params }) => { 5 | const all = [ 6 | { 7 | name: 'John', 8 | age: 15, 9 | }, 10 | { 11 | name: 'Lily', 12 | age: 16, 13 | } 14 | ]; 15 | let filtered; 16 | if ('undefined' !== typeof params) { 17 | filtered = all.filter(item => { 18 | let result = true; 19 | const keys = Object.keys(params); 20 | keys.forEach(key => { 21 | const param = params[key]; 22 | 23 | if (item[key] && item[key] !== param) { 24 | result = false; 25 | } 26 | }); 27 | 28 | return result; 29 | }); 30 | } else { 31 | filtered = all; 32 | } 33 | return { 34 | status: 200, 35 | data: filtered, 36 | }; 37 | }, 38 | '/api/users/mockjs': ({ params }) => { 39 | const all = Mock.mock({ 40 | 'list|2': [{ 41 | 'id|+1': 1, 42 | 'name': '@first @last', 43 | 'age|18-54': 1, 44 | }] 45 | }).list; 46 | let filtered; 47 | if ('undefined' !== typeof params) { 48 | filtered = all.filter(item => { 49 | let result = true; 50 | const keys = Object.keys(params); 51 | keys.forEach(key => { 52 | const param = params[key]; 53 | 54 | if (item[key] && item[key] !== param) { 55 | result = false; 56 | } 57 | }); 58 | 59 | return result; 60 | }); 61 | } else { 62 | filtered = all; 63 | } 64 | return { 65 | status: 200, 66 | data: filtered, 67 | }; 68 | }, 69 | '/api/users/{userId}': ({ urlparams }) => { 70 | return { 71 | status: 200, 72 | data: { 73 | userId: urlparams.userId, 74 | }, 75 | }; 76 | }, 77 | '/api/users/pru/{userId}': ({ urlparams }) => { 78 | return { 79 | userId: urlparams.userId, 80 | }; 81 | }, 82 | 'POST /api/users': () => { 83 | return { 84 | status: 201, 85 | }; 86 | }, 87 | 'PUT /api/users/{userId}': ({ urlparams }) => { 88 | return { 89 | status: 204, 90 | data: { 91 | userId: urlparams.userId, 92 | }, 93 | }; 94 | } 95 | } 96 | -------------------------------------------------------------------------------- /dist/index.js: -------------------------------------------------------------------------------- 1 | var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});Object.defineProperty(exports,"Mock",{enumerable:true,get:function get(){return _mockjs.default;}});exports.default=void 0;var _classCallCheck2=_interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));var _createClass2=_interopRequireDefault(require("@babel/runtime/helpers/createClass"));var _pathToRegexp=require("path-to-regexp");var _util=require("./util");var _response=_interopRequireDefault(require("./response"));var _mockjs=_interopRequireDefault(require("mockjs"));var FetchMock=function(){function FetchMock(required){var options=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{fetch:function fetch(){},exclude:[],fallbackToNetwork:false,proxy:[],delay:2000};(0,_classCallCheck2.default)(this,FetchMock);if('object'!==typeof required){throw new Error('There is no required defined.');}this.urls=[];this.raw=options.fetch;this.exclude=options.exclude||[];this.fallbackToNetwork=options.fallbackToNetwork||false;this.proxy=options.proxy||[];this.delayTime=options.delay;this.loadMocks=this.loadMocks.bind(this);this.loadMock=this.loadMock.bind(this);this.matchReqUrl=this.matchReqUrl.bind(this);this.isExclude=this.isExclude.bind(this);this.isProxied=this.isProxied.bind(this);this.fetch=this.fetch.bind(this);this.loadMocks(required);}(0,_createClass2.default)(FetchMock,[{key:"loadMocks",value:function loadMocks(required){var _this=this;var __mocks__=required.default||required;var mocks=Object.keys(__mocks__);mocks.forEach(function(key){_this.loadMock(key,__mocks__[key]);});}},{key:"loadMock",value:function loadMock(key,mock){var _this2=this;if('object'!==typeof mock){if('function'===typeof mock){var items=key.split(' ');var method=items.length===2?items[0]:'GET';var url=items.length===2?items[1]:key;this.urls.push({method:method,url:url,func:mock});}return;}var keys=Object.keys(mock);keys.map(function(key){_this2.loadMock(key,mock[key]);});}},{key:"matchReqUrl",value:function matchReqUrl(request){var insideParams;var filters=this.urls.filter(function(uri){var obj=(0,_util.matchUrl)(uri.url,request.url);if(obj.result&&uri.method.toUpperCase()===request.method.toUpperCase()){insideParams=obj.params;return true;}return false;});if(!filters||filters.length==0){return{matched:false};}request.urlparams=insideParams;return{matched:true,request:request,mock:filters[0]};}},{key:"isExclude",value:function isExclude(url){for(var i=0;i1)throw new Error(url+" proxied has two proxies, you should specific only one");return proxied[0];}},{key:"proxied",value:function proxied(url){var matches,proxied;this.proxy.forEach(function(item){var tmp=(0,_pathToRegexp.pathToRegexp)(item.path).exec(url);if(tmp.length>1){matches=tmp;proxied=item;return false;}});return proxied.process?proxied.process(proxied,matches):proxied.target+"/"+matches[1];}},{key:"fetch",value:function fetch(url){var options=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};if(this.isProxied(url)){url=this.proxied(url);}if(this.isExclude(url)||this.fallbackToNetwork==='always'){return this.raw(url,options);}var _this$matchReqUrl=this.matchReqUrl((0,_util.parseRequest)(url,options)),matched=_this$matchReqUrl.matched,request=_this$matchReqUrl.request,mock=_this$matchReqUrl.mock;if(!matched){if(this.fallbackToNetwork){return this.raw(url,options);}else{throw new Error("No url "+url+" is defined.");}}if('function'!==typeof mock.func){throw new Error("The url "+url+" defined in __mocks__ is not a function");}var obj=mock.func(request);if((0,_util.isNull)(obj)){throw'response data should not be undefined or null, it will be an object or an array at least';}if((0,_util.isNull)(obj.status)){obj={status:200,data:obj};}var response=new _response.default(obj);var delayTime=options.delay||this.delayTime||0;return(0,_util.delay)(delayTime).then(function(){return Promise.resolve(response);});}}]);return FetchMock;}();var _default=FetchMock;exports.default=_default; -------------------------------------------------------------------------------- /dist/response.js: -------------------------------------------------------------------------------- 1 | var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _classCallCheck2=_interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));var _createClass2=_interopRequireDefault(require("@babel/runtime/helpers/createClass"));var _status=Symbol('status');var _data=Symbol('data');var _statusText=Symbol('statusText');var Response=function(){function Response(_ref){var status=_ref.status,_ref$data=_ref.data,data=_ref$data===void 0?{}:_ref$data,_ref$statusText=_ref.statusText,statusText=_ref$statusText===void 0?'':_ref$statusText;(0,_classCallCheck2.default)(this,Response);this[_status]=status;this[_data]=data;this[_statusText]=statusText;}(0,_createClass2.default)(Response,[{key:"text",value:function text(){try{return Promise.resolve(JSON.stringify(this[_data]));}catch(err){return Promise.reject(new Error('failed text invoke.'));}}},{key:"json",value:function json(){return this[_data];}},{key:"status",get:function get(){return this[_status];}},{key:"statusText",get:function get(){return this[_statusText];}},{key:"ok",get:function get(){if(this.status>=200&&this.status<300){return true;}else{return false;}}}]);return Response;}();var _default=Response;exports.default=_default; -------------------------------------------------------------------------------- /dist/util.js: -------------------------------------------------------------------------------- 1 | var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.delay=exports.matchUrl=exports.parseRequest=exports.parseUrl=exports.prueUrl=exports.isNull=void 0;var _extends2=_interopRequireDefault(require("@babel/runtime/helpers/extends"));var isNull=function isNull(obj){if('undefined'===typeof obj||obj===null){return true;}return false;};exports.isNull=isNull;var removeProctol=function removeProctol(url){var index=-1;if((index=url.indexOf('://'))>-1){return url.substring(index);}return url;};var parseParamStr=function parseParamStr(paramStr,isGet){var params={};var paramPairs=paramStr.split('&');for(var i=0;i-1?url.split('?'):[url];if(items.length===1){return{url:items[0],params:{}};}return{url:items[0],params:parseParamStr(items[1],true)};};exports.parseUrl=parseUrl;var parseRequest=function parseRequest(url){var options=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var urlObj=parseUrl(url);var data=parseBody(options.body||{});return{method:options.method||'GET',url:urlObj.url,headers:options.headers,params:(0,_extends2.default)({},urlObj.params,data)};};exports.parseRequest=parseRequest;var prueUrl=function prueUrl(url){var index=url.indexOf('?');var result=index>-1?url.substring(0,index):url;return result;};exports.prueUrl=prueUrl;var matchUrl=function matchUrl(sourceUrl,targetUrl){if(sourceUrl===targetUrl){return{result:true,params:{}};}var sourceUrlWithoutProctol=removeProctol(sourceUrl);var targetUrlWithoutProctol=removeProctol(targetUrl);var sourceUrlSplits=sourceUrlWithoutProctol.split('/');var targetUrlSplits=targetUrlWithoutProctol.split('/');if(sourceUrlSplits.length!==targetUrlSplits.length){return{result:false};}var params={};for(var i=0;i1||sourceUrlSplit.replace(/[^}]/g,'').length>1){return{result:false};}params[sourceUrlSplit.substring(1,sourceUrlSplit.length-1)]=targetUrlSplit;continue;}return{result:false};}return{result:true,params:params};};exports.matchUrl=matchUrl;var delay=function delay(duration){return new Promise(function(resolve){setTimeout(function(){resolve();},duration);});};exports.delay=delay; -------------------------------------------------------------------------------- /example/Basic/.buckconfig: -------------------------------------------------------------------------------- 1 | 2 | [android] 3 | target = Google Inc.:Google APIs:23 4 | 5 | [maven_repositories] 6 | central = https://repo1.maven.org/maven2 7 | -------------------------------------------------------------------------------- /example/Basic/.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | root: true, 3 | extends: '@react-native-community', 4 | }; 5 | -------------------------------------------------------------------------------- /example/Basic/.flowconfig: -------------------------------------------------------------------------------- 1 | [ignore] 2 | ; We fork some components by platform 3 | .*/*[.]android.js 4 | 5 | ; Ignore "BUCK" generated dirs 6 | /\.buckd/ 7 | 8 | ; Ignore polyfills 9 | node_modules/react-native/Libraries/polyfills/.* 10 | 11 | ; These should not be required directly 12 | ; require from fbjs/lib instead: require('fbjs/lib/warning') 13 | node_modules/warning/.* 14 | 15 | ; Flow doesn't support platforms 16 | .*/Libraries/Utilities/LoadingView.js 17 | 18 | [untyped] 19 | .*/node_modules/@react-native-community/cli/.*/.* 20 | 21 | [include] 22 | 23 | [libs] 24 | node_modules/react-native/interface.js 25 | node_modules/react-native/flow/ 26 | 27 | [options] 28 | emoji=true 29 | 30 | esproposal.optional_chaining=enable 31 | esproposal.nullish_coalescing=enable 32 | 33 | module.file_ext=.js 34 | module.file_ext=.json 35 | module.file_ext=.ios.js 36 | 37 | munge_underscores=true 38 | 39 | module.name_mapper='^react-native/\(.*\)$' -> '/node_modules/react-native/\1' 40 | module.name_mapper='^@?[./a-zA-Z0-9$_-]+\.\(bmp\|gif\|jpg\|jpeg\|png\|psd\|svg\|webp\|m4v\|mov\|mp4\|mpeg\|mpg\|webm\|aac\|aiff\|caf\|m4a\|mp3\|wav\|html\|pdf\)$' -> '/node_modules/react-native/Libraries/Image/RelativeImageStub' 41 | 42 | suppress_type=$FlowIssue 43 | suppress_type=$FlowFixMe 44 | suppress_type=$FlowFixMeProps 45 | suppress_type=$FlowFixMeState 46 | 47 | suppress_comment=\\(.\\|\n\\)*\\$FlowFixMe\\($\\|[^(]\\|(\\(\\)? *\\(site=[a-z,_]*react_native\\(_ios\\)?_\\(oss\\|fb\\)[a-z,_]*\\)?)\\) 48 | suppress_comment=\\(.\\|\n\\)*\\$FlowIssue\\((\\(\\)? *\\(site=[a-z,_]*react_native\\(_ios\\)?_\\(oss\\|fb\\)[a-z,_]*\\)?)\\)?:? #[0-9]+ 49 | suppress_comment=\\(.\\|\n\\)*\\$FlowExpectedError 50 | 51 | [lints] 52 | sketchy-null-number=warn 53 | sketchy-null-mixed=warn 54 | sketchy-number=warn 55 | untyped-type-import=warn 56 | nonstrict-import=warn 57 | deprecated-type=warn 58 | unsafe-getters-setters=warn 59 | unnecessary-invariant=warn 60 | signature-verification-failure=warn 61 | deprecated-utility=error 62 | 63 | [strict] 64 | deprecated-type 65 | nonstrict-import 66 | sketchy-null 67 | unclear-type 68 | unsafe-getters-setters 69 | untyped-import 70 | untyped-type-import 71 | 72 | [version] 73 | ^0.122.0 74 | -------------------------------------------------------------------------------- /example/Basic/.gitattributes: -------------------------------------------------------------------------------- 1 | *.pbxproj -text 2 | -------------------------------------------------------------------------------- /example/Basic/.gitignore: -------------------------------------------------------------------------------- 1 | # OSX 2 | # 3 | .DS_Store 4 | 5 | # Xcode 6 | # 7 | build/ 8 | *.pbxuser 9 | !default.pbxuser 10 | *.mode1v3 11 | !default.mode1v3 12 | *.mode2v3 13 | !default.mode2v3 14 | *.perspectivev3 15 | !default.perspectivev3 16 | xcuserdata 17 | *.xccheckout 18 | *.moved-aside 19 | DerivedData 20 | *.hmap 21 | *.ipa 22 | *.xcuserstate 23 | 24 | # Android/IntelliJ 25 | # 26 | build/ 27 | .idea 28 | .gradle 29 | local.properties 30 | *.iml 31 | 32 | # node.js 33 | # 34 | node_modules/ 35 | npm-debug.log 36 | yarn-error.log 37 | 38 | # BUCK 39 | buck-out/ 40 | \.buckd/ 41 | *.keystore 42 | !debug.keystore 43 | 44 | # fastlane 45 | # 46 | # It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the 47 | # screenshots whenever they are needed. 48 | # For more information about the recommended setup visit: 49 | # https://docs.fastlane.tools/best-practices/source-control/ 50 | 51 | */fastlane/report.xml 52 | */fastlane/Preview.html 53 | */fastlane/screenshots 54 | 55 | # Bundle artifact 56 | *.jsbundle 57 | 58 | # CocoaPods 59 | /ios/Pods/ 60 | -------------------------------------------------------------------------------- /example/Basic/.prettierrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | bracketSpacing: false, 3 | jsxBracketSameLine: true, 4 | singleQuote: true, 5 | trailingComma: 'all', 6 | }; 7 | -------------------------------------------------------------------------------- /example/Basic/.watchmanconfig: -------------------------------------------------------------------------------- 1 | {} -------------------------------------------------------------------------------- /example/Basic/__mocks__/index.js: -------------------------------------------------------------------------------- 1 | 2 | export default { 3 | '/api/users': ({ params }) => { 4 | const all = [ 5 | { 6 | name: 'John', 7 | age: 15, 8 | }, 9 | { 10 | name: 'Lily', 11 | age: 16, 12 | } 13 | ]; 14 | let filtered; 15 | if ('undefined' !== typeof params) { 16 | filtered = all.filter(item => { 17 | let result = true; 18 | const keys = Object.keys(params); 19 | keys.forEach(key => { 20 | const param = params[key]; 21 | 22 | if (item[key] && item[key] !== param) { 23 | result = false; 24 | } 25 | }); 26 | 27 | return result; 28 | }); 29 | } else { 30 | filtered = all; 31 | } 32 | return { 33 | status: 200, 34 | data: filtered, 35 | }; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /example/Basic/__tests__/App-test.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @format 3 | */ 4 | 5 | import 'react-native'; 6 | import React from 'react'; 7 | import App from '../App'; 8 | 9 | // Note: test renderer must be required after react-native. 10 | import renderer from 'react-test-renderer'; 11 | 12 | it('renders correctly', () => { 13 | renderer.create(); 14 | }); 15 | -------------------------------------------------------------------------------- /example/Basic/android/app/BUCK: -------------------------------------------------------------------------------- 1 | # To learn about Buck see [Docs](https://buckbuild.com/). 2 | # To run your application with Buck: 3 | # - install Buck 4 | # - `npm start` - to start the packager 5 | # - `cd android` 6 | # - `keytool -genkey -v -keystore keystores/debug.keystore -storepass android -alias androiddebugkey -keypass android -dname "CN=Android Debug,O=Android,C=US"` 7 | # - `./gradlew :app:copyDownloadableDepsToLibs` - make all Gradle compile dependencies available to Buck 8 | # - `buck install -r android/app` - compile, install and run application 9 | # 10 | 11 | load(":build_defs.bzl", "create_aar_targets", "create_jar_targets") 12 | 13 | lib_deps = [] 14 | 15 | create_aar_targets(glob(["libs/*.aar"])) 16 | 17 | create_jar_targets(glob(["libs/*.jar"])) 18 | 19 | android_library( 20 | name = "all-libs", 21 | exported_deps = lib_deps, 22 | ) 23 | 24 | android_library( 25 | name = "app-code", 26 | srcs = glob([ 27 | "src/main/java/**/*.java", 28 | ]), 29 | deps = [ 30 | ":all-libs", 31 | ":build_config", 32 | ":res", 33 | ], 34 | ) 35 | 36 | android_build_config( 37 | name = "build_config", 38 | package = "com.basic", 39 | ) 40 | 41 | android_resource( 42 | name = "res", 43 | package = "com.basic", 44 | res = "src/main/res", 45 | ) 46 | 47 | android_binary( 48 | name = "app", 49 | keystore = "//android/keystores:debug", 50 | manifest = "src/main/AndroidManifest.xml", 51 | package_type = "debug", 52 | deps = [ 53 | ":app-code", 54 | ], 55 | ) 56 | -------------------------------------------------------------------------------- /example/Basic/android/app/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: "com.android.application" 2 | 3 | import com.android.build.OutputFile 4 | 5 | /** 6 | * The react.gradle file registers a task for each build variant (e.g. bundleDebugJsAndAssets 7 | * and bundleReleaseJsAndAssets). 8 | * These basically call `react-native bundle` with the correct arguments during the Android build 9 | * cycle. By default, bundleDebugJsAndAssets is skipped, as in debug/dev mode we prefer to load the 10 | * bundle directly from the development server. Below you can see all the possible configurations 11 | * and their defaults. If you decide to add a configuration block, make sure to add it before the 12 | * `apply from: "../../node_modules/react-native/react.gradle"` line. 13 | * 14 | * project.ext.react = [ 15 | * // the name of the generated asset file containing your JS bundle 16 | * bundleAssetName: "index.android.bundle", 17 | * 18 | * // the entry file for bundle generation. If none specified and 19 | * // "index.android.js" exists, it will be used. Otherwise "index.js" is 20 | * // default. Can be overridden with ENTRY_FILE environment variable. 21 | * entryFile: "index.android.js", 22 | * 23 | * // https://reactnative.dev/docs/performance#enable-the-ram-format 24 | * bundleCommand: "ram-bundle", 25 | * 26 | * // whether to bundle JS and assets in debug mode 27 | * bundleInDebug: false, 28 | * 29 | * // whether to bundle JS and assets in release mode 30 | * bundleInRelease: true, 31 | * 32 | * // whether to bundle JS and assets in another build variant (if configured). 33 | * // See http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Build-Variants 34 | * // The configuration property can be in the following formats 35 | * // 'bundleIn${productFlavor}${buildType}' 36 | * // 'bundleIn${buildType}' 37 | * // bundleInFreeDebug: true, 38 | * // bundleInPaidRelease: true, 39 | * // bundleInBeta: true, 40 | * 41 | * // whether to disable dev mode in custom build variants (by default only disabled in release) 42 | * // for example: to disable dev mode in the staging build type (if configured) 43 | * devDisabledInStaging: true, 44 | * // The configuration property can be in the following formats 45 | * // 'devDisabledIn${productFlavor}${buildType}' 46 | * // 'devDisabledIn${buildType}' 47 | * 48 | * // the root of your project, i.e. where "package.json" lives 49 | * root: "../../", 50 | * 51 | * // where to put the JS bundle asset in debug mode 52 | * jsBundleDirDebug: "$buildDir/intermediates/assets/debug", 53 | * 54 | * // where to put the JS bundle asset in release mode 55 | * jsBundleDirRelease: "$buildDir/intermediates/assets/release", 56 | * 57 | * // where to put drawable resources / React Native assets, e.g. the ones you use via 58 | * // require('./image.png')), in debug mode 59 | * resourcesDirDebug: "$buildDir/intermediates/res/merged/debug", 60 | * 61 | * // where to put drawable resources / React Native assets, e.g. the ones you use via 62 | * // require('./image.png')), in release mode 63 | * resourcesDirRelease: "$buildDir/intermediates/res/merged/release", 64 | * 65 | * // by default the gradle tasks are skipped if none of the JS files or assets change; this means 66 | * // that we don't look at files in android/ or ios/ to determine whether the tasks are up to 67 | * // date; if you have any other folders that you want to ignore for performance reasons (gradle 68 | * // indexes the entire tree), add them here. Alternatively, if you have JS files in android/ 69 | * // for example, you might want to remove it from here. 70 | * inputExcludes: ["android/**", "ios/**"], 71 | * 72 | * // override which node gets called and with what additional arguments 73 | * nodeExecutableAndArgs: ["node"], 74 | * 75 | * // supply additional arguments to the packager 76 | * extraPackagerArgs: [] 77 | * ] 78 | */ 79 | 80 | project.ext.react = [ 81 | enableHermes: false, // clean and rebuild if changing 82 | ] 83 | 84 | apply from: "../../node_modules/react-native/react.gradle" 85 | 86 | /** 87 | * Set this to true to create two separate APKs instead of one: 88 | * - An APK that only works on ARM devices 89 | * - An APK that only works on x86 devices 90 | * The advantage is the size of the APK is reduced by about 4MB. 91 | * Upload all the APKs to the Play Store and people will download 92 | * the correct one based on the CPU architecture of their device. 93 | */ 94 | def enableSeparateBuildPerCPUArchitecture = false 95 | 96 | /** 97 | * Run Proguard to shrink the Java bytecode in release builds. 98 | */ 99 | def enableProguardInReleaseBuilds = false 100 | 101 | /** 102 | * The preferred build flavor of JavaScriptCore. 103 | * 104 | * For example, to use the international variant, you can use: 105 | * `def jscFlavor = 'org.webkit:android-jsc-intl:+'` 106 | * 107 | * The international variant includes ICU i18n library and necessary data 108 | * allowing to use e.g. `Date.toLocaleString` and `String.localeCompare` that 109 | * give correct results when using with locales other than en-US. Note that 110 | * this variant is about 6MiB larger per architecture than default. 111 | */ 112 | def jscFlavor = 'org.webkit:android-jsc:+' 113 | 114 | /** 115 | * Whether to enable the Hermes VM. 116 | * 117 | * This should be set on project.ext.react and mirrored here. If it is not set 118 | * on project.ext.react, JavaScript will not be compiled to Hermes Bytecode 119 | * and the benefits of using Hermes will therefore be sharply reduced. 120 | */ 121 | def enableHermes = project.ext.react.get("enableHermes", false); 122 | 123 | android { 124 | compileSdkVersion rootProject.ext.compileSdkVersion 125 | 126 | compileOptions { 127 | sourceCompatibility JavaVersion.VERSION_1_8 128 | targetCompatibility JavaVersion.VERSION_1_8 129 | } 130 | 131 | defaultConfig { 132 | applicationId "com.basic" 133 | minSdkVersion rootProject.ext.minSdkVersion 134 | targetSdkVersion rootProject.ext.targetSdkVersion 135 | versionCode 1 136 | versionName "1.0" 137 | } 138 | splits { 139 | abi { 140 | reset() 141 | enable enableSeparateBuildPerCPUArchitecture 142 | universalApk false // If true, also generate a universal APK 143 | include "armeabi-v7a", "x86", "arm64-v8a", "x86_64" 144 | } 145 | } 146 | signingConfigs { 147 | debug { 148 | storeFile file('debug.keystore') 149 | storePassword 'android' 150 | keyAlias 'androiddebugkey' 151 | keyPassword 'android' 152 | } 153 | } 154 | buildTypes { 155 | debug { 156 | signingConfig signingConfigs.debug 157 | } 158 | release { 159 | // Caution! In production, you need to generate your own keystore file. 160 | // see https://reactnative.dev/docs/signed-apk-android. 161 | signingConfig signingConfigs.debug 162 | minifyEnabled enableProguardInReleaseBuilds 163 | proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro" 164 | } 165 | } 166 | 167 | // applicationVariants are e.g. debug, release 168 | applicationVariants.all { variant -> 169 | variant.outputs.each { output -> 170 | // For each separate APK per architecture, set a unique version code as described here: 171 | // https://developer.android.com/studio/build/configure-apk-splits.html 172 | def versionCodes = ["armeabi-v7a": 1, "x86": 2, "arm64-v8a": 3, "x86_64": 4] 173 | def abi = output.getFilter(OutputFile.ABI) 174 | if (abi != null) { // null for the universal-debug, universal-release variants 175 | output.versionCodeOverride = 176 | versionCodes.get(abi) * 1048576 + defaultConfig.versionCode 177 | } 178 | 179 | } 180 | } 181 | } 182 | 183 | dependencies { 184 | implementation fileTree(dir: "libs", include: ["*.jar"]) 185 | //noinspection GradleDynamicVersion 186 | implementation "com.facebook.react:react-native:+" // From node_modules 187 | 188 | implementation "androidx.swiperefreshlayout:swiperefreshlayout:1.0.0" 189 | 190 | debugImplementation("com.facebook.flipper:flipper:${FLIPPER_VERSION}") { 191 | exclude group:'com.facebook.fbjni' 192 | } 193 | 194 | debugImplementation("com.facebook.flipper:flipper-network-plugin:${FLIPPER_VERSION}") { 195 | exclude group:'com.facebook.flipper' 196 | exclude group:'com.squareup.okhttp3', module:'okhttp' 197 | } 198 | 199 | debugImplementation("com.facebook.flipper:flipper-fresco-plugin:${FLIPPER_VERSION}") { 200 | exclude group:'com.facebook.flipper' 201 | } 202 | 203 | if (enableHermes) { 204 | def hermesPath = "../../node_modules/hermes-engine/android/"; 205 | debugImplementation files(hermesPath + "hermes-debug.aar") 206 | releaseImplementation files(hermesPath + "hermes-release.aar") 207 | } else { 208 | implementation jscFlavor 209 | } 210 | } 211 | 212 | // Run this once to be able to run the application with BUCK 213 | // puts all compile dependencies into folder libs for BUCK to use 214 | task copyDownloadableDepsToLibs(type: Copy) { 215 | from configurations.compile 216 | into 'libs' 217 | } 218 | 219 | apply from: file("../../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesAppBuildGradle(project) 220 | -------------------------------------------------------------------------------- /example/Basic/android/app/build_defs.bzl: -------------------------------------------------------------------------------- 1 | """Helper definitions to glob .aar and .jar targets""" 2 | 3 | def create_aar_targets(aarfiles): 4 | for aarfile in aarfiles: 5 | name = "aars__" + aarfile[aarfile.rindex("/") + 1:aarfile.rindex(".aar")] 6 | lib_deps.append(":" + name) 7 | android_prebuilt_aar( 8 | name = name, 9 | aar = aarfile, 10 | ) 11 | 12 | def create_jar_targets(jarfiles): 13 | for jarfile in jarfiles: 14 | name = "jars__" + jarfile[jarfile.rindex("/") + 1:jarfile.rindex(".jar")] 15 | lib_deps.append(":" + name) 16 | prebuilt_jar( 17 | name = name, 18 | binary_jar = jarfile, 19 | ) 20 | -------------------------------------------------------------------------------- /example/Basic/android/app/debug.keystore: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/WhatAKitty/react-native-fetch-mock/0ca63a89a344543b1d8f39689dfca9575dc0ddef/example/Basic/android/app/debug.keystore -------------------------------------------------------------------------------- /example/Basic/android/app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in /usr/local/Cellar/android-sdk/24.3.3/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | -------------------------------------------------------------------------------- /example/Basic/android/app/src/debug/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /example/Basic/android/app/src/debug/java/com/basic/ReactNativeFlipper.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) Facebook, Inc. and its affiliates. 3 | * 4 | *

This source code is licensed under the MIT license found in the LICENSE file in the root 5 | * directory of this source tree. 6 | */ 7 | package com.basic; 8 | 9 | import android.content.Context; 10 | import com.facebook.flipper.android.AndroidFlipperClient; 11 | import com.facebook.flipper.android.utils.FlipperUtils; 12 | import com.facebook.flipper.core.FlipperClient; 13 | import com.facebook.flipper.plugins.crashreporter.CrashReporterPlugin; 14 | import com.facebook.flipper.plugins.databases.DatabasesFlipperPlugin; 15 | import com.facebook.flipper.plugins.fresco.FrescoFlipperPlugin; 16 | import com.facebook.flipper.plugins.inspector.DescriptorMapping; 17 | import com.facebook.flipper.plugins.inspector.InspectorFlipperPlugin; 18 | import com.facebook.flipper.plugins.network.FlipperOkhttpInterceptor; 19 | import com.facebook.flipper.plugins.network.NetworkFlipperPlugin; 20 | import com.facebook.flipper.plugins.react.ReactFlipperPlugin; 21 | import com.facebook.flipper.plugins.sharedpreferences.SharedPreferencesFlipperPlugin; 22 | import com.facebook.react.ReactInstanceManager; 23 | import com.facebook.react.bridge.ReactContext; 24 | import com.facebook.react.modules.network.NetworkingModule; 25 | import okhttp3.OkHttpClient; 26 | 27 | public class ReactNativeFlipper { 28 | public static void initializeFlipper(Context context, ReactInstanceManager reactInstanceManager) { 29 | if (FlipperUtils.shouldEnableFlipper(context)) { 30 | final FlipperClient client = AndroidFlipperClient.getInstance(context); 31 | 32 | client.addPlugin(new InspectorFlipperPlugin(context, DescriptorMapping.withDefaults())); 33 | client.addPlugin(new ReactFlipperPlugin()); 34 | client.addPlugin(new DatabasesFlipperPlugin(context)); 35 | client.addPlugin(new SharedPreferencesFlipperPlugin(context)); 36 | client.addPlugin(CrashReporterPlugin.getInstance()); 37 | 38 | NetworkFlipperPlugin networkFlipperPlugin = new NetworkFlipperPlugin(); 39 | NetworkingModule.setCustomClientBuilder( 40 | new NetworkingModule.CustomClientBuilder() { 41 | @Override 42 | public void apply(OkHttpClient.Builder builder) { 43 | builder.addNetworkInterceptor(new FlipperOkhttpInterceptor(networkFlipperPlugin)); 44 | } 45 | }); 46 | client.addPlugin(networkFlipperPlugin); 47 | client.start(); 48 | 49 | // Fresco Plugin needs to ensure that ImagePipelineFactory is initialized 50 | // Hence we run if after all native modules have been initialized 51 | ReactContext reactContext = reactInstanceManager.getCurrentReactContext(); 52 | if (reactContext == null) { 53 | reactInstanceManager.addReactInstanceEventListener( 54 | new ReactInstanceManager.ReactInstanceEventListener() { 55 | @Override 56 | public void onReactContextInitialized(ReactContext reactContext) { 57 | reactInstanceManager.removeReactInstanceEventListener(this); 58 | reactContext.runOnNativeModulesQueueThread( 59 | new Runnable() { 60 | @Override 61 | public void run() { 62 | client.addPlugin(new FrescoFlipperPlugin()); 63 | } 64 | }); 65 | } 66 | }); 67 | } else { 68 | client.addPlugin(new FrescoFlipperPlugin()); 69 | } 70 | } 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /example/Basic/android/app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 3 | 4 | 5 | 6 | 13 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /example/Basic/android/app/src/main/java/com/basic/MainActivity.java: -------------------------------------------------------------------------------- 1 | package com.basic; 2 | 3 | import com.facebook.react.ReactActivity; 4 | 5 | public class MainActivity extends ReactActivity { 6 | 7 | /** 8 | * Returns the name of the main component registered from JavaScript. This is used to schedule 9 | * rendering of the component. 10 | */ 11 | @Override 12 | protected String getMainComponentName() { 13 | return "Basic"; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /example/Basic/android/app/src/main/java/com/basic/MainApplication.java: -------------------------------------------------------------------------------- 1 | package com.basic; 2 | 3 | import android.app.Application; 4 | import android.content.Context; 5 | import com.facebook.react.PackageList; 6 | import com.facebook.react.ReactApplication; 7 | import com.facebook.react.ReactInstanceManager; 8 | import com.facebook.react.ReactNativeHost; 9 | import com.facebook.react.ReactPackage; 10 | import com.facebook.soloader.SoLoader; 11 | import java.lang.reflect.InvocationTargetException; 12 | import java.util.List; 13 | 14 | public class MainApplication extends Application implements ReactApplication { 15 | 16 | private final ReactNativeHost mReactNativeHost = 17 | new ReactNativeHost(this) { 18 | @Override 19 | public boolean getUseDeveloperSupport() { 20 | return BuildConfig.DEBUG; 21 | } 22 | 23 | @Override 24 | protected List getPackages() { 25 | @SuppressWarnings("UnnecessaryLocalVariable") 26 | List packages = new PackageList(this).getPackages(); 27 | // Packages that cannot be autolinked yet can be added manually here, for example: 28 | // packages.add(new MyReactNativePackage()); 29 | return packages; 30 | } 31 | 32 | @Override 33 | protected String getJSMainModuleName() { 34 | return "index"; 35 | } 36 | }; 37 | 38 | @Override 39 | public ReactNativeHost getReactNativeHost() { 40 | return mReactNativeHost; 41 | } 42 | 43 | @Override 44 | public void onCreate() { 45 | super.onCreate(); 46 | SoLoader.init(this, /* native exopackage */ false); 47 | initializeFlipper(this, getReactNativeHost().getReactInstanceManager()); 48 | } 49 | 50 | /** 51 | * Loads Flipper in React Native templates. Call this in the onCreate method with something like 52 | * initializeFlipper(this, getReactNativeHost().getReactInstanceManager()); 53 | * 54 | * @param context 55 | * @param reactInstanceManager 56 | */ 57 | private static void initializeFlipper( 58 | Context context, ReactInstanceManager reactInstanceManager) { 59 | if (BuildConfig.DEBUG) { 60 | try { 61 | /* 62 | We use reflection here to pick up the class that initializes Flipper, 63 | since Flipper library is not available in release mode 64 | */ 65 | Class aClass = Class.forName("com.basic.ReactNativeFlipper"); 66 | aClass 67 | .getMethod("initializeFlipper", Context.class, ReactInstanceManager.class) 68 | .invoke(null, context, reactInstanceManager); 69 | } catch (ClassNotFoundException e) { 70 | e.printStackTrace(); 71 | } catch (NoSuchMethodException e) { 72 | e.printStackTrace(); 73 | } catch (IllegalAccessException e) { 74 | e.printStackTrace(); 75 | } catch (InvocationTargetException e) { 76 | e.printStackTrace(); 77 | } 78 | } 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /example/Basic/android/app/src/main/res/mipmap-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/WhatAKitty/react-native-fetch-mock/0ca63a89a344543b1d8f39689dfca9575dc0ddef/example/Basic/android/app/src/main/res/mipmap-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /example/Basic/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/WhatAKitty/react-native-fetch-mock/0ca63a89a344543b1d8f39689dfca9575dc0ddef/example/Basic/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /example/Basic/android/app/src/main/res/mipmap-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/WhatAKitty/react-native-fetch-mock/0ca63a89a344543b1d8f39689dfca9575dc0ddef/example/Basic/android/app/src/main/res/mipmap-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /example/Basic/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/WhatAKitty/react-native-fetch-mock/0ca63a89a344543b1d8f39689dfca9575dc0ddef/example/Basic/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /example/Basic/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/WhatAKitty/react-native-fetch-mock/0ca63a89a344543b1d8f39689dfca9575dc0ddef/example/Basic/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /example/Basic/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/WhatAKitty/react-native-fetch-mock/0ca63a89a344543b1d8f39689dfca9575dc0ddef/example/Basic/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /example/Basic/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/WhatAKitty/react-native-fetch-mock/0ca63a89a344543b1d8f39689dfca9575dc0ddef/example/Basic/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /example/Basic/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/WhatAKitty/react-native-fetch-mock/0ca63a89a344543b1d8f39689dfca9575dc0ddef/example/Basic/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /example/Basic/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/WhatAKitty/react-native-fetch-mock/0ca63a89a344543b1d8f39689dfca9575dc0ddef/example/Basic/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /example/Basic/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/WhatAKitty/react-native-fetch-mock/0ca63a89a344543b1d8f39689dfca9575dc0ddef/example/Basic/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /example/Basic/android/app/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | Basic 3 | 4 | -------------------------------------------------------------------------------- /example/Basic/android/app/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /example/Basic/android/build.gradle: -------------------------------------------------------------------------------- 1 | // Top-level build file where you can add configuration options common to all sub-projects/modules. 2 | 3 | buildscript { 4 | ext { 5 | buildToolsVersion = "29.0.2" 6 | minSdkVersion = 16 7 | compileSdkVersion = 29 8 | targetSdkVersion = 29 9 | } 10 | repositories { 11 | google() 12 | jcenter() 13 | } 14 | dependencies { 15 | classpath("com.android.tools.build:gradle:3.5.3") 16 | // NOTE: Do not place your application dependencies here; they belong 17 | // in the individual module build.gradle files 18 | } 19 | } 20 | 21 | allprojects { 22 | repositories { 23 | mavenLocal() 24 | maven { 25 | // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm 26 | url("$rootDir/../node_modules/react-native/android") 27 | } 28 | maven { 29 | // Android JSC is installed from npm 30 | url("$rootDir/../node_modules/jsc-android/dist") 31 | } 32 | 33 | google() 34 | jcenter() 35 | maven { url 'https://www.jitpack.io' } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /example/Basic/android/gradle.properties: -------------------------------------------------------------------------------- 1 | # Project-wide Gradle settings. 2 | 3 | # IDE (e.g. Android Studio) users: 4 | # Gradle settings configured through the IDE *will override* 5 | # any settings specified in this file. 6 | 7 | # For more details on how to configure your build environment visit 8 | # http://www.gradle.org/docs/current/userguide/build_environment.html 9 | 10 | # Specifies the JVM arguments used for the daemon process. 11 | # The setting is particularly useful for tweaking memory settings. 12 | # Default value: -Xmx10248m -XX:MaxPermSize=256m 13 | # org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 14 | 15 | # When configured, Gradle will run in incubating parallel mode. 16 | # This option should only be used with decoupled projects. More details, visit 17 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 18 | # org.gradle.parallel=true 19 | 20 | # AndroidX package structure to make it clearer which packages are bundled with the 21 | # Android operating system, and which are packaged with your app's APK 22 | # https://developer.android.com/topic/libraries/support-library/androidx-rn 23 | android.useAndroidX=true 24 | # Automatically convert third-party libraries to use AndroidX 25 | android.enableJetifier=true 26 | 27 | # Version of flipper SDK to use with React Native 28 | FLIPPER_VERSION=0.54.0 29 | -------------------------------------------------------------------------------- /example/Basic/android/gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/WhatAKitty/react-native-fetch-mock/0ca63a89a344543b1d8f39689dfca9575dc0ddef/example/Basic/android/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /example/Basic/android/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-6.2-all.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /example/Basic/android/gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | # 4 | # Copyright 2015 the original author or authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | ## 21 | ## Gradle start up script for UN*X 22 | ## 23 | ############################################################################## 24 | 25 | # Attempt to set APP_HOME 26 | # Resolve links: $0 may be a link 27 | PRG="$0" 28 | # Need this for relative symlinks. 29 | while [ -h "$PRG" ] ; do 30 | ls=`ls -ld "$PRG"` 31 | link=`expr "$ls" : '.*-> \(.*\)$'` 32 | if expr "$link" : '/.*' > /dev/null; then 33 | PRG="$link" 34 | else 35 | PRG=`dirname "$PRG"`"/$link" 36 | fi 37 | done 38 | SAVED="`pwd`" 39 | cd "`dirname \"$PRG\"`/" >/dev/null 40 | APP_HOME="`pwd -P`" 41 | cd "$SAVED" >/dev/null 42 | 43 | APP_NAME="Gradle" 44 | APP_BASE_NAME=`basename "$0"` 45 | 46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 48 | 49 | # Use the maximum available, or set MAX_FD != -1 to use that value. 50 | MAX_FD="maximum" 51 | 52 | warn () { 53 | echo "$*" 54 | } 55 | 56 | die () { 57 | echo 58 | echo "$*" 59 | echo 60 | exit 1 61 | } 62 | 63 | # OS specific support (must be 'true' or 'false'). 64 | cygwin=false 65 | msys=false 66 | darwin=false 67 | nonstop=false 68 | case "`uname`" in 69 | CYGWIN* ) 70 | cygwin=true 71 | ;; 72 | Darwin* ) 73 | darwin=true 74 | ;; 75 | MINGW* ) 76 | msys=true 77 | ;; 78 | NONSTOP* ) 79 | nonstop=true 80 | ;; 81 | esac 82 | 83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 84 | 85 | # Determine the Java command to use to start the JVM. 86 | if [ -n "$JAVA_HOME" ] ; then 87 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 88 | # IBM's JDK on AIX uses strange locations for the executables 89 | JAVACMD="$JAVA_HOME/jre/sh/java" 90 | else 91 | JAVACMD="$JAVA_HOME/bin/java" 92 | fi 93 | if [ ! -x "$JAVACMD" ] ; then 94 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 95 | 96 | Please set the JAVA_HOME variable in your environment to match the 97 | location of your Java installation." 98 | fi 99 | else 100 | JAVACMD="java" 101 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 102 | 103 | Please set the JAVA_HOME variable in your environment to match the 104 | location of your Java installation." 105 | fi 106 | 107 | # Increase the maximum file descriptors if we can. 108 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 109 | MAX_FD_LIMIT=`ulimit -H -n` 110 | if [ $? -eq 0 ] ; then 111 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 112 | MAX_FD="$MAX_FD_LIMIT" 113 | fi 114 | ulimit -n $MAX_FD 115 | if [ $? -ne 0 ] ; then 116 | warn "Could not set maximum file descriptor limit: $MAX_FD" 117 | fi 118 | else 119 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 120 | fi 121 | fi 122 | 123 | # For Darwin, add options to specify how the application appears in the dock 124 | if $darwin; then 125 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 126 | fi 127 | 128 | # For Cygwin or MSYS, switch paths to Windows format before running java 129 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then 130 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 131 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 132 | JAVACMD=`cygpath --unix "$JAVACMD"` 133 | 134 | # We build the pattern for arguments to be converted via cygpath 135 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 136 | SEP="" 137 | for dir in $ROOTDIRSRAW ; do 138 | ROOTDIRS="$ROOTDIRS$SEP$dir" 139 | SEP="|" 140 | done 141 | OURCYGPATTERN="(^($ROOTDIRS))" 142 | # Add a user-defined pattern to the cygpath arguments 143 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 144 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 145 | fi 146 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 147 | i=0 148 | for arg in "$@" ; do 149 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 150 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 151 | 152 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 153 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 154 | else 155 | eval `echo args$i`="\"$arg\"" 156 | fi 157 | i=`expr $i + 1` 158 | done 159 | case $i in 160 | 0) set -- ;; 161 | 1) set -- "$args0" ;; 162 | 2) set -- "$args0" "$args1" ;; 163 | 3) set -- "$args0" "$args1" "$args2" ;; 164 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;; 165 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 166 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 167 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 168 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 169 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 170 | esac 171 | fi 172 | 173 | # Escape application args 174 | save () { 175 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 176 | echo " " 177 | } 178 | APP_ARGS=`save "$@"` 179 | 180 | # Collect all arguments for the java command, following the shell quoting and substitution rules 181 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 182 | 183 | exec "$JAVACMD" "$@" 184 | -------------------------------------------------------------------------------- /example/Basic/android/gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto init 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto init 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :init 68 | @rem Get command-line arguments, handling Windows variants 69 | 70 | if not "%OS%" == "Windows_NT" goto win9xME_args 71 | 72 | :win9xME_args 73 | @rem Slurp the command line arguments. 74 | set CMD_LINE_ARGS= 75 | set _SKIP=2 76 | 77 | :win9xME_args_slurp 78 | if "x%~1" == "x" goto execute 79 | 80 | set CMD_LINE_ARGS=%* 81 | 82 | :execute 83 | @rem Setup the command line 84 | 85 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 86 | 87 | @rem Execute Gradle 88 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 89 | 90 | :end 91 | @rem End local scope for the variables with windows NT shell 92 | if "%ERRORLEVEL%"=="0" goto mainEnd 93 | 94 | :fail 95 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 96 | rem the _cmd.exe /c_ return code! 97 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 98 | exit /b 1 99 | 100 | :mainEnd 101 | if "%OS%"=="Windows_NT" endlocal 102 | 103 | :omega 104 | -------------------------------------------------------------------------------- /example/Basic/android/settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'Basic' 2 | apply from: file("../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesSettingsGradle(settings) 3 | include ':app' 4 | -------------------------------------------------------------------------------- /example/Basic/app.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "Basic", 3 | "displayName": "Basic" 4 | } -------------------------------------------------------------------------------- /example/Basic/babel.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | presets: ['module:metro-react-native-babel-preset'], 3 | }; 4 | -------------------------------------------------------------------------------- /example/Basic/index.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @format 3 | */ 4 | 5 | import {AppRegistry} from 'react-native'; 6 | import App from './src/app'; 7 | import {name as appName} from './app.json'; 8 | 9 | AppRegistry.registerComponent(appName, () => App); 10 | -------------------------------------------------------------------------------- /example/Basic/ios/Basic-tvOS/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | en 7 | CFBundleExecutable 8 | $(EXECUTABLE_NAME) 9 | CFBundleIdentifier 10 | $(PRODUCT_BUNDLE_IDENTIFIER) 11 | CFBundleInfoDictionaryVersion 12 | 6.0 13 | CFBundleName 14 | $(PRODUCT_NAME) 15 | CFBundlePackageType 16 | APPL 17 | CFBundleShortVersionString 18 | 1.0 19 | CFBundleSignature 20 | ???? 21 | CFBundleVersion 22 | 1 23 | LSRequiresIPhoneOS 24 | 25 | NSAppTransportSecurity 26 | 27 | NSExceptionDomains 28 | 29 | localhost 30 | 31 | NSExceptionAllowsInsecureHTTPLoads 32 | 33 | 34 | 35 | 36 | NSLocationWhenInUseUsageDescription 37 | 38 | UILaunchStoryboardName 39 | LaunchScreen 40 | UIRequiredDeviceCapabilities 41 | 42 | armv7 43 | 44 | UISupportedInterfaceOrientations 45 | 46 | UIInterfaceOrientationPortrait 47 | UIInterfaceOrientationLandscapeLeft 48 | UIInterfaceOrientationLandscapeRight 49 | 50 | UIViewControllerBasedStatusBarAppearance 51 | 52 | 53 | 54 | -------------------------------------------------------------------------------- /example/Basic/ios/Basic-tvOSTests/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | en 7 | CFBundleExecutable 8 | $(EXECUTABLE_NAME) 9 | CFBundleIdentifier 10 | $(PRODUCT_BUNDLE_IDENTIFIER) 11 | CFBundleInfoDictionaryVersion 12 | 6.0 13 | CFBundleName 14 | $(PRODUCT_NAME) 15 | CFBundlePackageType 16 | BNDL 17 | CFBundleShortVersionString 18 | 1.0 19 | CFBundleSignature 20 | ???? 21 | CFBundleVersion 22 | 1 23 | 24 | 25 | -------------------------------------------------------------------------------- /example/Basic/ios/Basic.xcodeproj/xcshareddata/xcschemes/Basic-tvOS.xcscheme: -------------------------------------------------------------------------------- 1 | 2 | 5 | 8 | 9 | 15 | 21 | 22 | 23 | 24 | 25 | 30 | 31 | 33 | 39 | 40 | 41 | 42 | 43 | 53 | 55 | 61 | 62 | 63 | 64 | 70 | 72 | 78 | 79 | 80 | 81 | 83 | 84 | 87 | 88 | 89 | -------------------------------------------------------------------------------- /example/Basic/ios/Basic.xcodeproj/xcshareddata/xcschemes/Basic.xcscheme: -------------------------------------------------------------------------------- 1 | 2 | 5 | 8 | 9 | 15 | 21 | 22 | 23 | 24 | 25 | 30 | 31 | 33 | 39 | 40 | 41 | 42 | 43 | 53 | 55 | 61 | 62 | 63 | 64 | 70 | 72 | 78 | 79 | 80 | 81 | 83 | 84 | 87 | 88 | 89 | -------------------------------------------------------------------------------- /example/Basic/ios/Basic.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /example/Basic/ios/Basic/AppDelegate.h: -------------------------------------------------------------------------------- 1 | #import 2 | #import 3 | 4 | @interface AppDelegate : UIResponder 5 | 6 | @property (nonatomic, strong) UIWindow *window; 7 | 8 | @end 9 | -------------------------------------------------------------------------------- /example/Basic/ios/Basic/AppDelegate.m: -------------------------------------------------------------------------------- 1 | #import "AppDelegate.h" 2 | 3 | #import 4 | #import 5 | #import 6 | 7 | #ifdef FB_SONARKIT_ENABLED 8 | #import 9 | #import 10 | #import 11 | #import 12 | #import 13 | #import 14 | 15 | static void InitializeFlipper(UIApplication *application) { 16 | FlipperClient *client = [FlipperClient sharedClient]; 17 | SKDescriptorMapper *layoutDescriptorMapper = [[SKDescriptorMapper alloc] initWithDefaults]; 18 | [client addPlugin:[[FlipperKitLayoutPlugin alloc] initWithRootNode:application withDescriptorMapper:layoutDescriptorMapper]]; 19 | [client addPlugin:[[FKUserDefaultsPlugin alloc] initWithSuiteName:nil]]; 20 | [client addPlugin:[FlipperKitReactPlugin new]]; 21 | [client addPlugin:[[FlipperKitNetworkPlugin alloc] initWithNetworkAdapter:[SKIOSNetworkAdapter new]]]; 22 | [client start]; 23 | } 24 | #endif 25 | 26 | @implementation AppDelegate 27 | 28 | - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 29 | { 30 | #ifdef FB_SONARKIT_ENABLED 31 | InitializeFlipper(application); 32 | #endif 33 | 34 | RCTBridge *bridge = [[RCTBridge alloc] initWithDelegate:self launchOptions:launchOptions]; 35 | RCTRootView *rootView = [[RCTRootView alloc] initWithBridge:bridge 36 | moduleName:@"Basic" 37 | initialProperties:nil]; 38 | 39 | rootView.backgroundColor = [[UIColor alloc] initWithRed:1.0f green:1.0f blue:1.0f alpha:1]; 40 | 41 | self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds]; 42 | UIViewController *rootViewController = [UIViewController new]; 43 | rootViewController.view = rootView; 44 | self.window.rootViewController = rootViewController; 45 | [self.window makeKeyAndVisible]; 46 | return YES; 47 | } 48 | 49 | - (NSURL *)sourceURLForBridge:(RCTBridge *)bridge 50 | { 51 | #if DEBUG 52 | return [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index" fallbackResource:nil]; 53 | #else 54 | return [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"]; 55 | #endif 56 | } 57 | 58 | @end 59 | -------------------------------------------------------------------------------- /example/Basic/ios/Basic/Images.xcassets/AppIcon.appiconset/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "images" : [ 3 | { 4 | "idiom" : "iphone", 5 | "size" : "29x29", 6 | "scale" : "2x" 7 | }, 8 | { 9 | "idiom" : "iphone", 10 | "size" : "29x29", 11 | "scale" : "3x" 12 | }, 13 | { 14 | "idiom" : "iphone", 15 | "size" : "40x40", 16 | "scale" : "2x" 17 | }, 18 | { 19 | "idiom" : "iphone", 20 | "size" : "40x40", 21 | "scale" : "3x" 22 | }, 23 | { 24 | "idiom" : "iphone", 25 | "size" : "60x60", 26 | "scale" : "2x" 27 | }, 28 | { 29 | "idiom" : "iphone", 30 | "size" : "60x60", 31 | "scale" : "3x" 32 | } 33 | ], 34 | "info" : { 35 | "version" : 1, 36 | "author" : "xcode" 37 | } 38 | } -------------------------------------------------------------------------------- /example/Basic/ios/Basic/Images.xcassets/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "info" : { 3 | "version" : 1, 4 | "author" : "xcode" 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /example/Basic/ios/Basic/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | en 7 | CFBundleDisplayName 8 | Basic 9 | CFBundleExecutable 10 | $(EXECUTABLE_NAME) 11 | CFBundleIdentifier 12 | $(PRODUCT_BUNDLE_IDENTIFIER) 13 | CFBundleInfoDictionaryVersion 14 | 6.0 15 | CFBundleName 16 | $(PRODUCT_NAME) 17 | CFBundlePackageType 18 | APPL 19 | CFBundleShortVersionString 20 | 1.0 21 | CFBundleSignature 22 | ???? 23 | CFBundleVersion 24 | 1 25 | LSRequiresIPhoneOS 26 | 27 | NSAppTransportSecurity 28 | 29 | NSAllowsArbitraryLoads 30 | 31 | NSExceptionDomains 32 | 33 | localhost 34 | 35 | NSExceptionAllowsInsecureHTTPLoads 36 | 37 | 38 | 39 | 40 | NSLocationWhenInUseUsageDescription 41 | 42 | UILaunchStoryboardName 43 | LaunchScreen 44 | UIRequiredDeviceCapabilities 45 | 46 | armv7 47 | 48 | UISupportedInterfaceOrientations 49 | 50 | UIInterfaceOrientationPortrait 51 | UIInterfaceOrientationLandscapeLeft 52 | UIInterfaceOrientationLandscapeRight 53 | 54 | UIViewControllerBasedStatusBarAppearance 55 | 56 | 57 | 58 | -------------------------------------------------------------------------------- /example/Basic/ios/Basic/LaunchScreen.storyboard: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 25 | 31 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | -------------------------------------------------------------------------------- /example/Basic/ios/Basic/main.m: -------------------------------------------------------------------------------- 1 | #import 2 | 3 | #import "AppDelegate.h" 4 | 5 | int main(int argc, char * argv[]) { 6 | @autoreleasepool { 7 | return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class])); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /example/Basic/ios/BasicTests/BasicTests.m: -------------------------------------------------------------------------------- 1 | #import 2 | #import 3 | 4 | #import 5 | #import 6 | 7 | #define TIMEOUT_SECONDS 600 8 | #define TEXT_TO_LOOK_FOR @"Welcome to React" 9 | 10 | @interface BasicTests : XCTestCase 11 | 12 | @end 13 | 14 | @implementation BasicTests 15 | 16 | - (BOOL)findSubviewInView:(UIView *)view matching:(BOOL(^)(UIView *view))test 17 | { 18 | if (test(view)) { 19 | return YES; 20 | } 21 | for (UIView *subview in [view subviews]) { 22 | if ([self findSubviewInView:subview matching:test]) { 23 | return YES; 24 | } 25 | } 26 | return NO; 27 | } 28 | 29 | - (void)testRendersWelcomeScreen 30 | { 31 | UIViewController *vc = [[[RCTSharedApplication() delegate] window] rootViewController]; 32 | NSDate *date = [NSDate dateWithTimeIntervalSinceNow:TIMEOUT_SECONDS]; 33 | BOOL foundElement = NO; 34 | 35 | __block NSString *redboxError = nil; 36 | #ifdef DEBUG 37 | RCTSetLogFunction(^(RCTLogLevel level, RCTLogSource source, NSString *fileName, NSNumber *lineNumber, NSString *message) { 38 | if (level >= RCTLogLevelError) { 39 | redboxError = message; 40 | } 41 | }); 42 | #endif 43 | 44 | while ([date timeIntervalSinceNow] > 0 && !foundElement && !redboxError) { 45 | [[NSRunLoop mainRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.1]]; 46 | [[NSRunLoop mainRunLoop] runMode:NSRunLoopCommonModes beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.1]]; 47 | 48 | foundElement = [self findSubviewInView:vc.view matching:^BOOL(UIView *view) { 49 | if ([view.accessibilityLabel isEqualToString:TEXT_TO_LOOK_FOR]) { 50 | return YES; 51 | } 52 | return NO; 53 | }]; 54 | } 55 | 56 | #ifdef DEBUG 57 | RCTSetLogFunction(RCTDefaultLogFunction); 58 | #endif 59 | 60 | XCTAssertNil(redboxError, @"RedBox error: %@", redboxError); 61 | XCTAssertTrue(foundElement, @"Couldn't find element with text '%@' in %d seconds", TEXT_TO_LOOK_FOR, TIMEOUT_SECONDS); 62 | } 63 | 64 | 65 | @end 66 | -------------------------------------------------------------------------------- /example/Basic/ios/BasicTests/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | en 7 | CFBundleExecutable 8 | $(EXECUTABLE_NAME) 9 | CFBundleIdentifier 10 | $(PRODUCT_BUNDLE_IDENTIFIER) 11 | CFBundleInfoDictionaryVersion 12 | 6.0 13 | CFBundleName 14 | $(PRODUCT_NAME) 15 | CFBundlePackageType 16 | BNDL 17 | CFBundleShortVersionString 18 | 1.0 19 | CFBundleSignature 20 | ???? 21 | CFBundleVersion 22 | 1 23 | 24 | 25 | -------------------------------------------------------------------------------- /example/Basic/ios/Podfile: -------------------------------------------------------------------------------- 1 | require_relative '../node_modules/react-native/scripts/react_native_pods' 2 | require_relative '../node_modules/@react-native-community/cli-platform-ios/native_modules' 3 | 4 | platform :ios, '10.0' 5 | 6 | target 'Basic' do 7 | config = use_native_modules! 8 | 9 | use_react_native!(:path => config["reactNativePath"]) 10 | 11 | target 'BasicTests' do 12 | inherit! :complete 13 | # Pods for testing 14 | end 15 | 16 | # Enables Flipper. 17 | # 18 | # Note that if you have use_frameworks! enabled, Flipper will not work and 19 | # you should disable these next few lines. 20 | use_flipper! 21 | post_install do |installer| 22 | flipper_post_install(installer) 23 | end 24 | end 25 | 26 | target 'Basic-tvOS' do 27 | # Pods for Basic-tvOS 28 | 29 | target 'Basic-tvOSTests' do 30 | inherit! :search_paths 31 | # Pods for testing 32 | end 33 | end 34 | -------------------------------------------------------------------------------- /example/Basic/ios/Podfile.lock: -------------------------------------------------------------------------------- 1 | PODS: 2 | - boost-for-react-native (1.63.0) 3 | - CocoaAsyncSocket (7.6.4) 4 | - CocoaLibEvent (1.0.0) 5 | - DoubleConversion (1.1.6) 6 | - FBLazyVector (0.63.3) 7 | - FBReactNativeSpec (0.63.3): 8 | - Folly (= 2020.01.13.00) 9 | - RCTRequired (= 0.63.3) 10 | - RCTTypeSafety (= 0.63.3) 11 | - React-Core (= 0.63.3) 12 | - React-jsi (= 0.63.3) 13 | - ReactCommon/turbomodule/core (= 0.63.3) 14 | - Flipper (0.54.0): 15 | - Flipper-Folly (~> 2.2) 16 | - Flipper-RSocket (~> 1.1) 17 | - Flipper-DoubleConversion (1.1.7) 18 | - Flipper-Folly (2.2.0): 19 | - boost-for-react-native 20 | - CocoaLibEvent (~> 1.0) 21 | - Flipper-DoubleConversion 22 | - Flipper-Glog 23 | - OpenSSL-Universal (= 1.0.2.19) 24 | - Flipper-Glog (0.3.6) 25 | - Flipper-PeerTalk (0.0.4) 26 | - Flipper-RSocket (1.1.0): 27 | - Flipper-Folly (~> 2.2) 28 | - FlipperKit (0.54.0): 29 | - FlipperKit/Core (= 0.54.0) 30 | - FlipperKit/Core (0.54.0): 31 | - Flipper (~> 0.54.0) 32 | - FlipperKit/CppBridge 33 | - FlipperKit/FBCxxFollyDynamicConvert 34 | - FlipperKit/FBDefines 35 | - FlipperKit/FKPortForwarding 36 | - FlipperKit/CppBridge (0.54.0): 37 | - Flipper (~> 0.54.0) 38 | - FlipperKit/FBCxxFollyDynamicConvert (0.54.0): 39 | - Flipper-Folly (~> 2.2) 40 | - FlipperKit/FBDefines (0.54.0) 41 | - FlipperKit/FKPortForwarding (0.54.0): 42 | - CocoaAsyncSocket (~> 7.6) 43 | - Flipper-PeerTalk (~> 0.0.4) 44 | - FlipperKit/FlipperKitHighlightOverlay (0.54.0) 45 | - FlipperKit/FlipperKitLayoutPlugin (0.54.0): 46 | - FlipperKit/Core 47 | - FlipperKit/FlipperKitHighlightOverlay 48 | - FlipperKit/FlipperKitLayoutTextSearchable 49 | - YogaKit (~> 1.18) 50 | - FlipperKit/FlipperKitLayoutTextSearchable (0.54.0) 51 | - FlipperKit/FlipperKitNetworkPlugin (0.54.0): 52 | - FlipperKit/Core 53 | - FlipperKit/FlipperKitReactPlugin (0.54.0): 54 | - FlipperKit/Core 55 | - FlipperKit/FlipperKitUserDefaultsPlugin (0.54.0): 56 | - FlipperKit/Core 57 | - FlipperKit/SKIOSNetworkPlugin (0.54.0): 58 | - FlipperKit/Core 59 | - FlipperKit/FlipperKitNetworkPlugin 60 | - Folly (2020.01.13.00): 61 | - boost-for-react-native 62 | - DoubleConversion 63 | - Folly/Default (= 2020.01.13.00) 64 | - glog 65 | - Folly/Default (2020.01.13.00): 66 | - boost-for-react-native 67 | - DoubleConversion 68 | - glog 69 | - glog (0.3.5) 70 | - OpenSSL-Universal (1.0.2.19): 71 | - OpenSSL-Universal/Static (= 1.0.2.19) 72 | - OpenSSL-Universal/Static (1.0.2.19) 73 | - RCTRequired (0.63.3) 74 | - RCTTypeSafety (0.63.3): 75 | - FBLazyVector (= 0.63.3) 76 | - Folly (= 2020.01.13.00) 77 | - RCTRequired (= 0.63.3) 78 | - React-Core (= 0.63.3) 79 | - React (0.63.3): 80 | - React-Core (= 0.63.3) 81 | - React-Core/DevSupport (= 0.63.3) 82 | - React-Core/RCTWebSocket (= 0.63.3) 83 | - React-RCTActionSheet (= 0.63.3) 84 | - React-RCTAnimation (= 0.63.3) 85 | - React-RCTBlob (= 0.63.3) 86 | - React-RCTImage (= 0.63.3) 87 | - React-RCTLinking (= 0.63.3) 88 | - React-RCTNetwork (= 0.63.3) 89 | - React-RCTSettings (= 0.63.3) 90 | - React-RCTText (= 0.63.3) 91 | - React-RCTVibration (= 0.63.3) 92 | - React-callinvoker (0.63.3) 93 | - React-Core (0.63.3): 94 | - Folly (= 2020.01.13.00) 95 | - glog 96 | - React-Core/Default (= 0.63.3) 97 | - React-cxxreact (= 0.63.3) 98 | - React-jsi (= 0.63.3) 99 | - React-jsiexecutor (= 0.63.3) 100 | - Yoga 101 | - React-Core/CoreModulesHeaders (0.63.3): 102 | - Folly (= 2020.01.13.00) 103 | - glog 104 | - React-Core/Default 105 | - React-cxxreact (= 0.63.3) 106 | - React-jsi (= 0.63.3) 107 | - React-jsiexecutor (= 0.63.3) 108 | - Yoga 109 | - React-Core/Default (0.63.3): 110 | - Folly (= 2020.01.13.00) 111 | - glog 112 | - React-cxxreact (= 0.63.3) 113 | - React-jsi (= 0.63.3) 114 | - React-jsiexecutor (= 0.63.3) 115 | - Yoga 116 | - React-Core/DevSupport (0.63.3): 117 | - Folly (= 2020.01.13.00) 118 | - glog 119 | - React-Core/Default (= 0.63.3) 120 | - React-Core/RCTWebSocket (= 0.63.3) 121 | - React-cxxreact (= 0.63.3) 122 | - React-jsi (= 0.63.3) 123 | - React-jsiexecutor (= 0.63.3) 124 | - React-jsinspector (= 0.63.3) 125 | - Yoga 126 | - React-Core/RCTActionSheetHeaders (0.63.3): 127 | - Folly (= 2020.01.13.00) 128 | - glog 129 | - React-Core/Default 130 | - React-cxxreact (= 0.63.3) 131 | - React-jsi (= 0.63.3) 132 | - React-jsiexecutor (= 0.63.3) 133 | - Yoga 134 | - React-Core/RCTAnimationHeaders (0.63.3): 135 | - Folly (= 2020.01.13.00) 136 | - glog 137 | - React-Core/Default 138 | - React-cxxreact (= 0.63.3) 139 | - React-jsi (= 0.63.3) 140 | - React-jsiexecutor (= 0.63.3) 141 | - Yoga 142 | - React-Core/RCTBlobHeaders (0.63.3): 143 | - Folly (= 2020.01.13.00) 144 | - glog 145 | - React-Core/Default 146 | - React-cxxreact (= 0.63.3) 147 | - React-jsi (= 0.63.3) 148 | - React-jsiexecutor (= 0.63.3) 149 | - Yoga 150 | - React-Core/RCTImageHeaders (0.63.3): 151 | - Folly (= 2020.01.13.00) 152 | - glog 153 | - React-Core/Default 154 | - React-cxxreact (= 0.63.3) 155 | - React-jsi (= 0.63.3) 156 | - React-jsiexecutor (= 0.63.3) 157 | - Yoga 158 | - React-Core/RCTLinkingHeaders (0.63.3): 159 | - Folly (= 2020.01.13.00) 160 | - glog 161 | - React-Core/Default 162 | - React-cxxreact (= 0.63.3) 163 | - React-jsi (= 0.63.3) 164 | - React-jsiexecutor (= 0.63.3) 165 | - Yoga 166 | - React-Core/RCTNetworkHeaders (0.63.3): 167 | - Folly (= 2020.01.13.00) 168 | - glog 169 | - React-Core/Default 170 | - React-cxxreact (= 0.63.3) 171 | - React-jsi (= 0.63.3) 172 | - React-jsiexecutor (= 0.63.3) 173 | - Yoga 174 | - React-Core/RCTSettingsHeaders (0.63.3): 175 | - Folly (= 2020.01.13.00) 176 | - glog 177 | - React-Core/Default 178 | - React-cxxreact (= 0.63.3) 179 | - React-jsi (= 0.63.3) 180 | - React-jsiexecutor (= 0.63.3) 181 | - Yoga 182 | - React-Core/RCTTextHeaders (0.63.3): 183 | - Folly (= 2020.01.13.00) 184 | - glog 185 | - React-Core/Default 186 | - React-cxxreact (= 0.63.3) 187 | - React-jsi (= 0.63.3) 188 | - React-jsiexecutor (= 0.63.3) 189 | - Yoga 190 | - React-Core/RCTVibrationHeaders (0.63.3): 191 | - Folly (= 2020.01.13.00) 192 | - glog 193 | - React-Core/Default 194 | - React-cxxreact (= 0.63.3) 195 | - React-jsi (= 0.63.3) 196 | - React-jsiexecutor (= 0.63.3) 197 | - Yoga 198 | - React-Core/RCTWebSocket (0.63.3): 199 | - Folly (= 2020.01.13.00) 200 | - glog 201 | - React-Core/Default (= 0.63.3) 202 | - React-cxxreact (= 0.63.3) 203 | - React-jsi (= 0.63.3) 204 | - React-jsiexecutor (= 0.63.3) 205 | - Yoga 206 | - React-CoreModules (0.63.3): 207 | - FBReactNativeSpec (= 0.63.3) 208 | - Folly (= 2020.01.13.00) 209 | - RCTTypeSafety (= 0.63.3) 210 | - React-Core/CoreModulesHeaders (= 0.63.3) 211 | - React-jsi (= 0.63.3) 212 | - React-RCTImage (= 0.63.3) 213 | - ReactCommon/turbomodule/core (= 0.63.3) 214 | - React-cxxreact (0.63.3): 215 | - boost-for-react-native (= 1.63.0) 216 | - DoubleConversion 217 | - Folly (= 2020.01.13.00) 218 | - glog 219 | - React-callinvoker (= 0.63.3) 220 | - React-jsinspector (= 0.63.3) 221 | - React-jsi (0.63.3): 222 | - boost-for-react-native (= 1.63.0) 223 | - DoubleConversion 224 | - Folly (= 2020.01.13.00) 225 | - glog 226 | - React-jsi/Default (= 0.63.3) 227 | - React-jsi/Default (0.63.3): 228 | - boost-for-react-native (= 1.63.0) 229 | - DoubleConversion 230 | - Folly (= 2020.01.13.00) 231 | - glog 232 | - React-jsiexecutor (0.63.3): 233 | - DoubleConversion 234 | - Folly (= 2020.01.13.00) 235 | - glog 236 | - React-cxxreact (= 0.63.3) 237 | - React-jsi (= 0.63.3) 238 | - React-jsinspector (0.63.3) 239 | - React-RCTActionSheet (0.63.3): 240 | - React-Core/RCTActionSheetHeaders (= 0.63.3) 241 | - React-RCTAnimation (0.63.3): 242 | - FBReactNativeSpec (= 0.63.3) 243 | - Folly (= 2020.01.13.00) 244 | - RCTTypeSafety (= 0.63.3) 245 | - React-Core/RCTAnimationHeaders (= 0.63.3) 246 | - React-jsi (= 0.63.3) 247 | - ReactCommon/turbomodule/core (= 0.63.3) 248 | - React-RCTBlob (0.63.3): 249 | - FBReactNativeSpec (= 0.63.3) 250 | - Folly (= 2020.01.13.00) 251 | - React-Core/RCTBlobHeaders (= 0.63.3) 252 | - React-Core/RCTWebSocket (= 0.63.3) 253 | - React-jsi (= 0.63.3) 254 | - React-RCTNetwork (= 0.63.3) 255 | - ReactCommon/turbomodule/core (= 0.63.3) 256 | - React-RCTImage (0.63.3): 257 | - FBReactNativeSpec (= 0.63.3) 258 | - Folly (= 2020.01.13.00) 259 | - RCTTypeSafety (= 0.63.3) 260 | - React-Core/RCTImageHeaders (= 0.63.3) 261 | - React-jsi (= 0.63.3) 262 | - React-RCTNetwork (= 0.63.3) 263 | - ReactCommon/turbomodule/core (= 0.63.3) 264 | - React-RCTLinking (0.63.3): 265 | - FBReactNativeSpec (= 0.63.3) 266 | - React-Core/RCTLinkingHeaders (= 0.63.3) 267 | - React-jsi (= 0.63.3) 268 | - ReactCommon/turbomodule/core (= 0.63.3) 269 | - React-RCTNetwork (0.63.3): 270 | - FBReactNativeSpec (= 0.63.3) 271 | - Folly (= 2020.01.13.00) 272 | - RCTTypeSafety (= 0.63.3) 273 | - React-Core/RCTNetworkHeaders (= 0.63.3) 274 | - React-jsi (= 0.63.3) 275 | - ReactCommon/turbomodule/core (= 0.63.3) 276 | - React-RCTSettings (0.63.3): 277 | - FBReactNativeSpec (= 0.63.3) 278 | - Folly (= 2020.01.13.00) 279 | - RCTTypeSafety (= 0.63.3) 280 | - React-Core/RCTSettingsHeaders (= 0.63.3) 281 | - React-jsi (= 0.63.3) 282 | - ReactCommon/turbomodule/core (= 0.63.3) 283 | - React-RCTText (0.63.3): 284 | - React-Core/RCTTextHeaders (= 0.63.3) 285 | - React-RCTVibration (0.63.3): 286 | - FBReactNativeSpec (= 0.63.3) 287 | - Folly (= 2020.01.13.00) 288 | - React-Core/RCTVibrationHeaders (= 0.63.3) 289 | - React-jsi (= 0.63.3) 290 | - ReactCommon/turbomodule/core (= 0.63.3) 291 | - ReactCommon/turbomodule/core (0.63.3): 292 | - DoubleConversion 293 | - Folly (= 2020.01.13.00) 294 | - glog 295 | - React-callinvoker (= 0.63.3) 296 | - React-Core (= 0.63.3) 297 | - React-cxxreact (= 0.63.3) 298 | - React-jsi (= 0.63.3) 299 | - Yoga (1.14.0) 300 | - YogaKit (1.18.1): 301 | - Yoga (~> 1.14) 302 | 303 | DEPENDENCIES: 304 | - DoubleConversion (from `../node_modules/react-native/third-party-podspecs/DoubleConversion.podspec`) 305 | - FBLazyVector (from `../node_modules/react-native/Libraries/FBLazyVector`) 306 | - FBReactNativeSpec (from `../node_modules/react-native/Libraries/FBReactNativeSpec`) 307 | - Flipper (~> 0.54.0) 308 | - Flipper-DoubleConversion (= 1.1.7) 309 | - Flipper-Folly (~> 2.2) 310 | - Flipper-Glog (= 0.3.6) 311 | - Flipper-PeerTalk (~> 0.0.4) 312 | - Flipper-RSocket (~> 1.1) 313 | - FlipperKit (~> 0.54.0) 314 | - FlipperKit/Core (~> 0.54.0) 315 | - FlipperKit/CppBridge (~> 0.54.0) 316 | - FlipperKit/FBCxxFollyDynamicConvert (~> 0.54.0) 317 | - FlipperKit/FBDefines (~> 0.54.0) 318 | - FlipperKit/FKPortForwarding (~> 0.54.0) 319 | - FlipperKit/FlipperKitHighlightOverlay (~> 0.54.0) 320 | - FlipperKit/FlipperKitLayoutPlugin (~> 0.54.0) 321 | - FlipperKit/FlipperKitLayoutTextSearchable (~> 0.54.0) 322 | - FlipperKit/FlipperKitNetworkPlugin (~> 0.54.0) 323 | - FlipperKit/FlipperKitReactPlugin (~> 0.54.0) 324 | - FlipperKit/FlipperKitUserDefaultsPlugin (~> 0.54.0) 325 | - FlipperKit/SKIOSNetworkPlugin (~> 0.54.0) 326 | - Folly (from `../node_modules/react-native/third-party-podspecs/Folly.podspec`) 327 | - glog (from `../node_modules/react-native/third-party-podspecs/glog.podspec`) 328 | - RCTRequired (from `../node_modules/react-native/Libraries/RCTRequired`) 329 | - RCTTypeSafety (from `../node_modules/react-native/Libraries/TypeSafety`) 330 | - React (from `../node_modules/react-native/`) 331 | - React-callinvoker (from `../node_modules/react-native/ReactCommon/callinvoker`) 332 | - React-Core (from `../node_modules/react-native/`) 333 | - React-Core/DevSupport (from `../node_modules/react-native/`) 334 | - React-Core/RCTWebSocket (from `../node_modules/react-native/`) 335 | - React-CoreModules (from `../node_modules/react-native/React/CoreModules`) 336 | - React-cxxreact (from `../node_modules/react-native/ReactCommon/cxxreact`) 337 | - React-jsi (from `../node_modules/react-native/ReactCommon/jsi`) 338 | - React-jsiexecutor (from `../node_modules/react-native/ReactCommon/jsiexecutor`) 339 | - React-jsinspector (from `../node_modules/react-native/ReactCommon/jsinspector`) 340 | - React-RCTActionSheet (from `../node_modules/react-native/Libraries/ActionSheetIOS`) 341 | - React-RCTAnimation (from `../node_modules/react-native/Libraries/NativeAnimation`) 342 | - React-RCTBlob (from `../node_modules/react-native/Libraries/Blob`) 343 | - React-RCTImage (from `../node_modules/react-native/Libraries/Image`) 344 | - React-RCTLinking (from `../node_modules/react-native/Libraries/LinkingIOS`) 345 | - React-RCTNetwork (from `../node_modules/react-native/Libraries/Network`) 346 | - React-RCTSettings (from `../node_modules/react-native/Libraries/Settings`) 347 | - React-RCTText (from `../node_modules/react-native/Libraries/Text`) 348 | - React-RCTVibration (from `../node_modules/react-native/Libraries/Vibration`) 349 | - ReactCommon/turbomodule/core (from `../node_modules/react-native/ReactCommon`) 350 | - Yoga (from `../node_modules/react-native/ReactCommon/yoga`) 351 | 352 | SPEC REPOS: 353 | trunk: 354 | - boost-for-react-native 355 | - CocoaAsyncSocket 356 | - CocoaLibEvent 357 | - Flipper 358 | - Flipper-DoubleConversion 359 | - Flipper-Folly 360 | - Flipper-Glog 361 | - Flipper-PeerTalk 362 | - Flipper-RSocket 363 | - FlipperKit 364 | - OpenSSL-Universal 365 | - YogaKit 366 | 367 | EXTERNAL SOURCES: 368 | DoubleConversion: 369 | :podspec: "../node_modules/react-native/third-party-podspecs/DoubleConversion.podspec" 370 | FBLazyVector: 371 | :path: "../node_modules/react-native/Libraries/FBLazyVector" 372 | FBReactNativeSpec: 373 | :path: "../node_modules/react-native/Libraries/FBReactNativeSpec" 374 | Folly: 375 | :podspec: "../node_modules/react-native/third-party-podspecs/Folly.podspec" 376 | glog: 377 | :podspec: "../node_modules/react-native/third-party-podspecs/glog.podspec" 378 | RCTRequired: 379 | :path: "../node_modules/react-native/Libraries/RCTRequired" 380 | RCTTypeSafety: 381 | :path: "../node_modules/react-native/Libraries/TypeSafety" 382 | React: 383 | :path: "../node_modules/react-native/" 384 | React-callinvoker: 385 | :path: "../node_modules/react-native/ReactCommon/callinvoker" 386 | React-Core: 387 | :path: "../node_modules/react-native/" 388 | React-CoreModules: 389 | :path: "../node_modules/react-native/React/CoreModules" 390 | React-cxxreact: 391 | :path: "../node_modules/react-native/ReactCommon/cxxreact" 392 | React-jsi: 393 | :path: "../node_modules/react-native/ReactCommon/jsi" 394 | React-jsiexecutor: 395 | :path: "../node_modules/react-native/ReactCommon/jsiexecutor" 396 | React-jsinspector: 397 | :path: "../node_modules/react-native/ReactCommon/jsinspector" 398 | React-RCTActionSheet: 399 | :path: "../node_modules/react-native/Libraries/ActionSheetIOS" 400 | React-RCTAnimation: 401 | :path: "../node_modules/react-native/Libraries/NativeAnimation" 402 | React-RCTBlob: 403 | :path: "../node_modules/react-native/Libraries/Blob" 404 | React-RCTImage: 405 | :path: "../node_modules/react-native/Libraries/Image" 406 | React-RCTLinking: 407 | :path: "../node_modules/react-native/Libraries/LinkingIOS" 408 | React-RCTNetwork: 409 | :path: "../node_modules/react-native/Libraries/Network" 410 | React-RCTSettings: 411 | :path: "../node_modules/react-native/Libraries/Settings" 412 | React-RCTText: 413 | :path: "../node_modules/react-native/Libraries/Text" 414 | React-RCTVibration: 415 | :path: "../node_modules/react-native/Libraries/Vibration" 416 | ReactCommon: 417 | :path: "../node_modules/react-native/ReactCommon" 418 | Yoga: 419 | :path: "../node_modules/react-native/ReactCommon/yoga" 420 | 421 | SPEC CHECKSUMS: 422 | boost-for-react-native: 39c7adb57c4e60d6c5479dd8623128eb5b3f0f2c 423 | CocoaAsyncSocket: 694058e7c0ed05a9e217d1b3c7ded962f4180845 424 | CocoaLibEvent: 2fab71b8bd46dd33ddb959f7928ec5909f838e3f 425 | DoubleConversion: cde416483dac037923206447da6e1454df403714 426 | FBLazyVector: 878b59e31113e289e275165efbe4b54fa614d43d 427 | FBReactNativeSpec: 7da9338acfb98d4ef9e5536805a0704572d33c2f 428 | Flipper: be611d4b742d8c87fbae2ca5f44603a02539e365 429 | Flipper-DoubleConversion: 38631e41ef4f9b12861c67d17cb5518d06badc41 430 | Flipper-Folly: c12092ea368353b58e992843a990a3225d4533c3 431 | Flipper-Glog: 1dfd6abf1e922806c52ceb8701a3599a79a200a6 432 | Flipper-PeerTalk: 116d8f857dc6ef55c7a5a75ea3ceaafe878aadc9 433 | Flipper-RSocket: 64e7431a55835eb953b0bf984ef3b90ae9fdddd7 434 | FlipperKit: ab353d41aea8aae2ea6daaf813e67496642f3d7d 435 | Folly: b73c3869541e86821df3c387eb0af5f65addfab4 436 | glog: 40a13f7840415b9a77023fbcae0f1e6f43192af3 437 | OpenSSL-Universal: 8b48cc0d10c1b2923617dfe5c178aa9ed2689355 438 | RCTRequired: 48884c74035a0b5b76dbb7a998bd93bcfc5f2047 439 | RCTTypeSafety: edf4b618033c2f1c5b7bc3d90d8e085ed95ba2ab 440 | React: f36e90f3ceb976546e97df3403e37d226f79d0e3 441 | React-callinvoker: 18874f621eb96625df7a24a7dc8d6e07391affcd 442 | React-Core: ac3d816b8e3493970153f4aaf0cff18af0bb95e6 443 | React-CoreModules: 4016d3a4e518bcfc4f5a51252b5a05692ca6f0e1 444 | React-cxxreact: ffc9129013b87cb36cf3f30a86695a3c397b0f99 445 | React-jsi: df07aa95b39c5be3e41199921509bfa929ed2b9d 446 | React-jsiexecutor: b56c03e61c0dd5f5801255f2160a815f4a53d451 447 | React-jsinspector: 8e68ffbfe23880d3ee9bafa8be2777f60b25cbe2 448 | React-RCTActionSheet: 53ea72699698b0b47a6421cb1c8b4ab215a774aa 449 | React-RCTAnimation: 1befece0b5183c22ae01b966f5583f42e69a83c2 450 | React-RCTBlob: 0b284339cbe4b15705a05e2313a51c6d8b51fa40 451 | React-RCTImage: d1756599ebd4dc2cb19d1682fe67c6b976658387 452 | React-RCTLinking: 9af0a51c6d6a4dd1674daadafffc6d03033a6d18 453 | React-RCTNetwork: 332c83929cc5eae0b3bbca4add1d668e1fc18bda 454 | React-RCTSettings: d6953772cfd55f2c68ad72b7ef29efc7ec49f773 455 | React-RCTText: 65a6de06a7389098ce24340d1d3556015c38f746 456 | React-RCTVibration: 8e9fb25724a0805107fc1acc9075e26f814df454 457 | ReactCommon: 4167844018c9ed375cc01a843e9ee564399e53c3 458 | Yoga: 7d13633d129fd179e01b8953d38d47be90db185a 459 | YogaKit: f782866e155069a2cca2517aafea43200b01fd5a 460 | 461 | PODFILE CHECKSUM: fa1dccbea5e22ef9748d270c4c7ccfd179a326ff 462 | 463 | COCOAPODS: 1.9.3 464 | -------------------------------------------------------------------------------- /example/Basic/metro.config.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Metro configuration for React Native 3 | * https://github.com/facebook/react-native 4 | * 5 | * @format 6 | */ 7 | 8 | module.exports = { 9 | transformer: { 10 | getTransformOptions: async () => ({ 11 | transform: { 12 | experimentalImportSupport: false, 13 | inlineRequires: false, 14 | }, 15 | }), 16 | }, 17 | }; 18 | -------------------------------------------------------------------------------- /example/Basic/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "Basic", 3 | "version": "0.0.1", 4 | "private": true, 5 | "scripts": { 6 | "android": "react-native run-android", 7 | "ios": "react-native run-ios", 8 | "start": "react-native start", 9 | "test": "jest", 10 | "lint": "eslint ." 11 | }, 12 | "dependencies": { 13 | "react": "16.13.1", 14 | "react-native": "0.63.3", 15 | "react-native-fetch-mock": "^0.8.0" 16 | }, 17 | "devDependencies": { 18 | "@babel/core": "^7.12.3", 19 | "@babel/runtime": "^7.12.1", 20 | "@react-native-community/eslint-config": "^2.0.0", 21 | "babel-jest": "^26.6.1", 22 | "eslint": "^7.12.0", 23 | "jest": "^26.6.1", 24 | "metro-react-native-babel-preset": "^0.63.0", 25 | "react-test-renderer": "16.13.1" 26 | }, 27 | "jest": { 28 | "preset": "react-native" 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /example/Basic/src/app.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from 'react'; 2 | import { View, Text } from 'react-native'; 3 | import FetchMock from 'react-native-fetch-mock'; 4 | 5 | const fetch = new FetchMock(require('../__mocks__')).fetch; 6 | class App extends Component { 7 | constructor(props) { 8 | super(props); 9 | 10 | this.state = { 11 | data: [], 12 | }; 13 | 14 | this.getData = this.getData.bind(this); 15 | } 16 | 17 | componentDidMount() { 18 | this.getData(); 19 | } 20 | 21 | async getData() { 22 | const { data, err } = await fetch('/api/users') 23 | .then(res => { 24 | if (res.status !== 200) { 25 | throw new Error('fetch failed'); 26 | } 27 | return res.json(); 28 | }) 29 | .then(data => ({ data })) 30 | .catch(err => ({ err })); 31 | 32 | if (err) { 33 | return false; 34 | } 35 | 36 | this.setState({ 37 | data, 38 | }); 39 | } 40 | 41 | render() { 42 | return ( 43 | 44 | { 45 | this.state.data.map((item, index) => { 46 | return {item.name} 47 | }) 48 | } 49 | 50 | ); 51 | } 52 | } 53 | 54 | export default App; 55 | -------------------------------------------------------------------------------- /example/WithMockJs/.buckconfig: -------------------------------------------------------------------------------- 1 | 2 | [android] 3 | target = Google Inc.:Google APIs:23 4 | 5 | [maven_repositories] 6 | central = https://repo1.maven.org/maven2 7 | -------------------------------------------------------------------------------- /example/WithMockJs/.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | root: true, 3 | extends: '@react-native-community', 4 | }; 5 | -------------------------------------------------------------------------------- /example/WithMockJs/.flowconfig: -------------------------------------------------------------------------------- 1 | [ignore] 2 | ; We fork some components by platform 3 | .*/*[.]android.js 4 | 5 | ; Ignore "BUCK" generated dirs 6 | /\.buckd/ 7 | 8 | ; Ignore polyfills 9 | node_modules/react-native/Libraries/polyfills/.* 10 | 11 | ; These should not be required directly 12 | ; require from fbjs/lib instead: require('fbjs/lib/warning') 13 | node_modules/warning/.* 14 | 15 | ; Flow doesn't support platforms 16 | .*/Libraries/Utilities/LoadingView.js 17 | 18 | [untyped] 19 | .*/node_modules/@react-native-community/cli/.*/.* 20 | 21 | [include] 22 | 23 | [libs] 24 | node_modules/react-native/interface.js 25 | node_modules/react-native/flow/ 26 | 27 | [options] 28 | emoji=true 29 | 30 | esproposal.optional_chaining=enable 31 | esproposal.nullish_coalescing=enable 32 | 33 | module.file_ext=.js 34 | module.file_ext=.json 35 | module.file_ext=.ios.js 36 | 37 | munge_underscores=true 38 | 39 | module.name_mapper='^react-native/\(.*\)$' -> '/node_modules/react-native/\1' 40 | module.name_mapper='^@?[./a-zA-Z0-9$_-]+\.\(bmp\|gif\|jpg\|jpeg\|png\|psd\|svg\|webp\|m4v\|mov\|mp4\|mpeg\|mpg\|webm\|aac\|aiff\|caf\|m4a\|mp3\|wav\|html\|pdf\)$' -> '/node_modules/react-native/Libraries/Image/RelativeImageStub' 41 | 42 | suppress_type=$FlowIssue 43 | suppress_type=$FlowFixMe 44 | suppress_type=$FlowFixMeProps 45 | suppress_type=$FlowFixMeState 46 | 47 | suppress_comment=\\(.\\|\n\\)*\\$FlowFixMe\\($\\|[^(]\\|(\\(\\)? *\\(site=[a-z,_]*react_native\\(_ios\\)?_\\(oss\\|fb\\)[a-z,_]*\\)?)\\) 48 | suppress_comment=\\(.\\|\n\\)*\\$FlowIssue\\((\\(\\)? *\\(site=[a-z,_]*react_native\\(_ios\\)?_\\(oss\\|fb\\)[a-z,_]*\\)?)\\)?:? #[0-9]+ 49 | suppress_comment=\\(.\\|\n\\)*\\$FlowExpectedError 50 | 51 | [lints] 52 | sketchy-null-number=warn 53 | sketchy-null-mixed=warn 54 | sketchy-number=warn 55 | untyped-type-import=warn 56 | nonstrict-import=warn 57 | deprecated-type=warn 58 | unsafe-getters-setters=warn 59 | unnecessary-invariant=warn 60 | signature-verification-failure=warn 61 | deprecated-utility=error 62 | 63 | [strict] 64 | deprecated-type 65 | nonstrict-import 66 | sketchy-null 67 | unclear-type 68 | unsafe-getters-setters 69 | untyped-import 70 | untyped-type-import 71 | 72 | [version] 73 | ^0.122.0 74 | -------------------------------------------------------------------------------- /example/WithMockJs/.gitattributes: -------------------------------------------------------------------------------- 1 | *.pbxproj -text 2 | -------------------------------------------------------------------------------- /example/WithMockJs/.gitignore: -------------------------------------------------------------------------------- 1 | # OSX 2 | # 3 | .DS_Store 4 | 5 | # Xcode 6 | # 7 | build/ 8 | *.pbxuser 9 | !default.pbxuser 10 | *.mode1v3 11 | !default.mode1v3 12 | *.mode2v3 13 | !default.mode2v3 14 | *.perspectivev3 15 | !default.perspectivev3 16 | xcuserdata 17 | *.xccheckout 18 | *.moved-aside 19 | DerivedData 20 | *.hmap 21 | *.ipa 22 | *.xcuserstate 23 | 24 | # Android/IntelliJ 25 | # 26 | build/ 27 | .idea 28 | .gradle 29 | local.properties 30 | *.iml 31 | 32 | # node.js 33 | # 34 | node_modules/ 35 | npm-debug.log 36 | yarn-error.log 37 | 38 | # BUCK 39 | buck-out/ 40 | \.buckd/ 41 | *.keystore 42 | !debug.keystore 43 | 44 | # fastlane 45 | # 46 | # It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the 47 | # screenshots whenever they are needed. 48 | # For more information about the recommended setup visit: 49 | # https://docs.fastlane.tools/best-practices/source-control/ 50 | 51 | */fastlane/report.xml 52 | */fastlane/Preview.html 53 | */fastlane/screenshots 54 | 55 | # Bundle artifact 56 | *.jsbundle 57 | 58 | # CocoaPods 59 | /ios/Pods/ 60 | -------------------------------------------------------------------------------- /example/WithMockJs/.prettierrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | bracketSpacing: false, 3 | jsxBracketSameLine: true, 4 | singleQuote: true, 5 | trailingComma: 'all', 6 | }; 7 | -------------------------------------------------------------------------------- /example/WithMockJs/.watchmanconfig: -------------------------------------------------------------------------------- 1 | {} -------------------------------------------------------------------------------- /example/WithMockJs/__mocks__/index.js: -------------------------------------------------------------------------------- 1 | import { Mock } from 'react-native-fetch-mock'; 2 | 3 | export default { 4 | '/api/users/mockjs': ({ params }) => { 5 | const all = Mock.mock({ 6 | 'list|1-10': [{ 7 | 'id|+1': 1, 8 | 'name': '@first @last', 9 | 'age|18-54': 1, 10 | }] 11 | }).list; 12 | let filtered; 13 | if ('undefined' !== typeof params) { 14 | filtered = all.filter(item => { 15 | let result = true; 16 | const keys = Object.keys(params); 17 | keys.forEach(key => { 18 | const param = params[key]; 19 | 20 | if (item[key] && item[key] !== param) { 21 | result = false; 22 | } 23 | }); 24 | 25 | return result; 26 | }); 27 | } else { 28 | filtered = all; 29 | } 30 | return { 31 | status: 200, 32 | data: filtered, 33 | }; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /example/WithMockJs/__tests__/App-test.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @format 3 | */ 4 | 5 | import 'react-native'; 6 | import React from 'react'; 7 | import App from '../App'; 8 | 9 | // Note: test renderer must be required after react-native. 10 | import renderer from 'react-test-renderer'; 11 | 12 | it('renders correctly', () => { 13 | renderer.create(); 14 | }); 15 | -------------------------------------------------------------------------------- /example/WithMockJs/android/app/BUCK: -------------------------------------------------------------------------------- 1 | # To learn about Buck see [Docs](https://buckbuild.com/). 2 | # To run your application with Buck: 3 | # - install Buck 4 | # - `npm start` - to start the packager 5 | # - `cd android` 6 | # - `keytool -genkey -v -keystore keystores/debug.keystore -storepass android -alias androiddebugkey -keypass android -dname "CN=Android Debug,O=Android,C=US"` 7 | # - `./gradlew :app:copyDownloadableDepsToLibs` - make all Gradle compile dependencies available to Buck 8 | # - `buck install -r android/app` - compile, install and run application 9 | # 10 | 11 | load(":build_defs.bzl", "create_aar_targets", "create_jar_targets") 12 | 13 | lib_deps = [] 14 | 15 | create_aar_targets(glob(["libs/*.aar"])) 16 | 17 | create_jar_targets(glob(["libs/*.jar"])) 18 | 19 | android_library( 20 | name = "all-libs", 21 | exported_deps = lib_deps, 22 | ) 23 | 24 | android_library( 25 | name = "app-code", 26 | srcs = glob([ 27 | "src/main/java/**/*.java", 28 | ]), 29 | deps = [ 30 | ":all-libs", 31 | ":build_config", 32 | ":res", 33 | ], 34 | ) 35 | 36 | android_build_config( 37 | name = "build_config", 38 | package = "com.withmockjs", 39 | ) 40 | 41 | android_resource( 42 | name = "res", 43 | package = "com.withmockjs", 44 | res = "src/main/res", 45 | ) 46 | 47 | android_binary( 48 | name = "app", 49 | keystore = "//android/keystores:debug", 50 | manifest = "src/main/AndroidManifest.xml", 51 | package_type = "debug", 52 | deps = [ 53 | ":app-code", 54 | ], 55 | ) 56 | -------------------------------------------------------------------------------- /example/WithMockJs/android/app/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: "com.android.application" 2 | 3 | import com.android.build.OutputFile 4 | 5 | /** 6 | * The react.gradle file registers a task for each build variant (e.g. bundleDebugJsAndAssets 7 | * and bundleReleaseJsAndAssets). 8 | * These basically call `react-native bundle` with the correct arguments during the Android build 9 | * cycle. By default, bundleDebugJsAndAssets is skipped, as in debug/dev mode we prefer to load the 10 | * bundle directly from the development server. Below you can see all the possible configurations 11 | * and their defaults. If you decide to add a configuration block, make sure to add it before the 12 | * `apply from: "../../node_modules/react-native/react.gradle"` line. 13 | * 14 | * project.ext.react = [ 15 | * // the name of the generated asset file containing your JS bundle 16 | * bundleAssetName: "index.android.bundle", 17 | * 18 | * // the entry file for bundle generation. If none specified and 19 | * // "index.android.js" exists, it will be used. Otherwise "index.js" is 20 | * // default. Can be overridden with ENTRY_FILE environment variable. 21 | * entryFile: "index.android.js", 22 | * 23 | * // https://reactnative.dev/docs/performance#enable-the-ram-format 24 | * bundleCommand: "ram-bundle", 25 | * 26 | * // whether to bundle JS and assets in debug mode 27 | * bundleInDebug: false, 28 | * 29 | * // whether to bundle JS and assets in release mode 30 | * bundleInRelease: true, 31 | * 32 | * // whether to bundle JS and assets in another build variant (if configured). 33 | * // See http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Build-Variants 34 | * // The configuration property can be in the following formats 35 | * // 'bundleIn${productFlavor}${buildType}' 36 | * // 'bundleIn${buildType}' 37 | * // bundleInFreeDebug: true, 38 | * // bundleInPaidRelease: true, 39 | * // bundleInBeta: true, 40 | * 41 | * // whether to disable dev mode in custom build variants (by default only disabled in release) 42 | * // for example: to disable dev mode in the staging build type (if configured) 43 | * devDisabledInStaging: true, 44 | * // The configuration property can be in the following formats 45 | * // 'devDisabledIn${productFlavor}${buildType}' 46 | * // 'devDisabledIn${buildType}' 47 | * 48 | * // the root of your project, i.e. where "package.json" lives 49 | * root: "../../", 50 | * 51 | * // where to put the JS bundle asset in debug mode 52 | * jsBundleDirDebug: "$buildDir/intermediates/assets/debug", 53 | * 54 | * // where to put the JS bundle asset in release mode 55 | * jsBundleDirRelease: "$buildDir/intermediates/assets/release", 56 | * 57 | * // where to put drawable resources / React Native assets, e.g. the ones you use via 58 | * // require('./image.png')), in debug mode 59 | * resourcesDirDebug: "$buildDir/intermediates/res/merged/debug", 60 | * 61 | * // where to put drawable resources / React Native assets, e.g. the ones you use via 62 | * // require('./image.png')), in release mode 63 | * resourcesDirRelease: "$buildDir/intermediates/res/merged/release", 64 | * 65 | * // by default the gradle tasks are skipped if none of the JS files or assets change; this means 66 | * // that we don't look at files in android/ or ios/ to determine whether the tasks are up to 67 | * // date; if you have any other folders that you want to ignore for performance reasons (gradle 68 | * // indexes the entire tree), add them here. Alternatively, if you have JS files in android/ 69 | * // for example, you might want to remove it from here. 70 | * inputExcludes: ["android/**", "ios/**"], 71 | * 72 | * // override which node gets called and with what additional arguments 73 | * nodeExecutableAndArgs: ["node"], 74 | * 75 | * // supply additional arguments to the packager 76 | * extraPackagerArgs: [] 77 | * ] 78 | */ 79 | 80 | project.ext.react = [ 81 | enableHermes: false, // clean and rebuild if changing 82 | ] 83 | 84 | apply from: "../../node_modules/react-native/react.gradle" 85 | 86 | /** 87 | * Set this to true to create two separate APKs instead of one: 88 | * - An APK that only works on ARM devices 89 | * - An APK that only works on x86 devices 90 | * The advantage is the size of the APK is reduced by about 4MB. 91 | * Upload all the APKs to the Play Store and people will download 92 | * the correct one based on the CPU architecture of their device. 93 | */ 94 | def enableSeparateBuildPerCPUArchitecture = false 95 | 96 | /** 97 | * Run Proguard to shrink the Java bytecode in release builds. 98 | */ 99 | def enableProguardInReleaseBuilds = false 100 | 101 | /** 102 | * The preferred build flavor of JavaScriptCore. 103 | * 104 | * For example, to use the international variant, you can use: 105 | * `def jscFlavor = 'org.webkit:android-jsc-intl:+'` 106 | * 107 | * The international variant includes ICU i18n library and necessary data 108 | * allowing to use e.g. `Date.toLocaleString` and `String.localeCompare` that 109 | * give correct results when using with locales other than en-US. Note that 110 | * this variant is about 6MiB larger per architecture than default. 111 | */ 112 | def jscFlavor = 'org.webkit:android-jsc:+' 113 | 114 | /** 115 | * Whether to enable the Hermes VM. 116 | * 117 | * This should be set on project.ext.react and mirrored here. If it is not set 118 | * on project.ext.react, JavaScript will not be compiled to Hermes Bytecode 119 | * and the benefits of using Hermes will therefore be sharply reduced. 120 | */ 121 | def enableHermes = project.ext.react.get("enableHermes", false); 122 | 123 | android { 124 | compileSdkVersion rootProject.ext.compileSdkVersion 125 | 126 | compileOptions { 127 | sourceCompatibility JavaVersion.VERSION_1_8 128 | targetCompatibility JavaVersion.VERSION_1_8 129 | } 130 | 131 | defaultConfig { 132 | applicationId "com.withmockjs" 133 | minSdkVersion rootProject.ext.minSdkVersion 134 | targetSdkVersion rootProject.ext.targetSdkVersion 135 | versionCode 1 136 | versionName "1.0" 137 | } 138 | splits { 139 | abi { 140 | reset() 141 | enable enableSeparateBuildPerCPUArchitecture 142 | universalApk false // If true, also generate a universal APK 143 | include "armeabi-v7a", "x86", "arm64-v8a", "x86_64" 144 | } 145 | } 146 | signingConfigs { 147 | debug { 148 | storeFile file('debug.keystore') 149 | storePassword 'android' 150 | keyAlias 'androiddebugkey' 151 | keyPassword 'android' 152 | } 153 | } 154 | buildTypes { 155 | debug { 156 | signingConfig signingConfigs.debug 157 | } 158 | release { 159 | // Caution! In production, you need to generate your own keystore file. 160 | // see https://reactnative.dev/docs/signed-apk-android. 161 | signingConfig signingConfigs.debug 162 | minifyEnabled enableProguardInReleaseBuilds 163 | proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro" 164 | } 165 | } 166 | 167 | // applicationVariants are e.g. debug, release 168 | applicationVariants.all { variant -> 169 | variant.outputs.each { output -> 170 | // For each separate APK per architecture, set a unique version code as described here: 171 | // https://developer.android.com/studio/build/configure-apk-splits.html 172 | def versionCodes = ["armeabi-v7a": 1, "x86": 2, "arm64-v8a": 3, "x86_64": 4] 173 | def abi = output.getFilter(OutputFile.ABI) 174 | if (abi != null) { // null for the universal-debug, universal-release variants 175 | output.versionCodeOverride = 176 | versionCodes.get(abi) * 1048576 + defaultConfig.versionCode 177 | } 178 | 179 | } 180 | } 181 | } 182 | 183 | dependencies { 184 | implementation fileTree(dir: "libs", include: ["*.jar"]) 185 | //noinspection GradleDynamicVersion 186 | implementation "com.facebook.react:react-native:+" // From node_modules 187 | 188 | implementation "androidx.swiperefreshlayout:swiperefreshlayout:1.0.0" 189 | 190 | debugImplementation("com.facebook.flipper:flipper:${FLIPPER_VERSION}") { 191 | exclude group:'com.facebook.fbjni' 192 | } 193 | 194 | debugImplementation("com.facebook.flipper:flipper-network-plugin:${FLIPPER_VERSION}") { 195 | exclude group:'com.facebook.flipper' 196 | exclude group:'com.squareup.okhttp3', module:'okhttp' 197 | } 198 | 199 | debugImplementation("com.facebook.flipper:flipper-fresco-plugin:${FLIPPER_VERSION}") { 200 | exclude group:'com.facebook.flipper' 201 | } 202 | 203 | if (enableHermes) { 204 | def hermesPath = "../../node_modules/hermes-engine/android/"; 205 | debugImplementation files(hermesPath + "hermes-debug.aar") 206 | releaseImplementation files(hermesPath + "hermes-release.aar") 207 | } else { 208 | implementation jscFlavor 209 | } 210 | } 211 | 212 | // Run this once to be able to run the application with BUCK 213 | // puts all compile dependencies into folder libs for BUCK to use 214 | task copyDownloadableDepsToLibs(type: Copy) { 215 | from configurations.compile 216 | into 'libs' 217 | } 218 | 219 | apply from: file("../../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesAppBuildGradle(project) 220 | -------------------------------------------------------------------------------- /example/WithMockJs/android/app/build_defs.bzl: -------------------------------------------------------------------------------- 1 | """Helper definitions to glob .aar and .jar targets""" 2 | 3 | def create_aar_targets(aarfiles): 4 | for aarfile in aarfiles: 5 | name = "aars__" + aarfile[aarfile.rindex("/") + 1:aarfile.rindex(".aar")] 6 | lib_deps.append(":" + name) 7 | android_prebuilt_aar( 8 | name = name, 9 | aar = aarfile, 10 | ) 11 | 12 | def create_jar_targets(jarfiles): 13 | for jarfile in jarfiles: 14 | name = "jars__" + jarfile[jarfile.rindex("/") + 1:jarfile.rindex(".jar")] 15 | lib_deps.append(":" + name) 16 | prebuilt_jar( 17 | name = name, 18 | binary_jar = jarfile, 19 | ) 20 | -------------------------------------------------------------------------------- /example/WithMockJs/android/app/debug.keystore: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/WhatAKitty/react-native-fetch-mock/0ca63a89a344543b1d8f39689dfca9575dc0ddef/example/WithMockJs/android/app/debug.keystore -------------------------------------------------------------------------------- /example/WithMockJs/android/app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in /usr/local/Cellar/android-sdk/24.3.3/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | -------------------------------------------------------------------------------- /example/WithMockJs/android/app/src/debug/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /example/WithMockJs/android/app/src/debug/java/com/withmockjs/ReactNativeFlipper.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) Facebook, Inc. and its affiliates. 3 | * 4 | *

This source code is licensed under the MIT license found in the LICENSE file in the root 5 | * directory of this source tree. 6 | */ 7 | package com.withmockjs; 8 | 9 | import android.content.Context; 10 | import com.facebook.flipper.android.AndroidFlipperClient; 11 | import com.facebook.flipper.android.utils.FlipperUtils; 12 | import com.facebook.flipper.core.FlipperClient; 13 | import com.facebook.flipper.plugins.crashreporter.CrashReporterPlugin; 14 | import com.facebook.flipper.plugins.databases.DatabasesFlipperPlugin; 15 | import com.facebook.flipper.plugins.fresco.FrescoFlipperPlugin; 16 | import com.facebook.flipper.plugins.inspector.DescriptorMapping; 17 | import com.facebook.flipper.plugins.inspector.InspectorFlipperPlugin; 18 | import com.facebook.flipper.plugins.network.FlipperOkhttpInterceptor; 19 | import com.facebook.flipper.plugins.network.NetworkFlipperPlugin; 20 | import com.facebook.flipper.plugins.react.ReactFlipperPlugin; 21 | import com.facebook.flipper.plugins.sharedpreferences.SharedPreferencesFlipperPlugin; 22 | import com.facebook.react.ReactInstanceManager; 23 | import com.facebook.react.bridge.ReactContext; 24 | import com.facebook.react.modules.network.NetworkingModule; 25 | import okhttp3.OkHttpClient; 26 | 27 | public class ReactNativeFlipper { 28 | public static void initializeFlipper(Context context, ReactInstanceManager reactInstanceManager) { 29 | if (FlipperUtils.shouldEnableFlipper(context)) { 30 | final FlipperClient client = AndroidFlipperClient.getInstance(context); 31 | 32 | client.addPlugin(new InspectorFlipperPlugin(context, DescriptorMapping.withDefaults())); 33 | client.addPlugin(new ReactFlipperPlugin()); 34 | client.addPlugin(new DatabasesFlipperPlugin(context)); 35 | client.addPlugin(new SharedPreferencesFlipperPlugin(context)); 36 | client.addPlugin(CrashReporterPlugin.getInstance()); 37 | 38 | NetworkFlipperPlugin networkFlipperPlugin = new NetworkFlipperPlugin(); 39 | NetworkingModule.setCustomClientBuilder( 40 | new NetworkingModule.CustomClientBuilder() { 41 | @Override 42 | public void apply(OkHttpClient.Builder builder) { 43 | builder.addNetworkInterceptor(new FlipperOkhttpInterceptor(networkFlipperPlugin)); 44 | } 45 | }); 46 | client.addPlugin(networkFlipperPlugin); 47 | client.start(); 48 | 49 | // Fresco Plugin needs to ensure that ImagePipelineFactory is initialized 50 | // Hence we run if after all native modules have been initialized 51 | ReactContext reactContext = reactInstanceManager.getCurrentReactContext(); 52 | if (reactContext == null) { 53 | reactInstanceManager.addReactInstanceEventListener( 54 | new ReactInstanceManager.ReactInstanceEventListener() { 55 | @Override 56 | public void onReactContextInitialized(ReactContext reactContext) { 57 | reactInstanceManager.removeReactInstanceEventListener(this); 58 | reactContext.runOnNativeModulesQueueThread( 59 | new Runnable() { 60 | @Override 61 | public void run() { 62 | client.addPlugin(new FrescoFlipperPlugin()); 63 | } 64 | }); 65 | } 66 | }); 67 | } else { 68 | client.addPlugin(new FrescoFlipperPlugin()); 69 | } 70 | } 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /example/WithMockJs/android/app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 3 | 4 | 5 | 6 | 13 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /example/WithMockJs/android/app/src/main/java/com/withmockjs/MainActivity.java: -------------------------------------------------------------------------------- 1 | package com.withmockjs; 2 | 3 | import com.facebook.react.ReactActivity; 4 | 5 | public class MainActivity extends ReactActivity { 6 | 7 | /** 8 | * Returns the name of the main component registered from JavaScript. This is used to schedule 9 | * rendering of the component. 10 | */ 11 | @Override 12 | protected String getMainComponentName() { 13 | return "WithMockJs"; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /example/WithMockJs/android/app/src/main/java/com/withmockjs/MainApplication.java: -------------------------------------------------------------------------------- 1 | package com.withmockjs; 2 | 3 | import android.app.Application; 4 | import android.content.Context; 5 | import com.facebook.react.PackageList; 6 | import com.facebook.react.ReactApplication; 7 | import com.facebook.react.ReactInstanceManager; 8 | import com.facebook.react.ReactNativeHost; 9 | import com.facebook.react.ReactPackage; 10 | import com.facebook.soloader.SoLoader; 11 | import java.lang.reflect.InvocationTargetException; 12 | import java.util.List; 13 | 14 | public class MainApplication extends Application implements ReactApplication { 15 | 16 | private final ReactNativeHost mReactNativeHost = 17 | new ReactNativeHost(this) { 18 | @Override 19 | public boolean getUseDeveloperSupport() { 20 | return BuildConfig.DEBUG; 21 | } 22 | 23 | @Override 24 | protected List getPackages() { 25 | @SuppressWarnings("UnnecessaryLocalVariable") 26 | List packages = new PackageList(this).getPackages(); 27 | // Packages that cannot be autolinked yet can be added manually here, for example: 28 | // packages.add(new MyReactNativePackage()); 29 | return packages; 30 | } 31 | 32 | @Override 33 | protected String getJSMainModuleName() { 34 | return "index"; 35 | } 36 | }; 37 | 38 | @Override 39 | public ReactNativeHost getReactNativeHost() { 40 | return mReactNativeHost; 41 | } 42 | 43 | @Override 44 | public void onCreate() { 45 | super.onCreate(); 46 | SoLoader.init(this, /* native exopackage */ false); 47 | initializeFlipper(this, getReactNativeHost().getReactInstanceManager()); 48 | } 49 | 50 | /** 51 | * Loads Flipper in React Native templates. Call this in the onCreate method with something like 52 | * initializeFlipper(this, getReactNativeHost().getReactInstanceManager()); 53 | * 54 | * @param context 55 | * @param reactInstanceManager 56 | */ 57 | private static void initializeFlipper( 58 | Context context, ReactInstanceManager reactInstanceManager) { 59 | if (BuildConfig.DEBUG) { 60 | try { 61 | /* 62 | We use reflection here to pick up the class that initializes Flipper, 63 | since Flipper library is not available in release mode 64 | */ 65 | Class aClass = Class.forName("com.withmockjs.ReactNativeFlipper"); 66 | aClass 67 | .getMethod("initializeFlipper", Context.class, ReactInstanceManager.class) 68 | .invoke(null, context, reactInstanceManager); 69 | } catch (ClassNotFoundException e) { 70 | e.printStackTrace(); 71 | } catch (NoSuchMethodException e) { 72 | e.printStackTrace(); 73 | } catch (IllegalAccessException e) { 74 | e.printStackTrace(); 75 | } catch (InvocationTargetException e) { 76 | e.printStackTrace(); 77 | } 78 | } 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /example/WithMockJs/android/app/src/main/res/mipmap-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/WhatAKitty/react-native-fetch-mock/0ca63a89a344543b1d8f39689dfca9575dc0ddef/example/WithMockJs/android/app/src/main/res/mipmap-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /example/WithMockJs/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/WhatAKitty/react-native-fetch-mock/0ca63a89a344543b1d8f39689dfca9575dc0ddef/example/WithMockJs/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /example/WithMockJs/android/app/src/main/res/mipmap-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/WhatAKitty/react-native-fetch-mock/0ca63a89a344543b1d8f39689dfca9575dc0ddef/example/WithMockJs/android/app/src/main/res/mipmap-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /example/WithMockJs/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/WhatAKitty/react-native-fetch-mock/0ca63a89a344543b1d8f39689dfca9575dc0ddef/example/WithMockJs/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /example/WithMockJs/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/WhatAKitty/react-native-fetch-mock/0ca63a89a344543b1d8f39689dfca9575dc0ddef/example/WithMockJs/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /example/WithMockJs/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/WhatAKitty/react-native-fetch-mock/0ca63a89a344543b1d8f39689dfca9575dc0ddef/example/WithMockJs/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /example/WithMockJs/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/WhatAKitty/react-native-fetch-mock/0ca63a89a344543b1d8f39689dfca9575dc0ddef/example/WithMockJs/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /example/WithMockJs/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/WhatAKitty/react-native-fetch-mock/0ca63a89a344543b1d8f39689dfca9575dc0ddef/example/WithMockJs/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /example/WithMockJs/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/WhatAKitty/react-native-fetch-mock/0ca63a89a344543b1d8f39689dfca9575dc0ddef/example/WithMockJs/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /example/WithMockJs/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/WhatAKitty/react-native-fetch-mock/0ca63a89a344543b1d8f39689dfca9575dc0ddef/example/WithMockJs/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /example/WithMockJs/android/app/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | WithMockJs 3 | 4 | -------------------------------------------------------------------------------- /example/WithMockJs/android/app/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /example/WithMockJs/android/build.gradle: -------------------------------------------------------------------------------- 1 | // Top-level build file where you can add configuration options common to all sub-projects/modules. 2 | 3 | buildscript { 4 | ext { 5 | buildToolsVersion = "29.0.2" 6 | minSdkVersion = 16 7 | compileSdkVersion = 29 8 | targetSdkVersion = 29 9 | } 10 | repositories { 11 | google() 12 | jcenter() 13 | } 14 | dependencies { 15 | classpath("com.android.tools.build:gradle:3.5.3") 16 | // NOTE: Do not place your application dependencies here; they belong 17 | // in the individual module build.gradle files 18 | } 19 | } 20 | 21 | allprojects { 22 | repositories { 23 | mavenLocal() 24 | maven { 25 | // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm 26 | url("$rootDir/../node_modules/react-native/android") 27 | } 28 | maven { 29 | // Android JSC is installed from npm 30 | url("$rootDir/../node_modules/jsc-android/dist") 31 | } 32 | 33 | google() 34 | jcenter() 35 | maven { url 'https://www.jitpack.io' } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /example/WithMockJs/android/gradle.properties: -------------------------------------------------------------------------------- 1 | # Project-wide Gradle settings. 2 | 3 | # IDE (e.g. Android Studio) users: 4 | # Gradle settings configured through the IDE *will override* 5 | # any settings specified in this file. 6 | 7 | # For more details on how to configure your build environment visit 8 | # http://www.gradle.org/docs/current/userguide/build_environment.html 9 | 10 | # Specifies the JVM arguments used for the daemon process. 11 | # The setting is particularly useful for tweaking memory settings. 12 | # Default value: -Xmx10248m -XX:MaxPermSize=256m 13 | # org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 14 | 15 | # When configured, Gradle will run in incubating parallel mode. 16 | # This option should only be used with decoupled projects. More details, visit 17 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 18 | # org.gradle.parallel=true 19 | 20 | # AndroidX package structure to make it clearer which packages are bundled with the 21 | # Android operating system, and which are packaged with your app's APK 22 | # https://developer.android.com/topic/libraries/support-library/androidx-rn 23 | android.useAndroidX=true 24 | # Automatically convert third-party libraries to use AndroidX 25 | android.enableJetifier=true 26 | 27 | # Version of flipper SDK to use with React Native 28 | FLIPPER_VERSION=0.54.0 29 | -------------------------------------------------------------------------------- /example/WithMockJs/android/gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/WhatAKitty/react-native-fetch-mock/0ca63a89a344543b1d8f39689dfca9575dc0ddef/example/WithMockJs/android/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /example/WithMockJs/android/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-6.2-all.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /example/WithMockJs/android/gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | # 4 | # Copyright 2015 the original author or authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | ## 21 | ## Gradle start up script for UN*X 22 | ## 23 | ############################################################################## 24 | 25 | # Attempt to set APP_HOME 26 | # Resolve links: $0 may be a link 27 | PRG="$0" 28 | # Need this for relative symlinks. 29 | while [ -h "$PRG" ] ; do 30 | ls=`ls -ld "$PRG"` 31 | link=`expr "$ls" : '.*-> \(.*\)$'` 32 | if expr "$link" : '/.*' > /dev/null; then 33 | PRG="$link" 34 | else 35 | PRG=`dirname "$PRG"`"/$link" 36 | fi 37 | done 38 | SAVED="`pwd`" 39 | cd "`dirname \"$PRG\"`/" >/dev/null 40 | APP_HOME="`pwd -P`" 41 | cd "$SAVED" >/dev/null 42 | 43 | APP_NAME="Gradle" 44 | APP_BASE_NAME=`basename "$0"` 45 | 46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 48 | 49 | # Use the maximum available, or set MAX_FD != -1 to use that value. 50 | MAX_FD="maximum" 51 | 52 | warn () { 53 | echo "$*" 54 | } 55 | 56 | die () { 57 | echo 58 | echo "$*" 59 | echo 60 | exit 1 61 | } 62 | 63 | # OS specific support (must be 'true' or 'false'). 64 | cygwin=false 65 | msys=false 66 | darwin=false 67 | nonstop=false 68 | case "`uname`" in 69 | CYGWIN* ) 70 | cygwin=true 71 | ;; 72 | Darwin* ) 73 | darwin=true 74 | ;; 75 | MINGW* ) 76 | msys=true 77 | ;; 78 | NONSTOP* ) 79 | nonstop=true 80 | ;; 81 | esac 82 | 83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 84 | 85 | # Determine the Java command to use to start the JVM. 86 | if [ -n "$JAVA_HOME" ] ; then 87 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 88 | # IBM's JDK on AIX uses strange locations for the executables 89 | JAVACMD="$JAVA_HOME/jre/sh/java" 90 | else 91 | JAVACMD="$JAVA_HOME/bin/java" 92 | fi 93 | if [ ! -x "$JAVACMD" ] ; then 94 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 95 | 96 | Please set the JAVA_HOME variable in your environment to match the 97 | location of your Java installation." 98 | fi 99 | else 100 | JAVACMD="java" 101 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 102 | 103 | Please set the JAVA_HOME variable in your environment to match the 104 | location of your Java installation." 105 | fi 106 | 107 | # Increase the maximum file descriptors if we can. 108 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 109 | MAX_FD_LIMIT=`ulimit -H -n` 110 | if [ $? -eq 0 ] ; then 111 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 112 | MAX_FD="$MAX_FD_LIMIT" 113 | fi 114 | ulimit -n $MAX_FD 115 | if [ $? -ne 0 ] ; then 116 | warn "Could not set maximum file descriptor limit: $MAX_FD" 117 | fi 118 | else 119 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 120 | fi 121 | fi 122 | 123 | # For Darwin, add options to specify how the application appears in the dock 124 | if $darwin; then 125 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 126 | fi 127 | 128 | # For Cygwin or MSYS, switch paths to Windows format before running java 129 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then 130 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 131 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 132 | JAVACMD=`cygpath --unix "$JAVACMD"` 133 | 134 | # We build the pattern for arguments to be converted via cygpath 135 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 136 | SEP="" 137 | for dir in $ROOTDIRSRAW ; do 138 | ROOTDIRS="$ROOTDIRS$SEP$dir" 139 | SEP="|" 140 | done 141 | OURCYGPATTERN="(^($ROOTDIRS))" 142 | # Add a user-defined pattern to the cygpath arguments 143 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 144 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 145 | fi 146 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 147 | i=0 148 | for arg in "$@" ; do 149 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 150 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 151 | 152 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 153 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 154 | else 155 | eval `echo args$i`="\"$arg\"" 156 | fi 157 | i=`expr $i + 1` 158 | done 159 | case $i in 160 | 0) set -- ;; 161 | 1) set -- "$args0" ;; 162 | 2) set -- "$args0" "$args1" ;; 163 | 3) set -- "$args0" "$args1" "$args2" ;; 164 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;; 165 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 166 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 167 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 168 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 169 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 170 | esac 171 | fi 172 | 173 | # Escape application args 174 | save () { 175 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 176 | echo " " 177 | } 178 | APP_ARGS=`save "$@"` 179 | 180 | # Collect all arguments for the java command, following the shell quoting and substitution rules 181 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 182 | 183 | exec "$JAVACMD" "$@" 184 | -------------------------------------------------------------------------------- /example/WithMockJs/android/gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto init 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto init 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :init 68 | @rem Get command-line arguments, handling Windows variants 69 | 70 | if not "%OS%" == "Windows_NT" goto win9xME_args 71 | 72 | :win9xME_args 73 | @rem Slurp the command line arguments. 74 | set CMD_LINE_ARGS= 75 | set _SKIP=2 76 | 77 | :win9xME_args_slurp 78 | if "x%~1" == "x" goto execute 79 | 80 | set CMD_LINE_ARGS=%* 81 | 82 | :execute 83 | @rem Setup the command line 84 | 85 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 86 | 87 | @rem Execute Gradle 88 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 89 | 90 | :end 91 | @rem End local scope for the variables with windows NT shell 92 | if "%ERRORLEVEL%"=="0" goto mainEnd 93 | 94 | :fail 95 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 96 | rem the _cmd.exe /c_ return code! 97 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 98 | exit /b 1 99 | 100 | :mainEnd 101 | if "%OS%"=="Windows_NT" endlocal 102 | 103 | :omega 104 | -------------------------------------------------------------------------------- /example/WithMockJs/android/settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'WithMockJs' 2 | apply from: file("../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesSettingsGradle(settings) 3 | include ':app' 4 | -------------------------------------------------------------------------------- /example/WithMockJs/app.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "WithMockJs", 3 | "displayName": "WithMockJs" 4 | } -------------------------------------------------------------------------------- /example/WithMockJs/babel.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | presets: ['module:metro-react-native-babel-preset'], 3 | }; 4 | -------------------------------------------------------------------------------- /example/WithMockJs/index.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @format 3 | */ 4 | 5 | import {AppRegistry} from 'react-native'; 6 | import App from './src/app'; 7 | import {name as appName} from './app.json'; 8 | 9 | AppRegistry.registerComponent(appName, () => App); 10 | -------------------------------------------------------------------------------- /example/WithMockJs/ios/Podfile: -------------------------------------------------------------------------------- 1 | require_relative '../node_modules/react-native/scripts/react_native_pods' 2 | require_relative '../node_modules/@react-native-community/cli-platform-ios/native_modules' 3 | 4 | platform :ios, '10.0' 5 | 6 | target 'WithMockJs' do 7 | config = use_native_modules! 8 | 9 | use_react_native!(:path => config["reactNativePath"]) 10 | 11 | target 'WithMockJsTests' do 12 | inherit! :complete 13 | # Pods for testing 14 | end 15 | 16 | # Enables Flipper. 17 | # 18 | # Note that if you have use_frameworks! enabled, Flipper will not work and 19 | # you should disable these next few lines. 20 | use_flipper! 21 | post_install do |installer| 22 | flipper_post_install(installer) 23 | end 24 | end 25 | 26 | target 'WithMockJs-tvOS' do 27 | # Pods for WithMockJs-tvOS 28 | 29 | target 'WithMockJs-tvOSTests' do 30 | inherit! :search_paths 31 | # Pods for testing 32 | end 33 | end 34 | -------------------------------------------------------------------------------- /example/WithMockJs/ios/WithMockJs-tvOS/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | en 7 | CFBundleExecutable 8 | $(EXECUTABLE_NAME) 9 | CFBundleIdentifier 10 | $(PRODUCT_BUNDLE_IDENTIFIER) 11 | CFBundleInfoDictionaryVersion 12 | 6.0 13 | CFBundleName 14 | $(PRODUCT_NAME) 15 | CFBundlePackageType 16 | APPL 17 | CFBundleShortVersionString 18 | 1.0 19 | CFBundleSignature 20 | ???? 21 | CFBundleVersion 22 | 1 23 | LSRequiresIPhoneOS 24 | 25 | NSAppTransportSecurity 26 | 27 | NSExceptionDomains 28 | 29 | localhost 30 | 31 | NSExceptionAllowsInsecureHTTPLoads 32 | 33 | 34 | 35 | 36 | NSLocationWhenInUseUsageDescription 37 | 38 | UILaunchStoryboardName 39 | LaunchScreen 40 | UIRequiredDeviceCapabilities 41 | 42 | armv7 43 | 44 | UISupportedInterfaceOrientations 45 | 46 | UIInterfaceOrientationPortrait 47 | UIInterfaceOrientationLandscapeLeft 48 | UIInterfaceOrientationLandscapeRight 49 | 50 | UIViewControllerBasedStatusBarAppearance 51 | 52 | 53 | 54 | -------------------------------------------------------------------------------- /example/WithMockJs/ios/WithMockJs-tvOSTests/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | en 7 | CFBundleExecutable 8 | $(EXECUTABLE_NAME) 9 | CFBundleIdentifier 10 | $(PRODUCT_BUNDLE_IDENTIFIER) 11 | CFBundleInfoDictionaryVersion 12 | 6.0 13 | CFBundleName 14 | $(PRODUCT_NAME) 15 | CFBundlePackageType 16 | BNDL 17 | CFBundleShortVersionString 18 | 1.0 19 | CFBundleSignature 20 | ???? 21 | CFBundleVersion 22 | 1 23 | 24 | 25 | -------------------------------------------------------------------------------- /example/WithMockJs/ios/WithMockJs.xcodeproj/xcshareddata/xcschemes/WithMockJs-tvOS.xcscheme: -------------------------------------------------------------------------------- 1 | 2 | 5 | 8 | 9 | 15 | 21 | 22 | 23 | 24 | 25 | 30 | 31 | 33 | 39 | 40 | 41 | 42 | 43 | 53 | 55 | 61 | 62 | 63 | 64 | 70 | 72 | 78 | 79 | 80 | 81 | 83 | 84 | 87 | 88 | 89 | -------------------------------------------------------------------------------- /example/WithMockJs/ios/WithMockJs.xcodeproj/xcshareddata/xcschemes/WithMockJs.xcscheme: -------------------------------------------------------------------------------- 1 | 2 | 5 | 8 | 9 | 15 | 21 | 22 | 23 | 24 | 25 | 30 | 31 | 33 | 39 | 40 | 41 | 42 | 43 | 53 | 55 | 61 | 62 | 63 | 64 | 70 | 72 | 78 | 79 | 80 | 81 | 83 | 84 | 87 | 88 | 89 | -------------------------------------------------------------------------------- /example/WithMockJs/ios/WithMockJs.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /example/WithMockJs/ios/WithMockJs/AppDelegate.h: -------------------------------------------------------------------------------- 1 | #import 2 | #import 3 | 4 | @interface AppDelegate : UIResponder 5 | 6 | @property (nonatomic, strong) UIWindow *window; 7 | 8 | @end 9 | -------------------------------------------------------------------------------- /example/WithMockJs/ios/WithMockJs/AppDelegate.m: -------------------------------------------------------------------------------- 1 | #import "AppDelegate.h" 2 | 3 | #import 4 | #import 5 | #import 6 | 7 | #ifdef FB_SONARKIT_ENABLED 8 | #import 9 | #import 10 | #import 11 | #import 12 | #import 13 | #import 14 | 15 | static void InitializeFlipper(UIApplication *application) { 16 | FlipperClient *client = [FlipperClient sharedClient]; 17 | SKDescriptorMapper *layoutDescriptorMapper = [[SKDescriptorMapper alloc] initWithDefaults]; 18 | [client addPlugin:[[FlipperKitLayoutPlugin alloc] initWithRootNode:application withDescriptorMapper:layoutDescriptorMapper]]; 19 | [client addPlugin:[[FKUserDefaultsPlugin alloc] initWithSuiteName:nil]]; 20 | [client addPlugin:[FlipperKitReactPlugin new]]; 21 | [client addPlugin:[[FlipperKitNetworkPlugin alloc] initWithNetworkAdapter:[SKIOSNetworkAdapter new]]]; 22 | [client start]; 23 | } 24 | #endif 25 | 26 | @implementation AppDelegate 27 | 28 | - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 29 | { 30 | #ifdef FB_SONARKIT_ENABLED 31 | InitializeFlipper(application); 32 | #endif 33 | 34 | RCTBridge *bridge = [[RCTBridge alloc] initWithDelegate:self launchOptions:launchOptions]; 35 | RCTRootView *rootView = [[RCTRootView alloc] initWithBridge:bridge 36 | moduleName:@"WithMockJs" 37 | initialProperties:nil]; 38 | 39 | rootView.backgroundColor = [[UIColor alloc] initWithRed:1.0f green:1.0f blue:1.0f alpha:1]; 40 | 41 | self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds]; 42 | UIViewController *rootViewController = [UIViewController new]; 43 | rootViewController.view = rootView; 44 | self.window.rootViewController = rootViewController; 45 | [self.window makeKeyAndVisible]; 46 | return YES; 47 | } 48 | 49 | - (NSURL *)sourceURLForBridge:(RCTBridge *)bridge 50 | { 51 | #if DEBUG 52 | return [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index" fallbackResource:nil]; 53 | #else 54 | return [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"]; 55 | #endif 56 | } 57 | 58 | @end 59 | -------------------------------------------------------------------------------- /example/WithMockJs/ios/WithMockJs/Images.xcassets/AppIcon.appiconset/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "images" : [ 3 | { 4 | "idiom" : "iphone", 5 | "size" : "29x29", 6 | "scale" : "2x" 7 | }, 8 | { 9 | "idiom" : "iphone", 10 | "size" : "29x29", 11 | "scale" : "3x" 12 | }, 13 | { 14 | "idiom" : "iphone", 15 | "size" : "40x40", 16 | "scale" : "2x" 17 | }, 18 | { 19 | "idiom" : "iphone", 20 | "size" : "40x40", 21 | "scale" : "3x" 22 | }, 23 | { 24 | "idiom" : "iphone", 25 | "size" : "60x60", 26 | "scale" : "2x" 27 | }, 28 | { 29 | "idiom" : "iphone", 30 | "size" : "60x60", 31 | "scale" : "3x" 32 | } 33 | ], 34 | "info" : { 35 | "version" : 1, 36 | "author" : "xcode" 37 | } 38 | } -------------------------------------------------------------------------------- /example/WithMockJs/ios/WithMockJs/Images.xcassets/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "info" : { 3 | "version" : 1, 4 | "author" : "xcode" 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /example/WithMockJs/ios/WithMockJs/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | en 7 | CFBundleDisplayName 8 | WithMockJs 9 | CFBundleExecutable 10 | $(EXECUTABLE_NAME) 11 | CFBundleIdentifier 12 | $(PRODUCT_BUNDLE_IDENTIFIER) 13 | CFBundleInfoDictionaryVersion 14 | 6.0 15 | CFBundleName 16 | $(PRODUCT_NAME) 17 | CFBundlePackageType 18 | APPL 19 | CFBundleShortVersionString 20 | 1.0 21 | CFBundleSignature 22 | ???? 23 | CFBundleVersion 24 | 1 25 | LSRequiresIPhoneOS 26 | 27 | NSAppTransportSecurity 28 | 29 | NSAllowsArbitraryLoads 30 | 31 | NSExceptionDomains 32 | 33 | localhost 34 | 35 | NSExceptionAllowsInsecureHTTPLoads 36 | 37 | 38 | 39 | 40 | NSLocationWhenInUseUsageDescription 41 | 42 | UILaunchStoryboardName 43 | LaunchScreen 44 | UIRequiredDeviceCapabilities 45 | 46 | armv7 47 | 48 | UISupportedInterfaceOrientations 49 | 50 | UIInterfaceOrientationPortrait 51 | UIInterfaceOrientationLandscapeLeft 52 | UIInterfaceOrientationLandscapeRight 53 | 54 | UIViewControllerBasedStatusBarAppearance 55 | 56 | 57 | 58 | -------------------------------------------------------------------------------- /example/WithMockJs/ios/WithMockJs/LaunchScreen.storyboard: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 25 | 31 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | -------------------------------------------------------------------------------- /example/WithMockJs/ios/WithMockJs/main.m: -------------------------------------------------------------------------------- 1 | #import 2 | 3 | #import "AppDelegate.h" 4 | 5 | int main(int argc, char * argv[]) { 6 | @autoreleasepool { 7 | return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class])); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /example/WithMockJs/ios/WithMockJsTests/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | en 7 | CFBundleExecutable 8 | $(EXECUTABLE_NAME) 9 | CFBundleIdentifier 10 | $(PRODUCT_BUNDLE_IDENTIFIER) 11 | CFBundleInfoDictionaryVersion 12 | 6.0 13 | CFBundleName 14 | $(PRODUCT_NAME) 15 | CFBundlePackageType 16 | BNDL 17 | CFBundleShortVersionString 18 | 1.0 19 | CFBundleSignature 20 | ???? 21 | CFBundleVersion 22 | 1 23 | 24 | 25 | -------------------------------------------------------------------------------- /example/WithMockJs/ios/WithMockJsTests/WithMockJsTests.m: -------------------------------------------------------------------------------- 1 | #import 2 | #import 3 | 4 | #import 5 | #import 6 | 7 | #define TIMEOUT_SECONDS 600 8 | #define TEXT_TO_LOOK_FOR @"Welcome to React" 9 | 10 | @interface WithMockJsTests : XCTestCase 11 | 12 | @end 13 | 14 | @implementation WithMockJsTests 15 | 16 | - (BOOL)findSubviewInView:(UIView *)view matching:(BOOL(^)(UIView *view))test 17 | { 18 | if (test(view)) { 19 | return YES; 20 | } 21 | for (UIView *subview in [view subviews]) { 22 | if ([self findSubviewInView:subview matching:test]) { 23 | return YES; 24 | } 25 | } 26 | return NO; 27 | } 28 | 29 | - (void)testRendersWelcomeScreen 30 | { 31 | UIViewController *vc = [[[RCTSharedApplication() delegate] window] rootViewController]; 32 | NSDate *date = [NSDate dateWithTimeIntervalSinceNow:TIMEOUT_SECONDS]; 33 | BOOL foundElement = NO; 34 | 35 | __block NSString *redboxError = nil; 36 | #ifdef DEBUG 37 | RCTSetLogFunction(^(RCTLogLevel level, RCTLogSource source, NSString *fileName, NSNumber *lineNumber, NSString *message) { 38 | if (level >= RCTLogLevelError) { 39 | redboxError = message; 40 | } 41 | }); 42 | #endif 43 | 44 | while ([date timeIntervalSinceNow] > 0 && !foundElement && !redboxError) { 45 | [[NSRunLoop mainRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.1]]; 46 | [[NSRunLoop mainRunLoop] runMode:NSRunLoopCommonModes beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.1]]; 47 | 48 | foundElement = [self findSubviewInView:vc.view matching:^BOOL(UIView *view) { 49 | if ([view.accessibilityLabel isEqualToString:TEXT_TO_LOOK_FOR]) { 50 | return YES; 51 | } 52 | return NO; 53 | }]; 54 | } 55 | 56 | #ifdef DEBUG 57 | RCTSetLogFunction(RCTDefaultLogFunction); 58 | #endif 59 | 60 | XCTAssertNil(redboxError, @"RedBox error: %@", redboxError); 61 | XCTAssertTrue(foundElement, @"Couldn't find element with text '%@' in %d seconds", TEXT_TO_LOOK_FOR, TIMEOUT_SECONDS); 62 | } 63 | 64 | 65 | @end 66 | -------------------------------------------------------------------------------- /example/WithMockJs/metro.config.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Metro configuration for React Native 3 | * https://github.com/facebook/react-native 4 | * 5 | * @format 6 | */ 7 | 8 | module.exports = { 9 | transformer: { 10 | getTransformOptions: async () => ({ 11 | transform: { 12 | experimentalImportSupport: false, 13 | inlineRequires: false, 14 | }, 15 | }), 16 | }, 17 | }; 18 | -------------------------------------------------------------------------------- /example/WithMockJs/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "WithMockJs", 3 | "version": "0.0.1", 4 | "private": true, 5 | "scripts": { 6 | "android": "react-native run-android", 7 | "ios": "react-native run-ios", 8 | "start": "react-native start", 9 | "test": "jest", 10 | "lint": "eslint ." 11 | }, 12 | "dependencies": { 13 | "react": "16.13.1", 14 | "react-native": "0.63.3", 15 | "react-native-fetch-mock": "^0.8.0" 16 | }, 17 | "devDependencies": { 18 | "@babel/core": "^7.12.3", 19 | "@babel/runtime": "^7.12.1", 20 | "@react-native-community/eslint-config": "^2.0.0", 21 | "babel-jest": "^26.6.1", 22 | "eslint": "^7.12.0", 23 | "jest": "^26.6.1", 24 | "metro-react-native-babel-preset": "^0.63.0", 25 | "react-test-renderer": "16.13.1" 26 | }, 27 | "jest": { 28 | "preset": "react-native" 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /example/WithMockJs/src/app.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from 'react'; 2 | import { View, Text } from 'react-native'; 3 | import FetchMock from 'react-native-fetch-mock'; 4 | 5 | const fetch = new FetchMock(require('../__mocks__')).fetch; 6 | class App extends Component { 7 | constructor(props) { 8 | super(props); 9 | 10 | this.state = { 11 | data: [], 12 | }; 13 | 14 | this.getData = this.getData.bind(this); 15 | } 16 | 17 | componentDidMount() { 18 | this.getData(); 19 | } 20 | 21 | async getData() { 22 | const { data, err } = await fetch('/api/users/mockjs') 23 | .then(res => { 24 | if (res.status !== 200) { 25 | throw new Error('fetch failed'); 26 | } 27 | return res.json(); 28 | }) 29 | .then(data => ({ data })) 30 | .catch(err => ({ err })); 31 | 32 | if (err) { 33 | return false; 34 | } 35 | 36 | this.setState({ 37 | data, 38 | }); 39 | } 40 | 41 | render() { 42 | return ( 43 | 44 | { 45 | this.state.data.map((item, index) => { 46 | return { item.name } 47 | }) 48 | } 49 | 50 | ); 51 | } 52 | } 53 | 54 | export default App; 55 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | module.exports = require('./dist'); 2 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "react-native-fetch-mock", 3 | "version": "1.0.0", 4 | "description": "fetch mock for react-native", 5 | "main": "index.js", 6 | "scripts": { 7 | "build": "yarn lint && yarn test && ./node_modules/.bin/babel src --out-dir dist", 8 | "test": "./node_modules/.bin/mocha --require @babel/register", 9 | "lint": "./node_modules/.bin/eslint src/**/*.js" 10 | }, 11 | "standard": { 12 | "parser": "babel-eslint", 13 | "ignore": [ 14 | "dist/", 15 | "__mocks__/", 16 | "node_modules/" 17 | ] 18 | }, 19 | "repository": { 20 | "type": "git", 21 | "url": "git+https://github.com/WhatAKitty/react-native-fetch-mock.git" 22 | }, 23 | "keywords": [ 24 | "react-native", 25 | "fetch-mock" 26 | ], 27 | "author": "WhatAKitty", 28 | "license": "MIT", 29 | "bugs": { 30 | "url": "https://github.com/WhatAKitty/react-native-fetch-mock/issues" 31 | }, 32 | "homepage": "https://github.com/WhatAKitty/react-native-fetch-mock#readme", 33 | "devDependencies": { 34 | "@babel/cli": "^7.12.1", 35 | "@babel/core": "^7.12.3", 36 | "@babel/eslint-parser": "^7.12.1", 37 | "@babel/polyfill": "^7.12.1", 38 | "@babel/preset-flow": "^7.12.1", 39 | "@babel/register": "^7.12.1", 40 | "eslint": "^7.12.0", 41 | "expect.js": "^0.3.1", 42 | "isomorphic-fetch": "^3.0.0", 43 | "metro-react-native-babel-preset": "^0.63.0", 44 | "mocha": "^8.2.0" 45 | }, 46 | "dependencies": { 47 | "mockjs": "^1.1.0", 48 | "path-to-regexp": "^5.0.0" 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/index.js: -------------------------------------------------------------------------------- 1 | import { pathToRegexp } from 'path-to-regexp'; 2 | import { parseRequest, matchUrl, isNull, delay } from './util'; 3 | import Response from './response'; 4 | 5 | class FetchMock { 6 | constructor(required, options = { 7 | fetch: () => { }, 8 | exclude: [], 9 | fallbackToNetwork: false, 10 | proxy: [], 11 | delay: 2000, // ms 12 | }) { 13 | if ('object' !== typeof required) { 14 | throw new Error('There is no required defined.'); 15 | } 16 | 17 | this.urls = []; 18 | this.raw = options.fetch; 19 | this.exclude = options.exclude || []; 20 | this.fallbackToNetwork = options.fallbackToNetwork || false; 21 | this.proxy = options.proxy || []; 22 | this.delayTime = options.delay; 23 | 24 | this.loadMocks = this.loadMocks.bind(this); 25 | this.loadMock = this.loadMock.bind(this); 26 | this.matchReqUrl = this.matchReqUrl.bind(this); 27 | this.isExclude = this.isExclude.bind(this); 28 | this.isProxied = this.isProxied.bind(this); 29 | this.fetch = this.fetch.bind(this); 30 | 31 | this.loadMocks(required); 32 | } 33 | 34 | loadMocks(required) { 35 | const __mocks__ = required.default || required; // es6 import or amd 36 | let mocks = Object.keys(__mocks__); 37 | mocks.forEach(key => { 38 | this.loadMock(key, __mocks__[key]); 39 | }); 40 | } 41 | 42 | loadMock(key, mock) { 43 | if ('object' !== typeof mock) { 44 | if ('function' === typeof mock) { 45 | var items = key.split(' '); 46 | var method = items.length === 2 ? items[0] : 'GET'; 47 | var url = items.length === 2 ? items[1] : key; 48 | this.urls.push({ 49 | method, 50 | url, 51 | func: mock, 52 | }); 53 | } 54 | return; 55 | } 56 | const keys = Object.keys(mock); 57 | keys.map(key => { 58 | this.loadMock(key, mock[key]); 59 | }); 60 | } 61 | 62 | matchReqUrl(request) { 63 | let insideParams; 64 | const filters = this.urls.filter(uri => { 65 | const obj = matchUrl(uri.url, request.url); 66 | if (obj.result && uri.method.toUpperCase() === request.method.toUpperCase()) { 67 | insideParams = obj.params; 68 | return true; 69 | } 70 | return false; 71 | }); 72 | if (!filters || filters.length == 0) { 73 | return { 74 | matched: false, 75 | }; 76 | } 77 | request.urlparams = insideParams; 78 | return { 79 | matched: true, 80 | request, 81 | mock: filters[0], 82 | }; 83 | } 84 | 85 | isExclude(url) { 86 | for (let i = 0; i < this.exclude.length; i++) { 87 | const excludeUrl = this.exclude[i]; 88 | if (excludeUrl === url || pathToRegexp(`${excludeUrl}`).exec(url) !== null) { 89 | return true; 90 | } 91 | } 92 | return false; 93 | } 94 | 95 | isProxied(url) { 96 | if (this.proxy.length === 0) return false; 97 | const proxied = this.proxy.filter(item => pathToRegexp(`${item.path}`).exec(url) !== null); 98 | if (proxied.length > 1) throw new Error(`${url} proxied has two proxies, you should specific only one`); 99 | 100 | return proxied[0]; 101 | } 102 | 103 | proxied(url) { 104 | // get proxied info 105 | let matches, proxied; 106 | this.proxy.forEach(item => { 107 | const tmp = pathToRegexp(item.path).exec(url); 108 | if (tmp.length > 1) { 109 | matches = tmp; 110 | proxied = item; 111 | return false; 112 | } 113 | }); 114 | 115 | return proxied.process ? proxied.process(proxied, matches) : `${proxied.target}/${matches[1]}`; 116 | } 117 | 118 | fetch(url, options = {}) { 119 | // using proxy 120 | if (this.isProxied(url)) { 121 | url = this.proxied(url); 122 | } 123 | 124 | // using raw fetch while match exclude or the fallbackToNetwork value is 'always' 125 | if (this.isExclude(url) || this.fallbackToNetwork === 'always') { 126 | // using raw fetch 127 | return this.raw(url, options); 128 | } 129 | 130 | const { matched, request, mock } = this.matchReqUrl(parseRequest(url, options)); 131 | if (!matched) { 132 | if (this.fallbackToNetwork) { 133 | // Unhandled calls fall through to the network 134 | return this.raw(url, options); 135 | } else { 136 | // Unhandled calls throw an error 137 | throw new Error(`No url ${url} is defined.`); 138 | } 139 | } 140 | if ('function' !== typeof mock.func) { 141 | // the mock func is not a function 142 | throw new Error(`The url ${url} defined in __mocks__ is not a function`); 143 | } 144 | let obj = mock.func(request); 145 | 146 | if (isNull(obj)) { 147 | throw 'response data should not be undefined or null, it will be an object or an array at least'; 148 | } 149 | 150 | // resolve prue data object 151 | if (isNull(obj.status)) { 152 | obj = { 153 | status: 200, 154 | data: obj, 155 | }; 156 | } 157 | 158 | const response = new Response(obj); 159 | const delayTime = options.delay || this.delayTime || 0; 160 | return delay(delayTime).then(() => Promise.resolve(response)); 161 | } 162 | } 163 | 164 | export default FetchMock; 165 | export { default as Mock } from 'mockjs'; 166 | -------------------------------------------------------------------------------- /src/response.js: -------------------------------------------------------------------------------- 1 | 2 | const _status = Symbol('status'); 3 | const _data = Symbol('data'); 4 | const _statusText = Symbol('statusText'); 5 | 6 | class Response { 7 | constructor({ 8 | status, 9 | data = {}, 10 | statusText = '', 11 | }) { 12 | this[_status] = status; 13 | this[_data] = data; 14 | this[_statusText] = statusText; 15 | } 16 | 17 | get status() { 18 | return this[_status]; 19 | } 20 | 21 | get statusText() { 22 | return this[_statusText]; 23 | } 24 | 25 | get ok() { 26 | if (this.status >= 200 && this.status < 300) { 27 | return true; 28 | } else { 29 | return false; 30 | } 31 | } 32 | 33 | text() { 34 | try { 35 | return Promise.resolve(JSON.stringify(this[_data])); 36 | } catch (err) { 37 | return Promise.reject(new Error('failed text invoke.')); 38 | } 39 | } 40 | 41 | json() { 42 | return this[_data]; 43 | } 44 | 45 | } 46 | 47 | export default Response; 48 | -------------------------------------------------------------------------------- /src/util.js: -------------------------------------------------------------------------------- 1 | 2 | const isNull = (obj) => { 3 | if ('undefined' === typeof obj || obj === null) { 4 | return true; 5 | } 6 | 7 | return false; 8 | }; 9 | 10 | const removeProctol = (url) => { 11 | let index = -1; 12 | if ((index = url.indexOf('://')) > -1) { 13 | // contains proctol 14 | return url.substring(index); 15 | } 16 | return url; 17 | }; 18 | 19 | const parseParamStr = (paramStr, isGet) => { 20 | let params = {}; 21 | const paramPairs = paramStr.split('&'); 22 | for (var i = 0; i < paramPairs.length; i++) { 23 | const paramPair = paramPairs[i]; 24 | if (paramPair.indexOf('=') === -1) { 25 | continue; 26 | } 27 | const paramPairArray = paramPair.split('='); 28 | 29 | const paramValue = isGet ? decodeURI(paramPairArray[1]) : paramPairArray[1]; 30 | params[paramPairArray[0]] = paramPairArray.length === 2 ? paramValue : null; 31 | } 32 | return params; 33 | }; 34 | 35 | const parseBody = (body) => { 36 | if ('object' === typeof body) { 37 | return body; 38 | } 39 | try { 40 | return JSON.parse(body); 41 | } catch (e) { 42 | return parseParamStr(body); 43 | } 44 | }; 45 | 46 | const parseUrl = (url) => { 47 | const index = url.indexOf('?'); 48 | const items = index > -1 ? url.split('?') : [url]; 49 | if (items.length === 1) { 50 | return { 51 | url: items[0], 52 | params: {}, 53 | }; 54 | } 55 | 56 | return { 57 | url: items[0], 58 | params: parseParamStr(items[1], true), 59 | }; 60 | }; 61 | 62 | const parseRequest = (url, options = {}) => { 63 | const urlObj = parseUrl(url); 64 | const data = parseBody(options.body || {}); 65 | return { 66 | method: options.method || 'GET', 67 | url: urlObj.url, 68 | headers: options.headers, 69 | params: Object.assign({}, urlObj.params, data), 70 | }; 71 | }; 72 | 73 | const prueUrl = (url) => { 74 | const index = url.indexOf('?'); 75 | const result = index > -1 ? url.substring(0, index) : url; 76 | return result; 77 | }; 78 | 79 | const matchUrl = (sourceUrl, targetUrl) => { 80 | if (sourceUrl === targetUrl) { 81 | return { 82 | result: true, 83 | params: {}, 84 | }; 85 | } 86 | const sourceUrlWithoutProctol = removeProctol(sourceUrl); 87 | const targetUrlWithoutProctol = removeProctol(targetUrl); 88 | const sourceUrlSplits = sourceUrlWithoutProctol.split('/'); 89 | const targetUrlSplits = targetUrlWithoutProctol.split('/'); 90 | 91 | if (sourceUrlSplits.length !== targetUrlSplits.length) { 92 | return { 93 | result: false, 94 | }; 95 | } 96 | 97 | let params = {}; 98 | for (let i = 0; i < sourceUrlSplits.length; i++) { 99 | const sourceUrlSplit = sourceUrlSplits[i]; 100 | const targetUrlSplit = targetUrlSplits[i]; 101 | if (sourceUrlSplit === targetUrlSplit) { 102 | continue; 103 | } 104 | 105 | if (sourceUrlSplit.startsWith('{') && sourceUrlSplit.endsWith('}')) { 106 | if (sourceUrlSplit.replace(/[^{]/g, '').length > 1 || sourceUrlSplit.replace(/[^}]/g, '').length > 1) { 107 | return { 108 | result: false, 109 | }; 110 | } 111 | // contains url parameter 112 | params[sourceUrlSplit.substring(1, sourceUrlSplit.length - 1)] = targetUrlSplit; 113 | continue; 114 | } 115 | return { 116 | result: false, 117 | }; 118 | } 119 | 120 | return { 121 | result: true, 122 | params, 123 | }; 124 | }; 125 | 126 | const delay = (duration) => { 127 | return new Promise(resolve => { 128 | setTimeout(() => { 129 | resolve(); 130 | }, duration); 131 | }); 132 | }; 133 | 134 | export { 135 | isNull, 136 | prueUrl, 137 | parseUrl, 138 | parseRequest, 139 | matchUrl, 140 | delay, 141 | }; 142 | -------------------------------------------------------------------------------- /test/fallbackToNetwork.test.js: -------------------------------------------------------------------------------- 1 | import '@babel/polyfill'; 2 | import expect from 'expect.js'; 3 | import FetchMock, { Mock } from '../src'; 4 | 5 | const fetch1 = new FetchMock(require('../__mocks__'), { 6 | delay: 200, // delay 200ms 7 | fetch: require('isomorphic-fetch'), 8 | fallbackToNetwork: false 9 | }).fetch; 10 | describe('test fetch mock with fallbackToNetwork=false', () => { 11 | it('fetch /api/no-mocked', async () => { 12 | try { 13 | await fetch1('/api/no-mocked'); 14 | } catch (e) { 15 | expect(e.toString()).to.be.eql('Error: No url /api/no-mocked is defined.') 16 | } 17 | }).timeout(20000); 18 | }); 19 | 20 | const fetch2 = new FetchMock(require('../__mocks__'), { 21 | delay: 200, // delay 200ms 22 | fetch: require('isomorphic-fetch'), 23 | fallbackToNetwork: true 24 | }).fetch; 25 | describe('test fetch mock with fallbackToNetwork=true', () => { 26 | it('fetch http://www.baidu.com', async () => { 27 | const response = await fetch2('http://www.baidu.com'); 28 | const { status } = response; 29 | expect(status).to.be.eql(200); 30 | }).timeout(20000); 31 | 32 | it('fetch /api/users/{userId}', async () => { 33 | const response = await fetch2('/api/users/123'); 34 | const { status } = response; 35 | expect(status).to.be.eql(200); 36 | const data = await response.json(); 37 | expect(data).not.to.be(undefined); 38 | expect(data).not.to.be.empty(); 39 | expect(data).to.be.property('userId', '123'); 40 | }).timeout(20000); 41 | }); 42 | 43 | const fetch3 = new FetchMock(require('../__mocks__'), { 44 | delay: 200, // delay 200ms 45 | fetch: require('isomorphic-fetch'), 46 | fallbackToNetwork: 'always' 47 | }).fetch; 48 | describe('test fetch mock with fallbackToNetwork=true', () => { 49 | it('fetch http://www.baidu.com', async () => { 50 | const response = await fetch3('http://www.baidu.com'); 51 | const { status } = response; 52 | expect(status).to.be.eql(200); 53 | }).timeout(20000); 54 | 55 | it('fetch /api/users/{userId}', async () => { 56 | try { 57 | await fetch3('/api/users/123'); 58 | } catch (e) { 59 | expect(e.toString()).to.be.eql('TypeError: Only absolute URLs are supported') 60 | } 61 | }).timeout(20000); 62 | }); 63 | -------------------------------------------------------------------------------- /test/index.test.js: -------------------------------------------------------------------------------- 1 | import '@babel/polyfill'; 2 | import expect from 'expect.js'; 3 | import FetchMock, { Mock } from '../src'; 4 | 5 | const fetch = new FetchMock(require('../__mocks__'), { 6 | delay: 200, // delay 200ms 7 | fetch: require('isomorphic-fetch'), 8 | exclude: [ 9 | 'https://www.amazon.com', 10 | '/foo/boo/:foo*', 11 | 'http://:foo*', 12 | 'https://:foo*', 13 | ], 14 | proxy: [{ 15 | path: '/ip(.*)', 16 | target: 'https://api.ipify.org', 17 | process: ({ target }, matches) => { 18 | return `${target}${matches[1]}` 19 | } 20 | }], 21 | }).fetch; 22 | describe('test fetch mock', () => { 23 | it('fetch /api/users data', async () => { 24 | const response = await fetch('/api/users'); 25 | const { status } = response; 26 | expect(status).to.be.eql(200); 27 | const data = await response.json(); 28 | expect(data).not.to.be(undefined); 29 | expect(data).not.to.be.empty(); 30 | expect(data).to.be.an('array'); 31 | expect(data).to.have.length(2); 32 | }).timeout(20000); 33 | 34 | it('fetch /api/users?a=b', async () => { 35 | const response = await fetch('/api/users'); 36 | const { status } = response; 37 | expect(status).to.be.eql(200); 38 | const data = await response.json(); 39 | expect(data).not.to.be(undefined); 40 | expect(data).not.to.be.empty(); 41 | expect(data).to.be.an('array'); 42 | expect(data).to.have.length(2); 43 | }).timeout(20000); 44 | 45 | it('fetch /api/users with url parameters', async () => { 46 | const response = await fetch('/api/users?name=John'); 47 | const { status } = response; 48 | expect(status).to.be.eql(200); 49 | const data = await response.json(); 50 | expect(data).not.to.be(undefined); 51 | expect(data).not.to.be.empty(); 52 | expect(data).to.be.an('array'); 53 | expect(data).to.have.length(1); 54 | }).timeout(20000); 55 | 56 | it('fetch /api/users with post parameters', async () => { 57 | const response = await fetch('/api/users', { 58 | method: 'GET', 59 | headers: { 60 | 'Content-Type': 'application/json', 61 | }, 62 | body: JSON.stringify({ 63 | name: 'John', 64 | }), 65 | }); 66 | const { status } = response; 67 | expect(status).to.be.eql(200); 68 | const data = await response.json(); 69 | expect(data).not.to.be(undefined); 70 | expect(data).not.to.be.empty(); 71 | expect(data).to.be.an('array'); 72 | expect(data).to.have.length(1); 73 | }).timeout(20000); 74 | 75 | it('fetch /api/users/{userId}', async () => { 76 | const response = await fetch('/api/users/123'); 77 | const { status } = response; 78 | expect(status).to.be.eql(200); 79 | const data = await response.json(); 80 | expect(data).not.to.be(undefined); 81 | expect(data).not.to.be.empty(); 82 | expect(data).to.be.property('userId', '123'); 83 | }).timeout(20000); 84 | 85 | it('fetch /api/users/mockjs with mockjs', async () => { 86 | const response = await fetch('/api/users/mockjs'); 87 | const { status } = response; 88 | expect(status).to.be.eql(200); 89 | const data = await response.json(); 90 | expect(data).not.to.be(undefined); 91 | expect(data).not.to.be.empty(); 92 | expect(data).to.be.an('array'); 93 | expect(data).to.have.length(2); 94 | }).timeout(20000); 95 | 96 | it('fetch /api/users/mockjs with mockjs', async () => { 97 | const response = await fetch('/api/users/mockjs'); 98 | const { status } = response; 99 | expect(status).to.be.eql(200); 100 | const data = await response.json(); 101 | expect(data).not.to.be(undefined); 102 | expect(data).not.to.be.empty(); 103 | expect(data).to.be.an('array'); 104 | expect(data).to.have.length(2); 105 | }).timeout(20000); 106 | 107 | it('fetch /api/users/{userid} with prue data response', async () => { 108 | const response = await fetch('/api/users/pru/121'); 109 | const { status } = response; 110 | expect(status).to.be.eql(200); 111 | const data = await response.json(); 112 | expect(data).not.to.be(undefined); 113 | expect(data).not.to.be.empty(); 114 | expect(data).to.be.an('object'); 115 | expect(data).to.be.property('userId', '121'); 116 | }).timeout(20000); 117 | 118 | it('fetch exclude path', async () => { 119 | const response = await fetch('https://www.amazon.com'); 120 | const { status } = response; 121 | expect(status).to.be.eql(200); 122 | const html = await response.text(); 123 | expect(html).not.to.be(undefined); 124 | expect(html).not.to.be.empty(); 125 | expect(html).to.be.an('string'); 126 | }).timeout(20000); 127 | 128 | it('post /api/users', async () => { 129 | const { status } = await fetch('/api/users', { 130 | method: 'POST', 131 | headers: { 132 | 'Content-Type': 'application/json', 133 | }, 134 | body: JSON.stringify({ 135 | name: 'John', 136 | }), 137 | }); 138 | expect(status).to.be.eql(201); 139 | }).timeout(20000); 140 | 141 | it('put /api/users/123', async () => { 142 | const response = await fetch('/api/users/123', { 143 | method: 'PUT', 144 | headers: { 145 | 'Content-Type': 'application/json', 146 | }, 147 | body: JSON.stringify({ 148 | name: 'John2', 149 | }), 150 | }); 151 | const { status } = response; 152 | expect(status).to.be.eql(204); 153 | const data = await response.json(); 154 | expect(data).not.to.be(undefined); 155 | expect(data).not.to.be.empty(); 156 | expect(data).to.be.an('object'); 157 | expect(data.userId).to.be.eql(123); 158 | }).timeout(20000); 159 | 160 | it('proxy other api server', async () => { 161 | const response = await fetch('/ip/?format=json'); 162 | const { status } = response; 163 | const data = await response.json(); 164 | expect(status).to.be.eql(200); 165 | expect(data).not.to.be(undefined); 166 | expect(data).not.to.be.empty(); 167 | expect(data).to.be.an('object'); 168 | expect(data.ip).to.be.an('string'); 169 | }).timeout(20000); 170 | 171 | describe('test delay mock', () => { 172 | 173 | it('global delay', async () => { 174 | const start = new Date().getTime(); 175 | await fetch('/api/users'); 176 | expect(new Date().getTime() - start).to.greaterThan(199).lessThan(210); 177 | }).timeout(20000); 178 | 179 | it('method delay 30ms', async () => { 180 | const start = new Date().getTime(); 181 | await fetch('/api/users', { 182 | delay: 30, 183 | }); 184 | expect(new Date().getTime() - start).to.greaterThan(29).lessThan(40); 185 | }).timeout(20000); 186 | 187 | it('method delay 3000ms', async () => { 188 | const start = new Date().getTime(); 189 | await fetch('/api/users', { 190 | delay: 3000, 191 | }); 192 | expect(new Date().getTime() - start).to.greaterThan(2999).lessThan(3100); 193 | }).timeout(20000); 194 | 195 | }); 196 | 197 | }); 198 | -------------------------------------------------------------------------------- /test/util.test.js: -------------------------------------------------------------------------------- 1 | import '@babel/polyfill'; 2 | import expect from 'expect.js'; 3 | import { prueUrl, parseUrl, parseRequest, matchUrl, delay } from '../src/util'; 4 | 5 | describe('test util methods', () => { 6 | it('get prue url', async () => { 7 | expect(prueUrl('http://www.baidu.com?')).to.eql('http://www.baidu.com'); 8 | expect(prueUrl('http://www.baidu.com?ab=23')).to.eql('http://www.baidu.com'); 9 | }); 10 | it('parse basic url', async () => { 11 | expect(parseUrl('http://www.baidu.com?')).to.eql({ 12 | url: 'http://www.baidu.com', 13 | params: {}, 14 | }); 15 | expect(parseUrl('http://www.baidu.com?ab=23')).to.eql({ 16 | url: 'http://www.baidu.com', 17 | params: { 18 | ab: '23', 19 | }, 20 | }); 21 | expect(parseUrl('http://www.baidu.com?ab=23&name=123')).to.eql({ 22 | url: 'http://www.baidu.com', 23 | params: { 24 | ab: '23', 25 | name: '123', 26 | }, 27 | }); 28 | }); 29 | it('parse error url', async () => { 30 | expect(parseUrl('http://www.baidu.com?a')).to.eql({ 31 | url: 'http://www.baidu.com', 32 | params: {}, 33 | }); 34 | expect(parseUrl('http://www.baidu.com?a??=1')).to.eql({ 35 | url: 'http://www.baidu.com', 36 | params: {}, 37 | }); 38 | expect(parseUrl('http://www.baidu.com?a=1?b=1')).to.eql({ 39 | url: 'http://www.baidu.com', 40 | params: { 41 | a: '1', 42 | }, 43 | }); 44 | }); 45 | it('parse encoded url', async () => { 46 | expect(parseUrl('http://www.baidu.com?callback=http%20%201')).to.eql({ 47 | url: 'http://www.baidu.com', 48 | params: { 49 | callback: 'http 1' 50 | }, 51 | }); 52 | }); 53 | it('parse request', async () => { 54 | expect(parseRequest('http://www.baidu.com?callback=http%20%201', { 55 | headers: { 56 | 'Content-Type': 'application/json', 57 | } 58 | })).to.eql({ 59 | method: 'GET', 60 | url: 'http://www.baidu.com', 61 | headers: { 62 | 'Content-Type': 'application/json', 63 | }, 64 | params: { 65 | callback: 'http 1' 66 | }, 67 | }); 68 | }); 69 | it('match url', async () => { 70 | expect(matchUrl('http://www.baidu.com', 'http://www.baidu.com')).to.ok(); 71 | }); 72 | it('match url with inside parameter', async () => { 73 | expect(matchUrl('http://www.baidu.com/{id}', 'http://www.baidu.com/123')).to.be.eql({ 74 | result: true, 75 | params: { 76 | id: '123', 77 | }, 78 | }); 79 | expect(matchUrl('http://www.baidu.com/{id}/do', 'http://www.baidu.com/123/do')).to.be.eql({ 80 | result: true, 81 | params: { 82 | id: '123', 83 | }, 84 | }); 85 | expect(matchUrl('http://www.baidu.com/{id}/do/{name}', 'http://www.baidu.com/123/do/hello')).to.be.eql({ 86 | result: true, 87 | params: { 88 | id: '123', 89 | name: 'hello', 90 | }, 91 | }); 92 | }); 93 | it('match error url with inside parameter', async () => { 94 | expect(matchUrl('http://www.baidu.com/{id}{name}/do', 'http://www.baidu.com/123/do')).to.be.eql({ 95 | result: false, 96 | }); 97 | expect(matchUrl('http://www.baidu.com/{id}{name/do', 'http://www.baidu.com/123/do')).to.be.eql({ 98 | result: false, 99 | }); 100 | expect(matchUrl('http://www.baidu.com/{id}name}/do', 'http://www.baidu.com/123/do')).to.be.eql({ 101 | result: false, 102 | }); 103 | expect(matchUrl('http://www.baidu.com/{id}/do', 'http://www.baidu.com/123')).to.be.eql({ 104 | result: false, 105 | }); 106 | }); 107 | 108 | it('delay 5000ms', async () => { 109 | const start = new Date().getTime(); 110 | await delay(5000); 111 | expect(new Date().getTime() - start).to.greaterThan(5000); 112 | }).timeout(20000); 113 | }); 114 | --------------------------------------------------------------------------------