Best JavaScript code snippet using storybook-root
ng-cordova-mocks.js
Source:ng-cordova-mocks.js  
1/*!2 * ngCordova3 * v0.1.20-alpha4 * Copyright 2015 Drifty Co. http://drifty.com/5 * See LICENSE in this repository for license information6 */7(function(){8var ngCordovaMocks = angular.module('ngCordovaMocks', []);9ngCordovaMocks.factory('$cordovaAppVersion', ['$q', function ($q) {10  var throwsError = false;11  return {12    throwsError: throwsError,13    getAppVersion: function () {14      var defer = $q.defer();15      defer.resolve('mock v');16      return defer.promise;17    }18  };19}]);20/**21 * @ngdoc service22 * @name ngCordovaMocks.cordovaBarcodeScanner23 *24 * @description25 * A service for testing barcode scanner features26 * in an app build with ngCordova.27 **/28ngCordovaMocks.factory('$cordovaBarcodeScanner', ['$q', function ($q) {29  var throwsError = false;30  var scannedText = '';31  var scannedFormat = '';32  var wasCancelled = false;33  return {34    /**35     * @ngdoc property36     * @name throwsError37     * @propertyOf ngCordovaMocks.cordovaBarcodeScanner38     *39     * @description40     * A flag that signals whether a promise should be rejected or not.41     * This property should only be used in automated tests.42     **/43    throwsError: throwsError,44    /**45     * @ngdoc property46     * @name scannedText47     * @propertyOf ngCordovaMocks.cordovaBarcodeScanner48     *49     * @description50     * Used to simulate the result.text property of a51     * successful scan. For more information, see the text at52     * https://github.com/wildabeast/BarcodeScanner/#using-the-plugin53     * This property should only be used in automated tests.54     **/55    scannedText: scannedText,56    /**57     * @ngdoc property58     * @name scannedFormat59     * @propertyOf ngCordovaMocks.cordovaBarcodeScanner60     * @description61     * Used to simulate the result.format property of a62     * successful scan. For more information, see the text at63     * https://github.com/wildabeast/BarcodeScanner/#using-the-plugin64     * This property should only be used in automated tests.65     **/66    scannedFormat: scannedFormat,67    /**68     * @ngdoc property69     * @name wasCancelled70     * @propertyOf ngCordovaMocks.cordovaBarcodeScanner71     *72     * @description73     * Used to simulate the result.cancelled property of a74     * successful scan. For more information, see the text at75     * https://github.com/wildabeast/BarcodeScanner/#using-the-plugin76     * This property should only be used in automated tests.77     **/78    wasCancelled: wasCancelled,79    scan: function () {80      var defer = $q.defer();81      if (this.throwsError) {82        defer.reject('There was an error scanning.');83      } else {84        defer.resolve({text: this.scannedText, format: this.scannedFormat, cancelled: this.wasCancelled});85      }86      return defer.promise;87    },88    encode: function (type, data) {89      this.scannedFormat = type;90      this.scannedText = data;91      var defer = $q.defer();92      if (this.throwsError) {93        defer.reject('There was an error encoding the data.');94      } else {95        defer.resolve();96      }97      return defer.promise;98    }99  };100}]);101/**102 * @ngdoc service103 * @name ngCordovaMocks.cordovaBLE104 *105 * @description106 * A service for ble features107 * in an app build with ngCordova.108 **/109ngCordovaMocks.factory('$cordovaBLE', ['$q', '$timeout', function ($q, $timeout) {110  var deviceScan = {111    name: 'Test Device',112    id: 'AA:BB:CC:DD:EE:FF',113    advertising: [2, 1, 6, 3, 3, 15, 24, 8, 9, 66, 97, 116, 116, 101, 114, 121],114    rssi: -55115  };116  var deviceConnect = {117    name: 'Test Device',118    id: 'AA:BB:CC:DD:EE:FF',119    advertising: [2, 1, 6, 3, 3, 15, 24, 8, 9, 66, 97, 116, 116, 101, 114, 121],120    rssi: -55,121    services: [122      '1800',123      '1801',124      '180f'125    ],126    characteristics: [127      {128        service: '1800',129        characteristic: '2a00',130        properties: ['Read']131      },132      {133        service: '1800',134        characteristic: '2a01',135        properties: ['Read']136      },137      {138        service: '1801',139        characteristic: '2a05',140        properties: ['Read']141      },142      {143        service: '180f',144        characteristic: '2a19',145        properties: ['Read'],146        descriptors: [{'uuid': '2901'}, {'uuid': '2904'}]147      }148    ]149  };150  var readData = new ArrayBuffer(8);151  return {152    scan: function (services, seconds) {153      var q = $q.defer();154      $timeout(function () {155        q.resolve(deviceScan);156      }, seconds * 1000);157      return q.promise;158    },159    connect: function (deviceID) {160      var q = $q.defer();161      $timeout(function () {162        q.resolve(deviceConnect);163      }, 1500);164      return q.promise;165    },166    disconnect: function (deviceID) {167      var q = $q.defer();168      $timeout(function () {169        q.resolve(true);170      }, 500);171      return q.promise;172    },173    read: function (deviceID, serviceUUID, characteristicUUID) {174      var q = $q.defer();175      $timeout(function () {176        q.resolve(readData);177      }, 100);178      return q.promise;179    },180    write: function (deviceID, serviceUUID, characteristicUUID, data) {181      var q = $q.defer();182      $timeout(function () {183        q.resolve(true);184      }, 100);185      return q.promise;186    },187    writeCommand: function (deviceID, serviceUUID, characteristicUUID, data) {188      var q = $q.defer();189      $timeout(function () {190        q.resolve(true);191      }, 100);192      return q.promise;193    },194    notify: function (deviceID, serviceUUID, characteristicUUID) {195      var q = $q.defer();196      $timeout(function () {197        q.resolve(true);198      }, 100);199      return q.promise;200    },201    indicate: function (deviceID, serviceUUID, characteristicUUID) {202      var q = $q.defer();203      $timeout(function () {204        q.resolve(true);205      }, 100);206      return q.promise;207    },208    isConnected: function (deviceID) {209      var q = $q.defer();210      q.resolve(true);211      return q.promise;212    },213    isEnabled: function () {214      var q = $q.defer();215      q.resolve(true);216      return q.promise;217    }218  };219}]);220ngCordovaMocks.factory('$cordovaBrightness', ['$q', function ($q) {221	var currentBrightness = 100;222	return {223		get: function () {224			var q = $q.defer();225			q.resolve(currentBrightness);226        	return q.promise;227		},228		set: function (data) {229			var q = $q.defer();230			currentBrightness = data;231			q.resolve('OK');232        	return q.promise;233		},234		setKeepScreenOn: function (bool) {235			var q = $q.defer();236			q.resolve('OK');237			return q.promise;238		}239	};240}]);241/**242 * @ngdoc service243 * @name ngCordovaMocks.cordovaCamera244 *245 * @description246 * A service for testing camera features247 * in an app build with ngCordova.248 **/249ngCordovaMocks.factory('$cordovaCamera', ['$q', function ($q) {250  var throwsError = false;251  var imageData = '';252  return {253    /**254     * @ngdoc property255     * @name throwsError256     * @propertyOf ngCordovaMocks.cordovaCamera257     *258     * @description259     * A flag that signals whether a promise should be rejected or not.260     * This property should only be used in automated tests.261     **/262    throwsError: throwsError,263    /**264     * @ngdoc property265     * @name imageData266     * @propertyOf ngCordovaMocks.cordovaCamera267     *268     * @description269     * The imagedata (e.g. an url) which will be returned from the device.270     * This property should only be used in automated tests.271     **/272    imageData: imageData,273    getPicture: function (options) {274      var defer = $q.defer();275      if (this.throwsError) {276        defer.reject('There was an error getting the picture.');277      } else {278        if (options) {279          options = options;	// This is just to get by JSHint.280        }281        defer.resolve(this.imageData);282      }283      return defer.promise;284    }285  };286}]);287/**288 * @ngdoc service289 * @name ngCordovaMocks.cordovaCapture290 *291 * @description292 * A service for testing media capture293 * in an app build with ngCordova.294 *295 * @example296 */297ngCordovaMocks.factory('$cordovaCapture', ['$q', function ($q) {298  var throwsError = false;299  return {300    /**301     * @ngdoc property302     * @name throwsError303     * @propertyOf ngCordovaMocks.cordovaCapture304     *305     * @description306     * A flag that signals whether a promise should be rejected or not.307     * This property should only be used in automated tests.308     **/309    throwsError: throwsError,310    captureAudio: function () {311      var defer = $q.defer();312      if (this.throwsError) {313        defer.reject('There was an error capturing the audio.');314      } else {315        defer.resolve();316      }317      return defer.promise;318    },319    captureImage: function () {320      var defer = $q.defer();321      if (this.throwsError) {322        defer.reject('There was an error capturing the image.');323      } else {324        defer.resolve();325      }326      return defer.promise;327    },328    captureVideo: function () {329      var defer = $q.defer();330      if (this.throwsError) {331        defer.reject('There was an error capturing the video.');332      } else {333        defer.resolve();334      }335      return defer.promise;336    }337  };338}]);339/**340 * @ngdoc service341 * @name ngCordovaMocks.cordovaContacts342 *343 * @description344 * A service for testing features related with contacts345 * in an app build with ngCordova.346 **/347ngCordovaMocks.factory('$cordovaContacts', ['$q', function ($q) {348  var throwsError = false;349  var contacts = [];350  return {351    /**352     @ngdoc property353     @name throwsError354     @propertyOf ngCordovaMocks.cordovaContacts355     @description356     A flag that signals whether a promise should be rejected or not.357     This property should only be used in automated tests.358     */359    throwsError: throwsError,360    /**361     @ngdoc contacts362     @name throwsError363     @propertyOf ngCordovaMocks.cordovaContacts364     @description365     An in-memory collection of contacts.366     This property should only be used in automated tests.367     */368    contacts: contacts,369    save: function (contact) {370      var defer = $q.defer();371      if (this.throwsError) {372        defer.reject('There was an error saving the contact.');373      } else {374        var existingIndex = null;375        for (var i = 0; i < this.contacts.length; i++) {376          // The actual implementation relies on the entire object match.377          // we're gong to rely on the ID.378          if (this.contacts[i].id === contact.id) {379            existingIndex = i;380            break;381          }382        }383        if (existingIndex === null) {384          this.contacts.push(contact);385          defer.resolve();386        } else {387          defer.reject('Contact already exists.');388        }389      }390      return defer.promise;391    },392    remove: function (contact) {393      var defer = $q.defer();394      if (this.throwsError) {395        defer.reject('There was an error saving the contact.');396      } else {397        var toRemove = null;398        for (var i = 0; i < this.contacts.length; i++) {399          // The actual implementation relies on the entire object match.400          // we're gong to rely on the ID.401          if (this.contacts[i].id === contact.id) {402            toRemove = i;403            break;404          }405        }406        if (toRemove === null) {407          defer.reject('Unable to find contact.');408        } else {409          this.contacts.splice(toRemove, 1);410          defer.resolve();411        }412      }413      return defer.promise;414    },415    find: function (options) {416      var defer = $q.defer();417      if (this.throwsError) {418        defer.reject('There was an error finding the contact.');419      } else {420        var fields = options.fields || ['id', 'displayName'];421        delete options.fields;422        if (!fields) {423          defer.reject('ContactError.INVALID_ARGUMENT_ERROR');424        } else {425          if (fields === '*') {426            defer.resolve(this.contacts);427          } else {428            // Implement a very rudimentary search approach for testing purposes.429            // This is NOT exhaustive.430            var results = [];431            for (var i = 0; i < this.contacts.length; i++) {432              for (var key in this.contacts[i]) {433                var propertyValue = this.contacts[i][key];434              }435            }436            // TODO: Search by individual fields437            defer.resolve(results);438          }439        }440      }441      return defer.promise;442    }443  };444}]);445/**446 * @ngdoc service447 * @name ngCordovaMocks.cordovaDatePicker448 *449 * @description450 * A service for testing datepicker features451 * in an app build with ngCordova.452 */453ngCordovaMocks.factory('$cordovaDatePicker', ['$q', function ($q) {454  return {455    show: function (options) {456      var q = $q.defer();457      options = options || {date: new Date(), mode: 'date'};458      q.resolve(options.date);459      return q.promise;460    }461  };462}]);463/**464 * @ngdoc service465 * @name ngCordovaMocks.cordovaDevice466 *467 * @description468 * A service for testing device information469 * in an app build with ngCordova.470 **/471ngCordovaMocks.factory('$cordovaDevice', function () {472  var device = '';473  var cordova = '';474  var model = '';475  var platform = '';476  var uuid = '';477  var version = '';478  return {479    /**480     @ngdoc property481     @name device482     @propertyOf ngCordovaMocks.cordovaDevice483     @description484     The name of the 'device'.485     This property should only be used in automated tests.486     */487    device: device,488    /**489     @ngdoc property490     @name cordova491     @propertyOf ngCordovaMocks.cordovaDevice492     @description493     The version of cordova in use.494     This property should only be used in automated tests.495     */496    cordova: cordova,497    /**498     @ngdoc property499     @name model500     @propertyOf ngCordovaMocks.cordovaDevice501     @description502     The model of the device using the app.503     This property should only be used in automated tests.504     */505    model: model,506    /**507     @ngdoc property508     @name platform509     @propertyOf ngCordovaMocks.cordovaDevice510     @description511     The name of the operating system in use.512     This property should only be used in automated tests.513     */514    platform: platform,515    /**516     @ngdoc property517     @name uuid518     @propertyOf ngCordovaMocks.cordovaDevice519     @description520     The unique identifier of a device.521     This property should only be used in automated tests.522     */523    uuid: uuid,524    /**525     @ngdoc property526     @name version527     @propertyOf ngCordovaMocks.cordovaDevice528     @description529     The version of the operating system.530     This property should only be used in automated tests.531     */532    version: version,533    /**534     @ngdoc property535     @name manufacturer536     @propertyOf ngCordovaMocks.cordovaDevice537     @description538     The manufacturer of the device.539     This property should only be used in automated tests.540     */541    version: version,542    getDevice: function () {543      return this.device;544    },545    getCordova: function () {546      return this.cordova;547    },548    getModel: function () {549      return this.model;550    },551    getPlatform: function () {552      return this.platform;553    },554    getUUID: function () {555      return this.uuid;556    },557    getVersion: function () {558      return this.version;559    },560    getManufacturer: function () {561      return this.manufacturer;562    }563  };564});565/**566 * @ngdoc service567 * @name ngCordovaMocks.cordovaDeviceMotion568 *569 * @description570 * A service for mocking the accelerometer571 * in an app build with ngCordova.572 **/573ngCordovaMocks.factory('$cordovaDeviceMotion', ['$interval', '$q', function ($interval, $q) {574  var currentAcceleration = null;575  var throwsError = false;576  var positions = [];577  var watchIntervals = [];578  return {579    /**580     * @ngdoc property581     * @name currentAcceleration582     * @propertyOf ngCordovaMocks.cordovaDeviceMotion583     *584     * @description585     * The current acceleration.586     * This property should only be used in automated tests.587     **/588    currentAcceleration: currentAcceleration,589    /**590     @ngdoc property591     @name throwsError592     @propertyOf ngCordovaMocks.cordovaDeviceMotion593     @description594     A flag that signals whether a promise should be rejected or not.595     This property should only be used in automated tests.596     */597    throwsError: throwsError,598    /**599     @ngdoc property600     @name positions601     @propertyOf ngCordovaMocks.cordovaDeviceMotion602     @description603     The collection of 'positions' that have been logged.604     This property should only be used in automated tests.605     */606    positions: positions,607    /**608     @ngdoc property609     @name watchIntervals610     @propertyOf ngCordovaMocks.cordovaDeviceMotion611     @description612     The collection of watchers that are currently active.613     This property should only be used in automated tests.614     */615    watchIntervals: watchIntervals,616    getCurrentAcceleration: function () {617      var defer = $q.defer();618      if (this.throwsError) {619        defer.reject('There was an error getting the current acceleration.');620      } else {621        defer.resolve(this.currentAcceleration);622      }623      return defer.promise;624    },625    watchAcceleration: function (options) {626      var defer = $q.defer();627      var watchId = Math.floor((Math.random() * 1000000) + 1);628      this.positions = [];629      self = this;630      if (this.throwsError) {631        defer.reject('There was an error watching the current acceleration.');632      } else {633        var delay = 10000;		// The default based on https://github.com/apache/cordova-plugin-device-motion634        if (options && options.frequency) {635          delay = options.frequency;636        }637        this.watchIntervals.push($interval(638          function () {639            if (self.throwsError) {640              defer.reject('There was an error watching the acceleration.');641            }642            // Generate a random position643            var randomX = Math.floor((Math.random() * 100) + 1);644            var randomY = Math.floor((Math.random() * 100) + 1);645            var randomZ = Math.floor((Math.random() * 100) + 1);646            var result = {x: randomX, y: randomY, z: randomZ, timestamp: Date.now()};647            self.positions.push(result);648            defer.notify(result);649          },650          delay651        ));652      }653      return {654        watchId: watchId,655        promise: defer.promise656      };657    },658    clearWatch: function (watchId) {659      var defer = $q.defer();660      if (watchId) {661        if (this.throwsError) {662          defer.reject('Unable to clear watch.');663        } else {664          var removed = -1;665          for (var i = 0; i < this.watchIntervals.length; i++) {666            if (this.watchIntervals[i].watchId === watchId) {667              $interval.cancel(watchIntervals[i].interval);668              removed = i;669              break;670            }671          }672          if (removed !== -1) {673            this.watchIntervals.splice(removed, 1);674          }675        }676      } else {677        defer.reject('Unable to clear watch. No watch ID provided.');678      }679      return defer.promise;680    }681  };682}]);683/**684 * @ngdoc service685 * @name ngCordovaMocks.cordovaDeviceOrientation686 *687 * @description688 * A service for testing compass fetures689 * in an app build with ngCordova.690 */691ngCordovaMocks.factory('$cordovaDeviceOrientation', ['$interval', '$q', function ($interval, $q) {692  var currentHeading = null;693  var throwsError = false;694  var readings = [];695  var watchIntervals = [];696  return {697    /**698     * @ngdoc property699     * @name currentHeading700     * @propertyOf ngCordovaMocks.cordovaDeviceOrientation701     *702     * @description703     * The current heading.704     * This property should only be used in automated tests.705     **/706    currentHeading: currentHeading,707    /**708     @ngdoc property709     @name throwsError710     @propertyOf ngCordovaMocks.cordovaDeviceOrientation711     @description712     A flag that signals whether a promise should be rejected or not.713     This property should only be used in automated tests.714     */715    throwsError: throwsError,716    /**717     @ngdoc property718     @name positions719     @propertyOf ngCordovaMocks.cordovaDeviceOrientation720     @description721     The collection of compass 'readings' that have been logged.722     This property should only be used in automated tests.723     */724    readings: readings,725    /**726     @ngdoc property727     @name watchIntervals728     @propertyOf ngCordovaMocks.cordovaDeviceOrientation729     @description730     The collection of watchers that are currently active.731     This property should only be used in automated tests.732     */733    watchIntervals: watchIntervals,734    getCurrentHeading: function () {735      var defer = $q.defer();736      if (this.throwsError) {737        defer.reject('There was an error getting the current heading.');738      } else {739        defer.resolve(this.currentHeading);740      }741      return defer.promise;742    },743    watchHeading: function (options) {744      var defer = $q.defer();745      var watchID = Math.floor((Math.random() * 1000000) + 1);746      var self = this;747      self.readings = [];748      if (self.throwsError) {749        defer.reject('There was an error getting the compass heading.');750      } else {751        var delay = 100;		// The default based on https://github.com/apache/cordova-plugin-device-orientation752        if (options && options.frequency) {753          delay = options.frequency;754        }755        self.watchIntervals.push({756          watchID: watchID,757          interval: $interval(758            function () {759              if (self.throwsError) {760                defer.reject('There was an error watching the acceleration.');761              }762              // Generate a random position763              var magneticHeading = (Math.random() * 359.99) + 1;764              var trueHeading = (Math.random() * 359.99) + 1;765              var headingAccuracy = Math.floor((Math.random() * 360) + 1);766              var result = {magneticHeading: magneticHeading, trueHeading: trueHeading, headingAccuracy: headingAccuracy, timestamp: Date.now()};767              self.readings.push(result);768              defer.notify(result);769            },770            delay771          )772        });773      }774      var cancel = function (id) {775        var removed = -1;776        for (var i = 0; i < self.watchIntervals.length; i++) {777          if (self.watchIntervals[i].watchID === id) {778            $interval.cancel(watchIntervals[i].interval);779            removed = i;780            break;781          }782        }783        if (removed !== -1) {784          self.watchIntervals.splice(removed, 1);785        }786      };787      defer.promise.cancel = function () {788        cancel(watchID);789      };790      defer.promise.clearWatch = function (id) {791        cancel(id || watchID);792      };793      defer.promise.watchID = watchID;794      return defer.promise;795    },796    clearWatch: function (watchId) {797      var defer = $q.defer();798      if (watchId) {799        if (this.throwsError) {800          defer.reject('Unable to clear watch.');801        } else {802          var removed = -1;803          for (var i = 0; i < this.watchIntervals.length; i++) {804            if (this.watchIntervals[i].watchId === watchId) {805              $interval.cancel(watchIntervals[i].interval);806              removed = i;807              break;808            }809          }810          if (removed !== -1) {811            this.watchIntervals.splice(removed, 1);812          }813        }814      } else {815        defer.reject('Unable to clear watch. No watch ID provided.');816      }817      return defer.promise;818    }819  };820}]);821/**822 * @ngdoc service823 * @name ngCordovaMocks.cordovaDialogs824 *825 * @description826 * A service for testing dialogs827 * in an app build with ngCordova.828 */829ngCordovaMocks.factory('$cordovaDialogs', ['$q', function ($q) {830  var dialogText = false;831  var dialogTitle = '';832  var defaultValue = '';833  var promptResponse = '';834  var beepCount = 0;835  var useHostAbilities = true;836  return {837    /**838     @ngdoc property839     @name dialogText840     @propertyOf ngCordovaMocks.cordovaDialogs841     @description842     The main content in the dialog.843     This property should only be used in automated tests.844     */845    dialogText: dialogText,846    /**847     @ngdoc property848     @name dialogTitle849     @propertyOf ngCordovaMocks.cordovaDialogs850     @description851     The title of the dialog.852     This property should only be used in automated tests.853     */854    dialogTitle: dialogTitle,855    /**856     @ngdoc property857     @name defaultValue858     @propertyOf ngCordovaMocks.cordovaDialogs859     @description860     The default value to be used in a prompt.861     This property should only be used in automated tests.862     */863    defaultValue: defaultValue,864    /**865     @ngdoc property866     @name promptResponse867     @propertyOf ngCordovaMocks.cordovaDialogs868     @description869     Used to simulate a user's response to a prompt.870     This property should only be used in automated tests.871     */872    promptResponse: promptResponse,873    /**874     @ngdoc property875     @name buttonLabels876     @propertyOf ngCordovaMocks.cordovaDialogs877     @description878     An array of the text of each button in the dialog.879     This property should only be used in automated tests.880     */881    buttonLabels: [],882    /**883     @ngdoc property884     @name beepCount885     @propertyOf ngCordovaMocks.cordovaDialogs886     @description887     The number of times a beep has occurred.888     This property should only be used in automated tests.889     */890    beepCount: beepCount,891    /**892     @ngdoc property893     @name useHostAbilities894     @propertyOf ngCordovaMocks.cordovaDialogs895     @description896     A flag that signals whether or not to try and use the host's897     (browser or otherwise) prompting capabilities.898     This property should only be used in automated tests.899     */900    useHostAbilities: useHostAbilities,901    alert: function (message, title, buttonName) {902      var d = $q.defer();903      if (this.useHostAbilities) {904        // NOTE: The window.alert method doesn't support a title or callbacks.905        alert(message);906        d.resolve();907      } else {908        this.dialogText = message;909        this.dialogTitle = title;910        this.buttonLabels.push(buttonName);911        d.resolve();912      }913      return d.promise;914    },915    confirm: function (message, title, buttonName) {916      var d = $q.defer();917      if (this.useHostAbilities) {918        // NOTE: The window.confirm method doesn't support a title or custom button naming.919        var result = confirm(message);920        d.resolve(result ? 2 : 1);921      } else {922        this.dialogText = message;923        this.dialogTitle = title;924        this.buttonLabels.push(buttonName);925        d.resolve(0);926      }927      return d.promise;928    },929    prompt: function (message, title, buttonLabels, defaultText) {930      var d = $q.defer();931      if (this.useHostAbilities) {932        // NOTE: The window.prompt method doesn't support a title or custom button naming.933        var result = prompt(message, defaultText);934        d.resolve(result);935      } else {936        this.dialogText = message;937        this.dialogTitle = title;938        this.defaultValue = defaultText;939        for (var i = 0; i < buttonLabels.length; i++) {940          this.buttonLabels.push(buttonLabels[i]);941        }942        d.resolve(this.promptResponse);943      }944      return d.promise;945    },946    beep: function (times) {947      this.beepCount = times;948    }949  };950}]);951/**952 * @ngdoc service953 * @name ngCordovaMocks.cordovaFacebook954 *955 * @description956 * A service for testing Facebook features957 * in an app built with ngCordova.958 **/959ngCordovaMocks.factory('$cordovaFacebook', ['$q', function ($q) {960  return {961    /**962     * These properties are here for the purpose of automated testing only.963     **/964    loginShouldSucceedWith: null,965    showDialogShouldSucceedWith: null,966    apiShouldSucceedWith: null,967    getAccessTokenShouldSucceedWith: null,968    getLoginStatusShouldSucceedWith: null,969    logoutShouldSuceedWith: null,970    login: function (permissions) {971      if (this.loginShouldSucceedWith !== null) {972        return $q.when(this.loginShouldSucceedWith);973      } else {974        return $q.reject();975      }976    },977    showDialog: function (options) {978      if (this.showDialogShouldSucceedWith !== null) {979        return $q.when(this.showDialogShouldSucceedWith);980      } else {981        return $q.reject();982      }983    },984    api: function (path, permissions) {985      if (this.apiShouldSucceedWith !== null) {986        return $q.when(this.apiShouldSucceedWith);987      } else {988        return $q.reject();989      }990    },991    getAccessToken: function () {992      if (this.getAccessTokenShouldSucceedWith !== null) {993        return $q.when(this.getAccessTokenShouldSucceedWith);994      } else {995        return $q.reject();996      }997    },998    getLoginStatus: function () {999      if (this.getLoginStatusShouldSucceedWith !== null) {1000        return $q.when(this.getLoginStatusShouldSucceedWith);1001      } else {1002        return $q.reject();1003      }1004    },1005    logout: function () {1006      if (this.logoutShouldSuceedWith !== null) {1007        return $q.when(this.logoutShouldSuceedWith);1008      } else {1009        return $q.reject();1010      }1011    }1012  };1013}]);1014/**1015 * @ngdoc service1016 * @name ngCordovaMocks.cordovaFile1017 *1018 * @description1019 * A service for testing interaction with device directories and files1020 * in an app build with ngCordova.1021 */1022ngCordovaMocks.factory('$cordovaFile', ['$q', function ($q) {1023  var throwsError = false;1024  var fileSystem = {};1025  var shouldMockFiles = false;1026  var files = {};1027  var mockIt = function (errorMessage) {1028    var defer = $q.defer();1029    if (this.throwsError) {1030      defer.reject(errorMessage);1031    } else {1032      defer.resolve();1033    }1034    return defer.promise;1035  };1036  return {1037    /**1038     * @ngdoc property1039     * @name throwsError1040     * @propertyOf ngCordovaMocks.cordovaFile1041     *1042     * @description1043     * A flag that signals whether a promise should be rejected or not.1044     * This property should only be used in automated tests.1045     **/1046    throwsError: throwsError,1047    /**1048     * @ngdoc property1049     * @name fileSystem1050     * @propertyOf ngCordovaMocks.cordovaFile1051     *1052     * @description1053     * A fake, in-memory file system. This is incomplete at this time.1054     * This property should only be used in automated tests.1055     **/1056    fileSystem: fileSystem,1057    /**1058     * @ngdoc property1059     * @name shouldMockFiles1060     * @propertyOf ngCordovaMocks.cordovaFile1061     *1062     * @description1063     * A flag that signals whether one wish to mock files.1064     * This is useful if you need mocks specific file scenarios.1065     * This property should only be used in automated tests.1066     **/1067    shouldMockFiles: shouldMockFiles,1068    /**1069     * @ngdoc property1070     * @name files1071     * @propertyOf ngCordovaMocks.cordovaFile1072     *1073     * @description1074     * An object that may be used for mocking files on the device.1075     * This property should only be used in automated tests.1076     *1077     * **/1078    files: files,1079    checkDir: function (directory) {1080      if (this.shouldMockFiles) {1081        var defer = $q.defer();1082        if (this.files[directory] && !this.files[directory].isFile) {1083          defer.resolve();1084        } else {1085          defer.reject();1086        }1087        return defer.promise;1088      }1089      return mockIt.call(this, 'There was an error checking the directory.');1090    },1091    createDir: function (directory, overwrite) {1092      if (this.shouldMockFiles) {1093        var defer = $q.defer();1094        this.files[directory] = {isFile: false};1095        defer.resolve();1096        return defer.promise;1097      }1098      return mockIt.call(this, 'There was an error creating the directory.');1099    },1100    listDir: function (filePath) {1101      return mockIt.call(this, 'There was an error listing the directory');1102    },1103    checkFile: function (filePath) {1104      if (this.shouldMockFiles) {1105        var defer = $q.defer();1106        if (this.files[filePath] && this.files[filePath].isFile) {1107          defer.resolve();1108        } else {1109          defer.reject();1110        }1111        return defer.promise;1112      }1113      return mockIt.call(this, 'There was an error checking for the file.');1114    },1115    createFile: function (filePath, overwrite) {1116      if (this.shouldMockFiles) {1117        var defer = $q.defer();1118        this.files[filePath] = {1119          isFile: true,1120          fileContent: ''1121        };1122        defer.resolve();1123        return defer.promise;1124      }1125      return mockIt.call(this, 'There was an error creating the file.');1126    },1127    removeFile: function (directory, file) {1128      return mockIt.call(this, 'There was an error removng the file.');1129    },1130    writeFile: function (filePath, data, options) {1131      if (this.shouldMockFiles && filePath && data) {1132        this.files[filePath] = {1133          isFile: true,1134          fileContent: data1135        };1136      }1137      return mockIt.call(this, 'There was an error writing the file.');1138    },1139    readFile: function (filePath) {1140      return this.readAsText(filePath);1141    },1142    readAsText: function (filePath) {1143      if (this.shouldMockFiles) {1144        var defer = $q.defer();1145        if (files[filePath] && files[filePath].isFile) {1146          defer.resolve(files[filePath].fileContent);1147        } else {1148          defer.reject();1149        }1150        return defer.promise;1151      }1152      return mockIt.call(this, 'There was an error reading the file as text.');1153    },1154    readAsDataURL: function (filePath) {1155      return mockIt.call(this, 'There was an error reading the file as a data url.');1156    },1157    readAsBinaryString: function (filePath) {1158      return mockIt.call(this, 'There was an error reading the file as a binary string.');1159    },1160    readAsArrayBuffer: function (filePath) {1161      return mockIt.call(this, 'There was an error reading the file as an array buffer.');1162    },1163    readFileMetadata: function (filePath) {1164      return mockIt.call(this, 'There was an error reading the file metadata');1165    },1166    readFileAbsolute: function (filePath) {1167      return mockIt.call(this, 'There was an error reading the file from the absolute path');1168    },1169    readFileMetadataAbsolute: function (filePath) {1170      return mockIt.call(this, 'There was an error reading the file metadta from the absolute path');1171    }1172  };1173}]);1174/**1175 * @ngdoc service1176 * @name ngCordovaMocks.cordovaFileOpener21177 *1178 * @description1179 * A service for testing fileOpener21180 * in an app build with ngCordova.1181 */1182ngCordovaMocks.factory('$cordovaFileOpener2', ['$q', function ($q) {1183  var throwsError = false;1184  return {1185    /**1186     * @ngdoc property1187     * @name throwsError1188     * @propertyOf ngCordovaMocks.cordovaFileOpener21189     *1190     * @description1191     * A flag that signals whether a promise should be rejected or not.1192     * This property should only be used in automated tests.1193     **/1194    throwsError: throwsError,1195    open: function (file, type) {1196      var defer = $q.defer();1197      if (this.throwError) {1198        defer.reject({1199          status: 0,1200          message: 'There was an error capturing the file.'1201        });1202      } else {1203        defer.resolve();1204      }1205      return defer.promise;1206    },1207    uninstall: function (pack) {1208      var defer = $q.defer();1209      if (this.throwError) {1210        defer.reject({1211          status: 0,1212          message: 'There was an error capturing the packageId.'1213        });1214      } else {1215        defer.resolve();1216      }1217      return defer.promise;1218    },1219    appIsInstalled: function (pack) {1220      var defer = $q.defer();1221      if (this.throwError) {1222        defer.reject({1223          status: 0,1224          message: 'There was an error capturing the packageId.'1225        });1226      } else {1227        defer.resolve();1228      }1229      return defer.promise;1230    }1231  };1232}]);1233/**1234 * @ngdoc service1235 * @name ngCordovaMocks.cordovaFileTransfer1236 *1237 * @description1238 * A service for testing download and upload1239 * in an app build with ngCordova.1240 */1241ngCordovaMocks.factory('$cordovaFileTransfer', ['$q', function ($q) {1242    var throwsError = false;1243    var mockIt = function (errorMessage) {1244        var defer = $q.defer();1245        if (this.throwsError) {1246            defer.reject(errorMessage);1247        } else {1248            defer.resolve();1249        }1250        return defer.promise;1251    };1252    return {1253        /**1254         * @ngdoc property1255         * @name throwsError1256         * @propertyOf ngCordovaMocks.cordovaFileTransfer1257         *1258         * @description1259         * A flag that signals whether a promise should be rejected or not.1260         * This property should only be used in automated tests.1261         **/1262        throwsError: throwsError,1263        download: function (source, filePath, trust, options) {1264            return mockIt.call(this, 'There was an error downloading the file.');1265        },1266        upload: function (server, filePath, options) {1267            return mockIt.call(this, 'There was an error uploading the file.'); 1268        }1269    };1270}]);1271/**1272 * @ngdoc service1273 * @name ngCordovaMocks.cordovaGeolocation1274 *1275 * @description1276 * A service for testing location services1277 * in an app build with ngCordova.1278 */1279ngCordovaMocks.factory('$cordovaGeolocation', ['$interval', '$q', function ($interval, $q) {1280  var throwsError = false;1281  var useHostAbilities = true;1282  var watchIntervals = [];1283  var locations = [];1284  var currentPosition = null;1285  var nextPosition = null;1286  return {1287    /**1288     @ngdoc property1289     @name throwsError1290     @propertyOf ngCordovaMocks.cordovaGeolocation1291     @description1292     A flag that signals whether a promise should be rejected or not.1293     This property should only be used in automated tests.1294     */1295    throwsError: throwsError,1296    /**1297     @ngdoc property1298     @name watchIntervals1299     @propertyOf ngCordovaMocks.cordovaGeolocation1300     @description1301     The collection of watchers that are currently active.1302     This property should only be used in automated tests.1303     */1304    watchIntervals: watchIntervals,1305    /**1306     @ngdoc property1307     @name locations1308     @propertyOf ngCordovaMocks.cordovaGeolocation1309     @description1310     The collection of 'locations' that have been logged.1311     This property should only be used in automated tests.1312     */1313    locations: locations,1314    /**1315     @ngdoc property1316     @name currentPosition1317     @propertyOf ngCordovaMocks.cordovaGeolocation1318     @description1319     The last location logged.1320     This property should only be used in automated tests.1321     */1322    currentPosition: currentPosition,1323    /**1324     @ngdoc property1325     @name nextPosition1326     @propertyOf ngCordovaMocks.cordovaGeolocation1327     @description1328     The position to be logged the next time that a watcher1329     gets the location.1330     This property should only be used in automated tests.1331     */1332    nextPosition: nextPosition,1333    /**1334     @ngdoc property1335     @name useHostAbilities1336     @propertyOf ngCordovaMocks.cordovaGeolocation1337     @description1338     A flag that signals whether or not to try and use the host's1339     (browser or otherwise) geolocation capabilities.1340     This property should only be used in automated tests.1341     */1342    useHostAbilities: useHostAbilities,1343    getCurrentPosition: function (options) {1344      var defer = $q.defer();1345      if (this.throwsError) {1346        defer.reject('There was an error getting the location.');1347      } else {1348        if (options) {1349          options = options;	// This is just to get by JSHint.1350        }1351        if (this.useHostAbilities) {1352          if (navigator.geolocation) {1353            navigator.geolocation.getCurrentPosition(1354              function (position) {1355                this.currentPosition = position;1356                defer.resolve(this.currentPosition);1357              },1358              function (error) {1359                defer.reject(error);1360              }1361            );1362          } else {1363            defer.reject('Geolocation is not supported by this browser.');1364          }1365        } else {1366          defer.resolve(this.currentPosition);1367        }1368      }1369      return defer.promise;1370    },1371    watchPosition: function (options) {1372      var defer = $q.defer();1373      var watchID = Math.floor((Math.random() * 1000000) + 1);1374      var self = this;1375      self.locations = [];1376      if (self.throwsError) {1377        defer.reject('There was an error getting the geolocation.');1378      } else {1379        var delay = 1000;1380        if (options && options.timeout) {1381          delay = options.timeout;1382        }1383        self.watchIntervals.push({1384          watchID: watchID,1385          interval: $interval(1386            function () {1387              if (self.throwsError) {1388                defer.reject('There was an error watching the geolocation.');1389              }1390              // Attempt to use nextPosition.1391              var result = self.nextPosition;1392              if (result === null) {1393                // Determine whether to use the host's geolocation capabilities or not1394                if (self.useHostAbilities) {1395                  if (navigator.geolocation) {1396                    navigator.geolocation.getCurrentPosition(1397                      function (position) {1398                        self.currentPosition = position;1399                        self.locations.push(position);1400                        defer.resolve(position);1401                      },1402                      function (error) {1403                        defer.reject(error);1404                      }1405                    );1406                  } else {1407                    defer.reject('Geolocation is not supported by this browser.');1408                  }1409                } else {1410                  result = {1411                    coords: {1412                      latitude: ((Math.random() * 180) + 1) - 90,1413                      longitude: ((Math.random() * 360) + 1) - 180,1414                      altitude: ((Math.random() * 100) + 1),1415                      accuracy: ((Math.random() * 10) + 1),1416                      altitudeAccuracy: ((Math.random() * 10) + 1),1417                      heading: ((Math.random() * 360) + 1),1418                      speed: ((Math.random() * 100) + 1)1419                    },1420                    timestamp: Date.now()1421                  };1422                  self.currentPosition = result;1423                  self.locations.push(result);1424                  defer.notify(result);1425                }1426              }1427            },1428            delay1429          )1430        });1431      }1432      var cancel = function (id) {1433        var removed = -1;1434        for (var i = 0; i < self.watchIntervals.length; i++) {1435          if (self.watchIntervals[i].watchID === id) {1436            $interval.cancel(watchIntervals[i].interval);1437            removed = i;1438            break;1439          }1440        }1441        if (removed !== -1) {1442          self.watchIntervals.splice(removed, 1);1443        }1444      };1445      defer.promise.cancel = function () {1446        cancel(watchID);1447      };1448      defer.promise.clearWatch = function (id) {1449        cancel(id || watchID);1450      };1451      defer.promise.watchID = watchID;1452      return defer.promise;1453    },1454    clearWatch: function (watchID) {1455      var defer = $q.defer();1456      if (watchID) {1457        if (this.throwsError) {1458          defer.reject('Unable to clear watch.');1459        } else {1460          var removed = -1;1461          for (var i = 0; i < this.watchIntervals.length; i++) {1462            if (this.watchIntervals[i].watchID === watchID) {1463              $interval.cancel(watchIntervals[i].interval);1464              removed = i;1465              break;1466            }1467          }1468          if (removed !== -1) {1469            this.watchIntervals.splice(removed, 1);1470          }1471        }1472      } else {1473        defer.reject('Unable to clear watch. No watch ID provided.');1474      }1475      return defer.promise;1476    }1477  };1478}]);1479/**1480 * @ngdoc service1481 * @name ngCordovaMocks.cordovaGlobalization1482 *1483 * @description1484 * A service for testing features related to a user's locale and timezone.1485 * in an app build with ngCordova.1486 */1487ngCordovaMocks.factory('$cordovaGlobalization', ['$q', function ($q) {1488  var throwsError = false;1489  var language = (navigator.language) ? navigator.language : 'en-US';1490  var preferredLanguage = {value: language};1491  var firstDayOfWeek = 'Sunday';1492  var localeName = {value: language};1493  return {1494    /**1495     * @ngdoc property1496     * @name throwsError1497     * @propertyOf ngCordovaMocks.cordovaGlobalization1498     *1499     * @description1500     * A flag that signals whether a promise should be rejected or not.1501     * This property should only be used in automated tests.1502     **/1503    throwsError: throwsError,1504    /**1505     * @ngdoc property1506     * @name preferredLanguage1507     * @propertyOf ngCordovaMocks.cordovaGlobalization1508     *1509     * @description1510     * The user's preferred language.1511     * This property should only be used in automated tests.1512     **/1513    preferredLanguage: preferredLanguage,1514    /**1515     * @ngdoc property1516     * @name localeName1517     * @propertyOf ngCordovaMocks.cordovaGlobalization1518     *1519     * @description1520     * The name of the user's locale.1521     * This property should only be used in automated tests.1522     **/1523    localeName: localeName,1524    /**1525     * @ngdoc property1526     * @name firstDayOfWeek1527     * @propertyOf ngCordovaMocks.cordovaGlobalization1528     *1529     * @description1530     * The first day of the week based on the user's locale.1531     * This property should only be used in automated tests.1532     **/1533    firstDayOfWeek: firstDayOfWeek,1534    getPreferredLanguage: function () {1535      var defer = $q.defer();1536      if (this.throwsError) {1537        defer.reject('There was an error getting the preferred language.');1538      } else {1539        defer.resolve(this.preferredLanguage);1540      }1541      return defer.promise;1542    },1543    getLocaleName: function () {1544      var defer = $q.defer();1545      if (this.throwsError) {1546        defer.reject('There was an error getting the locale name.');1547      } else {1548        defer.resolve(this.localeName);1549      }1550      return defer.promise;1551    },1552    getFirstDayOfWeek: function () {1553      var defer = $q.defer();1554      if (this.throwsError) {1555        defer.reject('There was an error getting the first day of week.');1556      } else {1557        defer.resolve(this.firstDayOfWeek);1558      }1559      return defer.promise;1560    },1561    dateToString: function (date, options) {1562      var defer = $q.defer();1563      if (this.throwsError) {1564        defer.reject('There was an error getting the string from the date.');1565      } else {1566        var result = '';1567        // TODO: Review1568        date = date;1569        options = options;1570        // END TODO: Review1571        defer.resolve(result);1572      }1573      return defer.promise;1574    },1575    stringToDate: function (dateString, options) {1576      var defer = $q.defer();1577      if (this.throwsError) {1578        defer.reject('There was an error getting the date from the string.');1579      } else {1580        var result = '';1581        // TODO: Review1582        dateString = dateString;1583        options = options;1584        // END TODO: Review1585        defer.resolve(result);1586      }1587      return defer.promise;1588    },1589    getDatePattern: function (options) {1590      var defer = $q.defer();1591      if (this.throwsError) {1592        defer.reject('There was an error getting the date pattern.');1593      } else {1594        var result = '';1595        // TODO: Review1596        options = options;1597        // END TODO: Review1598        defer.resolve(result);1599      }1600      return defer.promise;1601    },1602    getDateNames: function (options) {1603      var defer = $q.defer();1604      if (this.throwsError) {1605        defer.reject('There was an error getting the date names.');1606      } else {1607        var result = '';1608        // TODO: Review1609        options = options;1610        // END TODO: Review1611        defer.resolve(result);1612      }1613      return defer.promise;1614    },1615    isDayLightSavingsTime: function (date) {1616      var defer = $q.defer();1617      if (this.throwsError) {1618        defer.reject('There was an error getting if this is in daylight savings time mode.');1619      } else {1620        var result = '';1621        // TODO: Review1622        date = date;1623        // END TODO: Review1624        defer.resolve(result);1625      }1626      return defer.promise;1627    },1628    numberToString: function (number, options) {1629      var defer = $q.defer();1630      if (this.throwsError) {1631        defer.reject('There was an error convertng the number to a string.');1632      } else {1633        var result = '';1634        // TODO: Review1635        number = number;1636        options = options;1637        // END TODO: Review1638        defer.resolve(result);1639      }1640      return defer.promise;1641    },1642    stringToNumber: function (numberString, options) {1643      var defer = $q.defer();1644      if (this.throwsError) {1645        defer.reject('There was an error convertng the string to a number.');1646      } else {1647        var result = '';1648        // TODO: Review1649        options = options;1650        // END TODO: Review1651        defer.resolve(result);1652      }1653      return defer.promise;1654    },1655    getNumberPattern: function (options) {1656      var defer = $q.defer();1657      if (this.throwsError) {1658        defer.reject('There was an error convertng the string to a number.');1659      } else {1660        var result = '';1661        // TODO: Review1662        options = options;1663        // END TODO: Review1664        defer.resolve(result);1665      }1666      return defer.promise;1667    },1668    getCurrencyPattern: function (currencyCode) {1669      var defer = $q.defer();1670      if (this.throwsError) {1671        defer.reject('There was an error convertng the string to a number.');1672      } else {1673        var result = '';1674        // TODO: Review1675        currencyCode = currencyCode;1676        // END TODO: Review1677        defer.resolve(result);1678      }1679      return defer.promise;1680    }1681  };1682}]);1683/**1684 * @ngdoc service1685 * @name ngCordovaMocks.cordovaGoogleAnalytics1686 *1687 * @description1688 * A service for testing google analytics services1689 * in an app build with ngCordova.1690 */1691ngCordovaMocks.factory('$cordovaGoogleAnalytics', ['$q', function ($q) {1692  var throwsError = false;1693  var methods = {};1694  /**1695   * @ngdoc property1696   * @name throwsError1697   * @propertyOf ngCordovaMocks.cordovaGeolocation1698   *1699   * @description1700   * A flag that signals whether a promise should be rejected or not.1701   * This property should only be used in automated tests.1702   **/1703  methods.throwsError = throwsError;1704  var methodsName = [1705    'startTrackerWithId',1706    'setUserId',1707    'debugMode',1708    'trackView',1709    'addCustomDimension',1710    'trackEvent',1711    'trackException',1712    'trackTiming',1713    'addTransaction',1714    'addTransactionItem'1715  ];1716  methodsName.forEach(function (funcName) {1717    methods[funcName] = function () {1718      var defer = $q.defer();1719      (this.throwsError) ?1720        defer.reject() :1721        defer.resolve();1722      return defer.promise;1723    };1724  });1725  return methods;1726}]);1727'use strict';1728/**1729 * @ngdoc service1730 * @name ngCordovaMocks.googlePlayGame1731 *1732 * @description1733 * A service for testing Google Play Game features1734 * in an app build with ngCordova.1735 */1736ngCordovaMocks.factory('$cordovaGooglePlayGame', ['$q', function ($q) {1737  var throwsError = false;1738  var isSignedIn = false;1739  var displayName = '';1740  return {1741    /**1742     * @ngdoc property1743     * @name _throwsError1744     * @propertyOf ngCordovaMocks.googlePlayGame1745     *1746     * @description1747     * A flag that signals whether a promise should be rejected or not.1748     * This property should only be used in automated tests.1749     **/1750    _throwsError: throwsError,1751    /**1752     * @ngdoc property1753     * @name _isSignedIn1754     * @propertyOf ngCordovaMocks.googlePlayGame1755     *1756     * @description1757     * A flag that signals whether a promise should be rejected or not.1758     * This property should only be used in automated tests.1759     **/1760    _isSignedIn: isSignedIn,1761    /**1762     * @ngdoc property1763     * @name _displayName1764     * @propertyOf ngCordovaMocks.googlePlayGame1765     *1766     * @description1767     * A flag that signals whether a promise should be rejected or not.1768     * This property should only be used in automated tests.1769     **/1770    _displayName: displayName,1771    auth: function () {1772      var defer = $q.defer();1773      if (this._throwsError) {1774        defer.reject('There was a auth error.');1775      } else {1776        this.isSignedIn = true;1777        defer.resolve('SIGN IN SUCCESS');1778      }1779      return defer.promise;1780    },1781    signout: function () {1782      var defer = $q.defer();1783      if (this.throwsError) {1784        defer.reject('There was a signout error.');1785      } else {1786        defer.resolve();1787      }1788      return defer.promise;1789    },1790    isSignedIn: function () {1791      var defer = $q.defer();1792      if (this._throwsError) {1793        defer.reject('There was a isSignedIn error.');1794      } else {1795        defer.resolve({1796          'isSignedIn': this._isSignedIn1797        });1798      }1799      return defer.promise;1800    },1801    showPlayer: function () {1802      var defer = $q.defer();1803      if (this.throwsError) {1804        defer.reject('There was a showPlayer error.');1805      } else {1806        defer.resolve({1807          'displayName': this._displayName1808        });1809      }1810      return defer.promise;1811    },1812    submitScore: function (data) {1813      var defer = $q.defer();1814      if (this._throwsError) {1815        defer.reject('There was a submitScore error.');1816      } else {1817        defer.resolve('OK');1818      }1819      return defer.promise;1820    },1821    showAllLeaderboards: function () {1822      var defer = $q.defer();1823      if (this.throwsError) {1824        defer.reject('There was a showAllLeaderboards error.');1825      } else {1826        defer.resolve('OK');1827      }1828      return defer.promise;1829    },1830    showLeaderboard: function (data) {1831      var defer = $q.defer();1832      if (this._throwsError) {1833        defer.reject('There was a showLeaderboard error.');1834      } else {1835        defer.resolve('OK');1836      }1837      return defer.promise;1838    },1839    unlockAchievement: function (data) {1840      var defer = $q.defer();1841      if (this.throwsError) {1842        defer.reject('There was a unlockAchievement error.');1843      } else {1844        defer.resolve('OK');1845      }1846      return defer.promise;1847    },1848    incrementAchievement: function (data) {1849      var defer = $q.defer();1850      if (this._throwsError) {1851        defer.reject('There was a incrementAchievement error.');1852      } else {1853        defer.resolve('OK');1854      }1855      return defer.promise;1856    },1857    showAchievements: function () {1858      var defer = $q.defer();1859      if (this.throwsError) {1860        defer.reject('There was a showAchievements error.');1861      } else {1862        defer.resolve('OK');1863      }1864      return defer.promise;1865    }1866  };1867}]);1868/**1869 * @ngdoc service1870 * @name ngCordovaMocks.cordovaKeyboard1871 *1872 * @description1873 * A service for testing device keyboard features1874 * in an app build with ngCordova.1875 **/1876ngCordovaMocks.factory('$cordovaKeyboard', function () {1877  var isVisible = false;1878  return {1879    hideAccessoryBar: function (bool) {1880    },1881    close: function () {1882      isVisible = false;1883    },1884    show: function () {1885      isVisible = true;1886    },1887    disableScroll: function (bool) {1888    },1889    isVisible: function () {1890      return isVisible;1891    }1892  };1893});1894/**1895 * @ngdoc service1896 * @name ngCordovaMocks.cordovaKeychain1897 *1898 * @description1899 * A service for testing Keychain features1900 * in an app built with ngCordova.1901 **/1902ngCordovaMocks.factory('$cordovaKeychain', ['$q', function ($q) {1903  var keychains = {};1904  return {1905    /**1906     * @ngdoc property1907     * @name keychains1908     * @propertyOf ngCordovaMocks.cordovaKeychain1909     *1910     * @description1911     * The collection of 'keychains' that have been saved.1912     * This property should only be used in automated tests.1913     **/1914    keychains: keychains,1915    getForKey: function (key, serviceName) {1916      var defer = $q.defer();1917      if (this.keychains[serviceName]) {1918        defer.resolve(this.keychains[serviceName][key]);1919      } else {1920        defer.reject();1921      }1922      return defer.promise;1923    },1924    setForKey: function (key, serviceName, value) {1925      var defer = $q.defer();1926      if (!this.keychains[serviceName]) {1927        this.keychains[serviceName] = {};1928      }1929      this.keychains[serviceName][key] = value;1930      defer.resolve();1931      return defer.promise;1932    },1933    removeForKey: function (key, serviceName) {1934      var defer = $q.defer();1935      if (this.keychains[serviceName]) {1936        delete this.keychains[serviceName][key];1937      }1938      defer.resolve();1939      return defer.promise;1940    }1941  };1942}]);1943/**1944 * @ngdoc service1945 * @name ngCordovaMocks.cordovaNetwork1946 *1947 * @description1948 * A service for testing networked fetures1949 * in an app build with ngCordova.1950 */1951ngCordovaMocks.factory('$cordovaNetwork', function () {1952  var connectionType = 'WiFi connection';1953  var isConnected = true;1954  return {1955    /**1956     * @ngdoc property1957     * @name connectionType1958     * @propertyOf ngCordovaMocks.cordovaNetwork1959     *1960     * @description1961     * They type of connection. Values should match those found at1962     * https://github.com/apache/cordova-plugin-network-information1963     * This property should only be used in automated tests.1964     **/1965    connectionType: connectionType,1966    /**1967     * @ngdoc property1968     * @name isConnected1969     * @propertyOf ngCordovaMocks.cordovaNetwork1970     *1971     * @description1972     * A flag that signals whether the app is connected to a network.1973     * This property should only be used in automated tests.1974     **/1975    isConnected: isConnected,1976    getNetwork: function () {1977      return this.connectionType;1978    },1979    isOnline: function () {1980      return this.isConnected;1981    },1982    isOffline: function () {1983      return !this.isConnected;1984    }1985  };1986});1987'use strict';1988/**1989 * @ngdoc service1990 * @name ngCordovaMocks.cordovaPush1991 *1992 * @description1993 * A service for testing push notifications features1994 * in an app build with ngCordova.1995 */1996ngCordovaMocks.factory('$cordovaPush', ['$q', '$timeout', '$rootScope', function ($q, $timeout, $rootScope) {1997  var throwsError = false;1998  var deviceToken = '';1999  return {2000    /**2001     * @ngdoc property2002     * @name throwsError2003     * @propertyOf ngCordovaMocks.cordovaPush2004     *2005     * @description2006     * A flag that signals whether a promise should be rejected or not.2007     * This property should only be used in automated tests.2008     **/2009    throwsError: throwsError,2010    /**2011     * @ngdoc property2012     * @name deviceToken2013     * @propertyOf ngCordovaMocks.cordovaPush2014     *2015     * @description2016     * Token send when service register device2017     * This property should only be used in automated tests.2018     **/2019    deviceToken: deviceToken,2020    onNotification: function (notification) {2021      $timeout(function () {2022        $rootScope.$broadcast('$cordovaPush:notificationReceived', notification);2023      });2024    },2025    register: function (config) {2026      var _self = this;2027      var defer = $q.defer();2028      if (config !== undefined && config.ecb === undefined) {2029        config.ecb = this.onNotification;2030      }2031      if (this.throwsError) {2032        defer.reject('There was a register error.');2033      } else {2034        defer.resolve(this.deviceToken);2035        if (config && config.ecb) {2036          config.ecb({2037            event: 'registered',2038            regid: _self.deviceToken2039          });2040        }2041      }2042      return defer.promise;2043    },2044    unregister: function (options) {2045      var defer = $q.defer();2046      if (this.throwsError) {2047        defer.reject('There was a register error.');2048      } else {2049        defer.resolve();2050      }2051      return defer.promise;2052    },2053  };2054}]);2055/**2056 * @ngdoc service2057 * @name ngCordovaMocks.cordovaSocialSharing2058 *2059 * @description2060 * A service for testing via social services2061 * in an app build with ngCordova.2062 */2063ngCordovaMocks.factory('$cordovaSocialSharing', ['$q', function ($q) {2064  var throwsError = false;2065  var message = '';2066  var image = '';2067  var link = '';2068  var number = '';2069  var socialService = '';2070  var subject = '';2071  var toAddresses = [];2072  var bccAddresses = [];2073  var attachments = [];2074  return {2075    /**2076     * @ngdoc property2077     * @name throwsError2078     * @propertyOf ngCordovaMocks.cordovaSocialSharing2079     *2080     * @description2081     * A flag that signals whether a promise should be rejected or not.2082     * This property should only be used in automated tests.2083     **/2084    throwsError: throwsError,2085    /**2086     * @ngdoc property2087     * @name message2088     * @propertyOf ngCordovaMocks.cordovaSocialSharing2089     *2090     * @description2091     * The message to be shared via a social service.2092     * This property should only be used in automated tests.2093     **/2094    message: message,2095    /**2096     * @ngdoc property2097     * @name image2098     * @propertyOf ngCordovaMocks.cordovaSocialSharing2099     *2100     * @description2101     * An image to be shared via a social service.2102     * This property should only be used in automated tests.2103     **/2104    image: image,2105    /**2106     * @ngdoc property2107     * @name link2108     * @propertyOf ngCordovaMocks.cordovaSocialSharing2109     *2110     * @description2111     * A link to be shared via a social service.2112     * This property should only be used in automated tests.2113     **/2114    link: link,2115    /**2116     * @ngdoc property2117     * @name number2118     * @propertyOf ngCordovaMocks.cordovaSocialSharing2119     *2120     * @description2121     * A comma-delimited list of phone numbers to send a social message to.2122     * This property should only be used in automated tests.2123     **/2124    number: number,2125    /**2126     * @ngdoc property2127     * @name subject2128     * @propertyOf ngCordovaMocks.cordovaSocialSharing2129     *2130     * @description2131     * The subject of an email.2132     * This property should only be used in automated tests.2133     **/2134    subject: subject,2135    /**2136     * @ngdoc property2137     * @name toAddresses2138     * @propertyOf ngCordovaMocks.cordovaSocialSharing2139     *2140     * @description2141     * An array of email addresses to send an email to.2142     * This property should only be used in automated tests.2143     **/2144    toAddresses: toAddresses,2145    /**2146     * @ngdoc property2147     * @name bccAddresses2148     * @propertyOf ngCordovaMocks.cordovaSocialSharing2149     *2150     * @description2151     * An array of email addresses to blind carbon-copy an email to.2152     * This property should only be used in automated tests.2153     **/2154    bccAddresses: bccAddresses,2155    /**2156     * @ngdoc property2157     * @name socialService2158     * @propertyOf ngCordovaMocks.cordovaSocialSharing2159     *2160     * @description2161     * The name of a social service to share content through.2162     * This property should only be used in automated tests.2163     **/2164    socialService: socialService,2165    /**2166     * @ngdoc property2167     * @name attachments2168     * @propertyOf ngCordovaMocks.cordovaSocialSharing2169     *2170     * @description2171     * An array of attachments to include with an email to be sent.2172     * This property should only be used in automated tests.2173     **/2174    attachments: attachments,2175    shareViaTwitter: function (message, image, link) {2176      var defer = $q.defer();2177      if (this.throwsError) {2178        defer.reject('There was an error sharing via Twitter.');2179      } else {2180        this.message = message;2181        this.image = image;2182        this.link = link;2183        defer.resolve();2184      }2185      return defer.promise;2186    },2187    shareViaWhatsApp: function (message, image, link) {2188      var defer = $q.defer();2189      if (this.throwsError) {2190        defer.reject('There was an error sharing via WhatsApp.');2191      } else {2192        this.message = message;2193        this.image = image;2194        this.link = link;2195        defer.resolve();2196      }2197      return defer.promise;2198    },2199    shareViaFacebook: function (message, image, link) {2200      var defer = $q.defer();2201      if (this.throwsError) {2202        defer.reject('There was an error sharing via Facebook.');2203      } else {2204        this.message = message;2205        this.image = image;2206        this.link = link;2207        defer.resolve();2208      }2209      return defer.promise;2210    },2211    shareViaSMS: function (message, number) {2212      var defer = $q.defer();2213      if (this.throwsError) {2214        defer.reject('There was an error sharing via SMS.');2215      } else {2216        this.message = message;2217        this.number = number;2218        defer.resolve();2219      }2220      return defer.promise;2221    },2222    shareViaEmail: function (message, subject, toArr, bccArr, file) {2223      var defer = $q.defer();2224      if (this.throwsError) {2225        defer.reject('There was an error sharing via SMS.');2226      } else {2227        // These are added to get by JSHINT for now2228        this.message = message;2229        this.subject = subject;2230        this.toAddresses = toArr;2231        this.bccAddressesc = bccArr;2232        this.attachments = file;2233        defer.resolve();2234      }2235      return defer.promise;2236    },2237    canShareViaEmail: function () {2238      var defer = $q.defer();2239      if (this.throwsError) {2240        defer.reject(false);2241      } else {2242        defer.resolve(true);2243      }2244      return defer.promise;2245    },2246    canShareVia: function (via, message, subject, file, link) {2247      var defer = $q.defer();2248      if (this.throwsError) {2249        defer.reject('There was an error sharing via SMS.');2250      } else {2251        // These are added to get by JSHINT for now2252        this.message = message;2253        this.socialService = via;2254        this.subject = subject;2255        this.attachments = file;2256        this.link = link;2257        defer.resolve();2258      }2259      return defer.promise;2260    },2261    shareVia: function (via, message, subject, file, link) {2262      var defer = $q.defer();2263      if (this.throwsError) {2264        defer.reject('There was an error sharing via SMS.');2265      } else {2266        this.socialService = via;2267        this.message = message;2268        this.subject = subject;2269        this.attachments = file;2270        this.link = link;2271        defer.resolve();2272      }2273      return defer.promise;2274    },2275    share: function (message, subject, file, link) {2276      var defer = $q.defer();2277      if (this.throwsError) {2278        defer.reject('There was an error sharing via SMS.');2279      } else {2280        this.message = message;2281        this.subject = subject;2282        this.attachments = file;2283        this.link = link;2284        defer.resolve();2285      }2286      return defer.promise;2287    }2288  };2289}]);2290/**2291 * @ngdoc service2292 * @name ngCordovaMocks.cordovaSplashscreen2293 *2294 * @description2295 * A service for testing the splash screen2296 * in an app build with ngCordova.2297 */2298ngCordovaMocks.factory('$cordovaSplashscreen', function () {2299  var isVisible = false;2300  return {2301    /**2302     * @ngdoc property2303     * @name isVisible2304     * @propertyOf ngCordovaMocks.cordovaSplashscreen2305     *2306     * @description2307     * A flag that signals whether the splash screen is visible or not.2308     * This property should only be used in automated tests.2309     **/2310    isVisible: isVisible,2311    hide: function () {2312      // do nothing. everything happens behind the scenes in this case.2313      // its a stub that is present for completeness.2314      this.isVisible = false;2315      return true;2316    },2317    show: function () {2318      // do nothing. everything happens behind the scenes in this case.2319      // its a stub that is present for completeness.2320      this.isVisible = true;2321      return true;2322    }2323  };2324});2325/**2326 * @ngdoc service2327 * @name ngCordovaMocks.cordovaStatusbar2328 *2329 * @description2330 * A service for testing the status bar2331 * in an app build with ngCordova.2332 */2333ngCordovaMocks.factory('$cordovaStatusbar', function () {2334  var isStatusBarVisible = true;2335  var canOverlayWebView = true;2336  return {2337    /**2338     * @ngdoc property2339     * @name isStatusBarVisible2340     * @propertyOf ngCordovaMocks.cordovaStatusbar2341     *2342     * @description2343     * A flag that signals whether the status bar is visible or not.2344     * This property should only be used in automated tests.2345     **/2346    isStatusBarVisible: isStatusBarVisible,2347    /**2348     * @ngdoc property2349     * @name canOverlayWebView2350     * @propertyOf ngCordovaMocks.cordovaStatusbar2351     *2352     * @description2353     * A flag that signals whether the status bar can overlay the web view.2354     * This property should only be used in automated tests.2355     **/2356    canOverlayWebView: canOverlayWebView,2357    overlaysWebView: function (bool) {2358      this.canOverlayWebView = bool;2359    },2360    style: function (style) {2361      // TODO: Review2362      return style;2363    },2364    styleHex: function (colorHex) {2365      // TODO: review2366      return colorHex;2367    },2368    styleColor: function (color) {2369      // TODO: review2370      return color;2371    },2372    hide: function () {2373      this.isStatusBarVisible = false;2374    },2375    show: function () {2376      this.isStatusBarVisible = true;2377    },2378    isVisible: function () {2379      return this.isStatusBarVisible;2380    }2381  };2382});2383/**2384 * @ngdoc service2385 * @name ngCordovaMocks.cordovaToast2386 *2387 * @description2388 * A service for testing toasts2389 * in an app build with ngCordova.2390 *2391 * @example2392 */2393ngCordovaMocks.factory('$cordovaToast', ['$q', function ($q) {2394  var throwsError = false;2395  return {2396    /**2397     * @ngdoc property2398     * @name throwsError2399     * @propertyOf ngCordovaMocks.cordovaToast2400     *2401     * @description2402     * A flag that signals whether a promise should be rejected or not.2403     * This property should only be used in automated tests.2404     **/2405    throwsError: throwsError,2406    showShortTop: function (message) {2407      var defer = $q.defer();2408      if (this.throwsError) {2409        defer.reject('There was an error showing the toast.');2410      } else {2411        defer.resolve();2412      }2413      return defer.promise;2414    },2415    showShortCenter: function (message) {2416      var defer = $q.defer();2417      if (this.throwsError) {2418        defer.reject('There was an error showing the toast.');2419      } else {2420        defer.resolve();2421      }2422      return defer.promise;2423    },2424    showShortBottom: function (message) {2425      var defer = $q.defer();2426      if (this.throwsError) {2427        defer.reject('There was an error showing the toast.');2428      } else {2429        defer.resolve();2430      }2431      return defer.promise;2432    },2433    showLongTop: function (message) {2434      var defer = $q.defer();2435      if (this.throwsError) {2436        defer.reject('There was an error showing the toast.');2437      } else {2438        defer.resolve();2439      }2440      return defer.promise;2441    },2442    showLongCenter: function (message) {2443      var defer = $q.defer();2444      if (this.throwsError) {2445        defer.reject('There was an error showing the toast.');2446      } else {2447        defer.resolve();2448      }2449      return defer.promise;2450    },2451    showLongBottom: function (message) {2452      var defer = $q.defer();2453      if (this.throwsError) {2454        defer.reject('There was an error showing the toast.');2455      } else {2456        defer.resolve();2457      }2458      return defer.promise;2459    },2460    show: function (message, duration, position) {2461      var defer = $q.defer();2462      if (this.throwsError) {2463        defer.reject('There was an error showing the toast.');2464      } else {2465        defer.resolve();2466      }2467      return defer.promise;2468    }2469  };2470}]);2471/**2472 * @ngdoc service2473 * @name ngCordovaMocks.cordovaVibration2474 *2475 * @description2476 * A service for testing vibration2477 * in an app build with ngCordova.2478 */2479ngCordovaMocks.factory('$cordovaVibration', ['$timeout', function ($timeout) {2480  var isVibrating = false;2481  var vibrateTimer = null;2482  return {2483    /**2484     * @ngdoc property2485     * @name vibrateTimer2486     * @propertyOf ngCordovaMocks.cordovaVibration2487     *2488     * @description2489     * Access to the timer associated with vibration.2490     * This property should only be used in automated tests.2491     **/2492    vibrateTimer: vibrateTimer,2493    /**2494     * @ngdoc property2495     * @name isVibrating2496     * @propertyOf ngCordovaMocks.cordovaVibration2497     *2498     * @description2499     * A flag that signals whether vibration is active.2500     * This property should only be used in automated tests.2501     **/2502    isVibrating: isVibrating,2503    vibrate: function (time) {2504      if (time > 0) {2505        this.isVibrating = true;2506        self = this;2507        if (time instanceof Array) {2508          // TODO: Implement pattern here.2509          // The following is a temporary timer that just looks at the first value2510          this.vibrateTimer = $timeout(2511            function () {2512              self.isVibrating = false;2513              self.vibrateTimer = null;2514            },2515            time[0]2516          );2517        } else {2518          this.vibrateTimer = $timeout(2519            function () {2520              self.isVibrating = false;2521              self.vibrateTimer = null;2522            },2523            time2524          );2525        }2526      }2527    },2528    /* jshint ignore:start */2529    vibrateWithPattern: function (pattern, repeat) {2530      // Based on the documentation (https://github.com/apache/cordova-plugin-vibration)2531      // This method is deprecated. For that reason, this isn't implemented at this time.2532    },2533    /* jshint ignore:end */2534    cancelVibration: function () {2535      if (this.vibrateTimer !== null) {2536        if (this.isVibrating === true) {2537          $timeout.cancel(this.vibrateTimer);2538          this.isVibrating = false;2539        }2540      }2541    }2542  };2543}]);...Using AI Code Generation
1import { ThrowsError } from "storybook-root-decorator";2import React from "react";3export default {4};5export const throwsError = () => {6  throw new Error("This is an error");7};8import { configure } from "@storybook/react";9import { setOptions } from "@storybook/addon-options";10import { addDecorator } from "@storybook/react";11import { ThrowsError } from "storybook-root-decorator";12addDecorator(ThrowsError);13setOptions({Using AI Code Generation
1import { ThrowsError } from 'storybook-root-decorator';2ThrowsError('error message');3ThrowsError('error message', 'error');4ThrowsError('error message', 'error', 'error');5ThrowsError('error message', 'error', 'error', 'error');6ThrowsError('error message', 'error', 'error', 'error', 'error');7ThrowsError('error message', 'error', 'error', 'error', 'error', 'error');8ThrowsError('error message', 'error', 'error', 'error', 'error', 'error', 'error');9ThrowsError('error message', 'error', 'error', 'error', 'error', 'error', 'error', 'error');10ThrowsError('error message', 'error', 'error', 'error', 'error', 'error', 'error', 'error', 'error');11ThrowsError('error message', 'error', 'error', 'error', 'error', 'error', 'error', 'error', 'error', 'error');12ThrowsError('error message', 'error', 'error', 'error', 'error', 'error', 'error', 'error', 'error', 'error', 'error');Using AI Code Generation
1import { ThrowsError } from '../index';2describe('ThrowsError', () => {3  it('should throw an error', () => {4    expect(() => ThrowsError()).to.throw('Throws an error');5  });6});7export function ThrowsError() {8  throw new Error('Throws an error');9}10{11  "devDependencies": {12  }13}14"resolutions": {15  }Using AI Code Generation
1import { ThrowsError } from 'storybook-root';2ThrowsError('Hello World');3import { ThrowsError } from 'storybook-root';4ThrowsError('Hello World');5import { ThrowsError } from 'storybook-root';6ThrowsError('Hello World');7import { ThrowsError } from 'storybook-root';8ThrowsError('Hello World');9import { ThrowsError } from 'storybook-root';10ThrowsError('Hello World');11import { ThrowsError } from 'storybook-root';12ThrowsError('Hello World');13import { ThrowsError } from 'storybook-root';14ThrowsError('Hello World');15import { ThrowsError } from 'storybook-root';16ThrowsError('Hello World');17import { ThrowsError } from 'storybook-root';18ThrowsError('Hello World');19import { ThrowsError } from 'storybook-root';20ThrowsError('Hello World');21import { ThrowsError } from 'storybook-root';22ThrowsError('Hello World');23import { ThrowsError } from 'storybook-root';24ThrowsError('Hello World');25import { ThrowsError } from 'storybook-root';26ThrowsError('Hello World');27import { ThrowsError } from 'storybook-root';28ThrowsError('Hello World');29import { ThrowsErrorUsing AI Code Generation
1import { ThrowsError } from 'storybook-root-addon';2export default {3};4export const Test = () => {5  ThrowsError('test');6  return <div>Test</div>;7};8import { configure, addDecorator, addParameters } from '@storybook/react';9import { withRoot } from 'storybook-root-addon';10import { withInfo } from '@storybook/addon-info';11import { withKnobs } from '@storybook/addon-knobs';12import { withA11y } from '@storybook/addon-a11y';13addDecorator(withRoot);14addDecorator(withKnobs);15addDecorator(withInfo);16addDecorator(withA11y);17addParameters({18  options: {19  },20});21configure(require.context('../src', true, /\.stories\.js$/), module);Using AI Code Generation
1import { ThrowsError } from 'storybook-root-provider';2const App = () => {3  return (4  );5};6export default App;7import React from 'react';8import { storiesOf } from '@storybook/react';9import App from './test';10storiesOf('App', module).add('App', () => <App />);Using AI Code Generation
1import { ThrowsError } from 'storybook-root';2import Component from './index';3ThrowsError(Component);4import { configure } from '@storybook/react';5import { setOptions } from '@storybook/addon-options';6import { setDefaults } from 'storybook-root';7setDefaults();8function loadStories() {9  require('../src/stories');10}11configure(loadStories, module);12const path = require('path');13module.exports = (baseConfig, env, defaultConfig) => {14  defaultConfig.module.rules.push({15    test: /\.(ts|tsx)$/,16    loader: require.resolve('awesome-typescript-loader'),17  });18  defaultConfig.resolve.extensions.push('.ts', '.tsx');19  defaultConfig.resolve.alias = {20    'storybook-root': path.resolve(__dirname, '../../'),21  };22  return defaultConfig;23};24import 'storybook-root/register';25{26  "scripts": {27  },28  "devDependencies": {29  },30}Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
