UNPKG

angular-mocks

Version:

AngularJS mocks for testing

1,571 lines (1,396 loc) 135 kB
/** * @license AngularJS v1.7.9 * (c) 2010-2018 Google, Inc. http://angularjs.org * License: MIT */ (function(window, angular) { 'use strict'; /* global routeToRegExp: true */ /** * @param {string} path - The path to parse. (It is assumed to have query and hash stripped off.) * @param {Object} opts - Options. * @return {Object} - An object containing an array of path parameter names (`keys`) and a regular * expression (`regexp`) that can be used to identify a matching URL and extract the path * parameter values. * * @description * Parses the given path, extracting path parameter names and a regular expression to match URLs. * * Originally inspired by `pathRexp` in `visionmedia/express/lib/utils.js`. */ function routeToRegExp(path, opts) { var keys = []; var pattern = path .replace(/([().])/g, '\\$1') .replace(/(\/)?:(\w+)(\*\?|[?*])?/g, function(_, slash, key, option) { var optional = option === '?' || option === '*?'; var star = option === '*' || option === '*?'; keys.push({name: key, optional: optional}); slash = slash || ''; return ( (optional ? '(?:' + slash : slash + '(?:') + (star ? '(.+?)' : '([^/]+)') + (optional ? '?)?' : ')') ); }) .replace(/([/$*])/g, '\\$1'); if (opts.ignoreTrailingSlashes) { pattern = pattern.replace(/\/+$/, '') + '/*'; } return { keys: keys, regexp: new RegExp( '^' + pattern + '(?:[?#]|$)', opts.caseInsensitiveMatch ? 'i' : '' ) }; } 'use strict'; /* global routeToRegExp: false */ /** * @ngdoc object * @name angular.mock * @description * * Namespace from 'angular-mocks.js' which contains testing related code. * */ angular.mock = {}; /** * ! This is a private undocumented service ! * * @name $browser * * @description * This service is a mock implementation of {@link ng.$browser}. It provides fake * implementation for commonly used browser apis that are hard to test, e.g. setTimeout, xhr, * cookies, etc. * * The api of this service is the same as that of the real {@link ng.$browser $browser}, except * that there are several helper methods available which can be used in tests. */ angular.mock.$BrowserProvider = function() { this.$get = [ '$log', '$$taskTrackerFactory', function($log, $$taskTrackerFactory) { return new angular.mock.$Browser($log, $$taskTrackerFactory); } ]; }; angular.mock.$Browser = function($log, $$taskTrackerFactory) { var self = this; var taskTracker = $$taskTrackerFactory($log); this.isMock = true; self.$$url = 'http://server/'; self.$$lastUrl = self.$$url; // used by url polling fn self.pollFns = []; // Task-tracking API self.$$completeOutstandingRequest = taskTracker.completeTask; self.$$incOutstandingRequestCount = taskTracker.incTaskCount; self.notifyWhenNoOutstandingRequests = taskTracker.notifyWhenNoPendingTasks; // register url polling fn self.onUrlChange = function(listener) { self.pollFns.push( function() { if (self.$$lastUrl !== self.$$url || self.$$state !== self.$$lastState) { self.$$lastUrl = self.$$url; self.$$lastState = self.$$state; listener(self.$$url, self.$$state); } } ); return listener; }; self.$$applicationDestroyed = angular.noop; self.$$checkUrlChange = angular.noop; self.deferredFns = []; self.deferredNextId = 0; self.defer = function(fn, delay, taskType) { var timeoutId = self.deferredNextId++; delay = delay || 0; taskType = taskType || taskTracker.DEFAULT_TASK_TYPE; taskTracker.incTaskCount(taskType); self.deferredFns.push({ id: timeoutId, type: taskType, time: (self.defer.now + delay), fn: fn }); self.deferredFns.sort(function(a, b) { return a.time - b.time; }); return timeoutId; }; /** * @name $browser#defer.now * * @description * Current milliseconds mock time. */ self.defer.now = 0; self.defer.cancel = function(deferId) { var taskIndex; angular.forEach(self.deferredFns, function(task, index) { if (task.id === deferId) taskIndex = index; }); if (angular.isDefined(taskIndex)) { var task = self.deferredFns.splice(taskIndex, 1)[0]; taskTracker.completeTask(angular.noop, task.type); return true; } return false; }; /** * @name $browser#defer.flush * * @description * Flushes all pending requests and executes the defer callbacks. * * See {@link ngMock.$flushPendingsTasks} for more info. * * @param {number=} number of milliseconds to flush. See {@link #defer.now} */ self.defer.flush = function(delay) { var nextTime; if (angular.isDefined(delay)) { // A delay was passed so compute the next time nextTime = self.defer.now + delay; } else if (self.deferredFns.length) { // No delay was passed so set the next time so that it clears the deferred queue nextTime = self.deferredFns[self.deferredFns.length - 1].time; } else { // No delay passed, but there are no deferred tasks so flush - indicates an error! throw new Error('No deferred tasks to be flushed'); } while (self.deferredFns.length && self.deferredFns[0].time <= nextTime) { // Increment the time and call the next deferred function self.defer.now = self.deferredFns[0].time; var task = self.deferredFns.shift(); taskTracker.completeTask(task.fn, task.type); } // Ensure that the current time is correct self.defer.now = nextTime; }; /** * @name $browser#defer.getPendingTasks * * @description * Returns the currently pending tasks that need to be flushed. * You can request a specific type of tasks only, by specifying a `taskType`. * * @param {string=} taskType - The type tasks to return. */ self.defer.getPendingTasks = function(taskType) { return !taskType ? self.deferredFns : self.deferredFns.filter(function(task) { return task.type === taskType; }); }; /** * @name $browser#defer.formatPendingTasks * * @description * Formats each task in a list of pending tasks as a string, suitable for use in error messages. * * @param {Array<Object>} pendingTasks - A list of task objects. * @return {Array<string>} A list of stringified tasks. */ self.defer.formatPendingTasks = function(pendingTasks) { return pendingTasks.map(function(task) { return '{id: ' + task.id + ', type: ' + task.type + ', time: ' + task.time + '}'; }); }; /** * @name $browser#defer.verifyNoPendingTasks * * @description * Verifies that there are no pending tasks that need to be flushed. * You can check for a specific type of tasks only, by specifying a `taskType`. * * See {@link $verifyNoPendingTasks} for more info. * * @param {string=} taskType - The type tasks to check for. */ self.defer.verifyNoPendingTasks = function(taskType) { var pendingTasks = self.defer.getPendingTasks(taskType); if (pendingTasks.length) { var formattedTasks = self.defer.formatPendingTasks(pendingTasks).join('\n '); throw new Error('Deferred tasks to flush (' + pendingTasks.length + '):\n ' + formattedTasks); } }; self.$$baseHref = '/'; self.baseHref = function() { return this.$$baseHref; }; }; angular.mock.$Browser.prototype = { /** * @name $browser#poll * * @description * run all fns in pollFns */ poll: function poll() { angular.forEach(this.pollFns, function(pollFn) { pollFn(); }); }, url: function(url, replace, state) { if (angular.isUndefined(state)) { state = null; } if (url) { // The `$browser` service trims empty hashes; simulate it. this.$$url = url.replace(/#$/, ''); // Native pushState serializes & copies the object; simulate it. this.$$state = angular.copy(state); return this; } return this.$$url; }, state: function() { return this.$$state; } }; /** * @ngdoc service * @name $flushPendingTasks * * @description * Flushes all currently pending tasks and executes the corresponding callbacks. * * Optionally, you can also pass a `delay` argument to only flush tasks that are scheduled to be * executed within `delay` milliseconds. Currently, `delay` only applies to timeouts, since all * other tasks have a delay of 0 (i.e. they are scheduled to be executed as soon as possible, but * still asynchronously). * * If no delay is specified, it uses a delay such that all currently pending tasks are flushed. * * The types of tasks that are flushed include: * * - Pending timeouts (via {@link $timeout}). * - Pending tasks scheduled via {@link ng.$rootScope.Scope#$applyAsync $applyAsync}. * - Pending tasks scheduled via {@link ng.$rootScope.Scope#$evalAsync $evalAsync}. * These include tasks scheduled via `$evalAsync()` indirectly (such as {@link $q} promises). * * <div class="alert alert-info"> * Periodic tasks scheduled via {@link $interval} use a different queue and are not flushed by * `$flushPendingTasks()`. Use {@link ngMock.$interval#flush $interval.flush(millis)} instead. * </div> * * @param {number=} delay - The number of milliseconds to flush. */ angular.mock.$FlushPendingTasksProvider = function() { this.$get = [ '$browser', function($browser) { return function $flushPendingTasks(delay) { return $browser.defer.flush(delay); }; } ]; }; /** * @ngdoc service * @name $verifyNoPendingTasks * * @description * Verifies that there are no pending tasks that need to be flushed. It throws an error if there are * still pending tasks. * * You can check for a specific type of tasks only, by specifying a `taskType`. * * Available task types: * * - `$timeout`: Pending timeouts (via {@link $timeout}). * - `$http`: Pending HTTP requests (via {@link $http}). * - `$route`: In-progress route transitions (via {@link $route}). * - `$applyAsync`: Pending tasks scheduled via {@link ng.$rootScope.Scope#$applyAsync $applyAsync}. * - `$evalAsync`: Pending tasks scheduled via {@link ng.$rootScope.Scope#$evalAsync $evalAsync}. * These include tasks scheduled via `$evalAsync()` indirectly (such as {@link $q} promises). * * <div class="alert alert-info"> * Periodic tasks scheduled via {@link $interval} use a different queue and are not taken into * account by `$verifyNoPendingTasks()`. There is currently no way to verify that there are no * pending {@link $interval} tasks. * </div> * * @param {string=} taskType - The type of tasks to check for. */ angular.mock.$VerifyNoPendingTasksProvider = function() { this.$get = [ '$browser', function($browser) { return function $verifyNoPendingTasks(taskType) { return $browser.defer.verifyNoPendingTasks(taskType); }; } ]; }; /** * @ngdoc provider * @name $exceptionHandlerProvider * * @description * Configures the mock implementation of {@link ng.$exceptionHandler} to rethrow or to log errors * passed to the `$exceptionHandler`. */ /** * @ngdoc service * @name $exceptionHandler * * @description * Mock implementation of {@link ng.$exceptionHandler} that rethrows or logs errors passed * to it. See {@link ngMock.$exceptionHandlerProvider $exceptionHandlerProvider} for configuration * information. * * * ```js * describe('$exceptionHandlerProvider', function() { * * it('should capture log messages and exceptions', function() { * * module(function($exceptionHandlerProvider) { * $exceptionHandlerProvider.mode('log'); * }); * * inject(function($log, $exceptionHandler, $timeout) { * $timeout(function() { $log.log(1); }); * $timeout(function() { $log.log(2); throw 'banana peel'; }); * $timeout(function() { $log.log(3); }); * expect($exceptionHandler.errors).toEqual([]); * expect($log.assertEmpty()); * $timeout.flush(); * expect($exceptionHandler.errors).toEqual(['banana peel']); * expect($log.log.logs).toEqual([[1], [2], [3]]); * }); * }); * }); * ``` */ angular.mock.$ExceptionHandlerProvider = function() { var handler; /** * @ngdoc method * @name $exceptionHandlerProvider#mode * * @description * Sets the logging mode. * * @param {string} mode Mode of operation, defaults to `rethrow`. * * - `log`: Sometimes it is desirable to test that an error is thrown, for this case the `log` * mode stores an array of errors in `$exceptionHandler.errors`, to allow later assertion of * them. See {@link ngMock.$log#assertEmpty assertEmpty()} and * {@link ngMock.$log#reset reset()}. * - `rethrow`: If any errors are passed to the handler in tests, it typically means that there * is a bug in the application or test, so this mock will make these tests fail. For any * implementations that expect exceptions to be thrown, the `rethrow` mode will also maintain * a log of thrown errors in `$exceptionHandler.errors`. */ this.mode = function(mode) { switch (mode) { case 'log': case 'rethrow': var errors = []; handler = function(e) { if (arguments.length === 1) { errors.push(e); } else { errors.push([].slice.call(arguments, 0)); } if (mode === 'rethrow') { throw e; } }; handler.errors = errors; break; default: throw new Error('Unknown mode \'' + mode + '\', only \'log\'/\'rethrow\' modes are allowed!'); } }; this.$get = function() { return handler; }; this.mode('rethrow'); }; /** * @ngdoc service * @name $log * * @description * Mock implementation of {@link ng.$log} that gathers all logged messages in arrays * (one array per logging level). These arrays are exposed as `logs` property of each of the * level-specific log function, e.g. for level `error` the array is exposed as `$log.error.logs`. * */ angular.mock.$LogProvider = function() { var debug = true; function concat(array1, array2, index) { return array1.concat(Array.prototype.slice.call(array2, index)); } this.debugEnabled = function(flag) { if (angular.isDefined(flag)) { debug = flag; return this; } else { return debug; } }; this.$get = function() { var $log = { log: function() { $log.log.logs.push(concat([], arguments, 0)); }, warn: function() { $log.warn.logs.push(concat([], arguments, 0)); }, info: function() { $log.info.logs.push(concat([], arguments, 0)); }, error: function() { $log.error.logs.push(concat([], arguments, 0)); }, debug: function() { if (debug) { $log.debug.logs.push(concat([], arguments, 0)); } } }; /** * @ngdoc method * @name $log#reset * * @description * Reset all of the logging arrays to empty. */ $log.reset = function() { /** * @ngdoc property * @name $log#log.logs * * @description * Array of messages logged using {@link ng.$log#log `log()`}. * * @example * ```js * $log.log('Some Log'); * var first = $log.log.logs.unshift(); * ``` */ $log.log.logs = []; /** * @ngdoc property * @name $log#info.logs * * @description * Array of messages logged using {@link ng.$log#info `info()`}. * * @example * ```js * $log.info('Some Info'); * var first = $log.info.logs.unshift(); * ``` */ $log.info.logs = []; /** * @ngdoc property * @name $log#warn.logs * * @description * Array of messages logged using {@link ng.$log#warn `warn()`}. * * @example * ```js * $log.warn('Some Warning'); * var first = $log.warn.logs.unshift(); * ``` */ $log.warn.logs = []; /** * @ngdoc property * @name $log#error.logs * * @description * Array of messages logged using {@link ng.$log#error `error()`}. * * @example * ```js * $log.error('Some Error'); * var first = $log.error.logs.unshift(); * ``` */ $log.error.logs = []; /** * @ngdoc property * @name $log#debug.logs * * @description * Array of messages logged using {@link ng.$log#debug `debug()`}. * * @example * ```js * $log.debug('Some Error'); * var first = $log.debug.logs.unshift(); * ``` */ $log.debug.logs = []; }; /** * @ngdoc method * @name $log#assertEmpty * * @description * Assert that all of the logging methods have no logged messages. If any messages are present, * an exception is thrown. */ $log.assertEmpty = function() { var errors = []; angular.forEach(['error', 'warn', 'info', 'log', 'debug'], function(logLevel) { angular.forEach($log[logLevel].logs, function(log) { angular.forEach(log, function(logItem) { errors.push('MOCK $log (' + logLevel + '): ' + String(logItem) + '\n' + (logItem.stack || '')); }); }); }); if (errors.length) { errors.unshift('Expected $log to be empty! Either a message was logged unexpectedly, or ' + 'an expected log message was not checked and removed:'); errors.push(''); throw new Error(errors.join('\n---------\n')); } }; $log.reset(); return $log; }; }; /** * @ngdoc service * @name $interval * * @description * Mock implementation of the $interval service. * * Use {@link ngMock.$interval#flush `$interval.flush(millis)`} to * move forward by `millis` milliseconds and trigger any functions scheduled to run in that * time. * * @param {function()} fn A function that should be called repeatedly. * @param {number} delay Number of milliseconds between each function call. * @param {number=} [count=0] Number of times to repeat. If not set, or 0, will repeat * indefinitely. * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block. * @param {...*=} Pass additional parameters to the executed function. * @returns {promise} A promise which will be notified on each iteration. */ angular.mock.$IntervalProvider = function() { this.$get = ['$browser', '$$intervalFactory', function($browser, $$intervalFactory) { var repeatFns = [], nextRepeatId = 0, now = 0, setIntervalFn = function(tick, delay, deferred, skipApply) { var id = nextRepeatId++; var fn = !skipApply ? tick : function() { tick(); $browser.defer.flush(); }; repeatFns.push({ nextTime: (now + (delay || 0)), delay: delay || 1, fn: fn, id: id, deferred: deferred }); repeatFns.sort(function(a, b) { return a.nextTime - b.nextTime; }); return id; }, clearIntervalFn = function(id) { for (var fnIndex = repeatFns.length - 1; fnIndex >= 0; fnIndex--) { if (repeatFns[fnIndex].id === id) { repeatFns.splice(fnIndex, 1); break; } } }; var $interval = $$intervalFactory(setIntervalFn, clearIntervalFn); /** * @ngdoc method * @name $interval#cancel * * @description * Cancels a task associated with the `promise`. * * @param {promise} promise A promise from calling the `$interval` function. * @returns {boolean} Returns `true` if the task was successfully cancelled. */ $interval.cancel = function(promise) { if (!promise) return false; for (var fnIndex = repeatFns.length - 1; fnIndex >= 0; fnIndex--) { if (repeatFns[fnIndex].id === promise.$$intervalId) { var deferred = repeatFns[fnIndex].deferred; deferred.promise.then(undefined, function() {}); deferred.reject('canceled'); repeatFns.splice(fnIndex, 1); return true; } } return false; }; /** * @ngdoc method * @name $interval#flush * @description * * Runs interval tasks scheduled to be run in the next `millis` milliseconds. * * @param {number} millis maximum timeout amount to flush up until. * * @return {number} The amount of time moved forward. */ $interval.flush = function(millis) { var before = now; now += millis; while (repeatFns.length && repeatFns[0].nextTime <= now) { var task = repeatFns[0]; task.fn(); if (task.nextTime === before) { // this can only happen the first time // a zero-delay interval gets triggered task.nextTime++; } task.nextTime += task.delay; repeatFns.sort(function(a, b) { return a.nextTime - b.nextTime;}); } return millis; }; return $interval; }]; }; function jsonStringToDate(string) { // The R_ISO8061_STR regex is never going to fit into the 100 char limit! // eslit-disable-next-line max-len var R_ISO8061_STR = /^(-?\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d{3}))?)?)?(Z|([+-])(\d\d):?(\d\d)))?$/; var match; if ((match = string.match(R_ISO8061_STR))) { var date = new Date(0), tzHour = 0, tzMin = 0; if (match[9]) { tzHour = toInt(match[9] + match[10]); tzMin = toInt(match[9] + match[11]); } date.setUTCFullYear(toInt(match[1]), toInt(match[2]) - 1, toInt(match[3])); date.setUTCHours(toInt(match[4] || 0) - tzHour, toInt(match[5] || 0) - tzMin, toInt(match[6] || 0), toInt(match[7] || 0)); return date; } return string; } function toInt(str) { return parseInt(str, 10); } function padNumberInMock(num, digits, trim) { var neg = ''; if (num < 0) { neg = '-'; num = -num; } num = '' + num; while (num.length < digits) num = '0' + num; if (trim) { num = num.substr(num.length - digits); } return neg + num; } /** * @ngdoc type * @name angular.mock.TzDate * @description * * *NOTE*: this is not an injectable instance, just a globally available mock class of `Date`. * * Mock of the Date type which has its timezone specified via constructor arg. * * The main purpose is to create Date-like instances with timezone fixed to the specified timezone * offset, so that we can test code that depends on local timezone settings without dependency on * the time zone settings of the machine where the code is running. * * @param {number} offset Offset of the *desired* timezone in hours (fractions will be honored) * @param {(number|string)} timestamp Timestamp representing the desired time in *UTC* * * @example * !!!! WARNING !!!!! * This is not a complete Date object so only methods that were implemented can be called safely. * To make matters worse, TzDate instances inherit stuff from Date via a prototype. * * We do our best to intercept calls to "unimplemented" methods, but since the list of methods is * incomplete we might be missing some non-standard methods. This can result in errors like: * "Date.prototype.foo called on incompatible Object". * * ```js * var newYearInBratislava = new TzDate(-1, '2009-12-31T23:00:00Z'); * newYearInBratislava.getTimezoneOffset() => -60; * newYearInBratislava.getFullYear() => 2010; * newYearInBratislava.getMonth() => 0; * newYearInBratislava.getDate() => 1; * newYearInBratislava.getHours() => 0; * newYearInBratislava.getMinutes() => 0; * newYearInBratislava.getSeconds() => 0; * ``` * */ angular.mock.TzDate = function(offset, timestamp) { var self = new Date(0); if (angular.isString(timestamp)) { var tsStr = timestamp; self.origDate = jsonStringToDate(timestamp); timestamp = self.origDate.getTime(); if (isNaN(timestamp)) { // eslint-disable-next-line no-throw-literal throw { name: 'Illegal Argument', message: 'Arg \'' + tsStr + '\' passed into TzDate constructor is not a valid date string' }; } } else { self.origDate = new Date(timestamp); } var localOffset = new Date(timestamp).getTimezoneOffset(); self.offsetDiff = localOffset * 60 * 1000 - offset * 1000 * 60 * 60; self.date = new Date(timestamp + self.offsetDiff); self.getTime = function() { return self.date.getTime() - self.offsetDiff; }; self.toLocaleDateString = function() { return self.date.toLocaleDateString(); }; self.getFullYear = function() { return self.date.getFullYear(); }; self.getMonth = function() { return self.date.getMonth(); }; self.getDate = function() { return self.date.getDate(); }; self.getHours = function() { return self.date.getHours(); }; self.getMinutes = function() { return self.date.getMinutes(); }; self.getSeconds = function() { return self.date.getSeconds(); }; self.getMilliseconds = function() { return self.date.getMilliseconds(); }; self.getTimezoneOffset = function() { return offset * 60; }; self.getUTCFullYear = function() { return self.origDate.getUTCFullYear(); }; self.getUTCMonth = function() { return self.origDate.getUTCMonth(); }; self.getUTCDate = function() { return self.origDate.getUTCDate(); }; self.getUTCHours = function() { return self.origDate.getUTCHours(); }; self.getUTCMinutes = function() { return self.origDate.getUTCMinutes(); }; self.getUTCSeconds = function() { return self.origDate.getUTCSeconds(); }; self.getUTCMilliseconds = function() { return self.origDate.getUTCMilliseconds(); }; self.getDay = function() { return self.date.getDay(); }; // provide this method only on browsers that already have it if (self.toISOString) { self.toISOString = function() { return padNumberInMock(self.origDate.getUTCFullYear(), 4) + '-' + padNumberInMock(self.origDate.getUTCMonth() + 1, 2) + '-' + padNumberInMock(self.origDate.getUTCDate(), 2) + 'T' + padNumberInMock(self.origDate.getUTCHours(), 2) + ':' + padNumberInMock(self.origDate.getUTCMinutes(), 2) + ':' + padNumberInMock(self.origDate.getUTCSeconds(), 2) + '.' + padNumberInMock(self.origDate.getUTCMilliseconds(), 3) + 'Z'; }; } //hide all methods not implemented in this mock that the Date prototype exposes var unimplementedMethods = ['getUTCDay', 'getYear', 'setDate', 'setFullYear', 'setHours', 'setMilliseconds', 'setMinutes', 'setMonth', 'setSeconds', 'setTime', 'setUTCDate', 'setUTCFullYear', 'setUTCHours', 'setUTCMilliseconds', 'setUTCMinutes', 'setUTCMonth', 'setUTCSeconds', 'setYear', 'toDateString', 'toGMTString', 'toJSON', 'toLocaleFormat', 'toLocaleString', 'toLocaleTimeString', 'toSource', 'toString', 'toTimeString', 'toUTCString', 'valueOf']; angular.forEach(unimplementedMethods, function(methodName) { self[methodName] = function() { throw new Error('Method \'' + methodName + '\' is not implemented in the TzDate mock'); }; }); return self; }; //make "tzDateInstance instanceof Date" return true angular.mock.TzDate.prototype = Date.prototype; /** * @ngdoc service * @name $animate * * @description * Mock implementation of the {@link ng.$animate `$animate`} service. Exposes two additional methods * for testing animations. * * You need to require the `ngAnimateMock` module in your test suite for instance `beforeEach(module('ngAnimateMock'))` */ angular.mock.animate = angular.module('ngAnimateMock', ['ng']) .info({ angularVersion: '1.7.9' }) .config(['$provide', function($provide) { $provide.factory('$$forceReflow', function() { function reflowFn() { reflowFn.totalReflows++; } reflowFn.totalReflows = 0; return reflowFn; }); $provide.factory('$$animateAsyncRun', function() { var queue = []; var queueFn = function() { return function(fn) { queue.push(fn); }; }; queueFn.flush = function() { if (queue.length === 0) return false; for (var i = 0; i < queue.length; i++) { queue[i](); } queue = []; return true; }; return queueFn; }); $provide.decorator('$$animateJs', ['$delegate', function($delegate) { var runners = []; var animateJsConstructor = function() { var animator = $delegate.apply($delegate, arguments); // If no javascript animation is found, animator is undefined if (animator) { runners.push(animator); } return animator; }; animateJsConstructor.$closeAndFlush = function() { runners.forEach(function(runner) { runner.end(); }); runners = []; }; return animateJsConstructor; }]); $provide.decorator('$animateCss', ['$delegate', function($delegate) { var runners = []; var animateCssConstructor = function(element, options) { var animator = $delegate(element, options); runners.push(animator); return animator; }; animateCssConstructor.$closeAndFlush = function() { runners.forEach(function(runner) { runner.end(); }); runners = []; }; return animateCssConstructor; }]); $provide.decorator('$animate', ['$delegate', '$timeout', '$browser', '$$rAF', '$animateCss', '$$animateJs', '$$forceReflow', '$$animateAsyncRun', '$rootScope', function($delegate, $timeout, $browser, $$rAF, $animateCss, $$animateJs, $$forceReflow, $$animateAsyncRun, $rootScope) { var animate = { queue: [], cancel: $delegate.cancel, on: $delegate.on, off: $delegate.off, pin: $delegate.pin, get reflows() { return $$forceReflow.totalReflows; }, enabled: $delegate.enabled, /** * @ngdoc method * @name $animate#closeAndFlush * @description * * This method will close all pending animations (both {@link ngAnimate#javascript-based-animations Javascript} * and {@link ngAnimate.$animateCss CSS}) and it will also flush any remaining animation frames and/or callbacks. */ closeAndFlush: function() { // we allow the flush command to swallow the errors // because depending on whether CSS or JS animations are // used, there may not be a RAF flush. The primary flush // at the end of this function must throw an exception // because it will track if there were pending animations this.flush(true); $animateCss.$closeAndFlush(); $$animateJs.$closeAndFlush(); this.flush(); }, /** * @ngdoc method * @name $animate#flush * @description * * This method is used to flush the pending callbacks and animation frames to either start * an animation or conclude an animation. Note that this will not actually close an * actively running animation (see {@link ngMock.$animate#closeAndFlush `closeAndFlush()`} for that). */ flush: function(hideErrors) { $rootScope.$digest(); var doNextRun, somethingFlushed = false; do { doNextRun = false; if ($$rAF.queue.length) { $$rAF.flush(); doNextRun = somethingFlushed = true; } if ($$animateAsyncRun.flush()) { doNextRun = somethingFlushed = true; } } while (doNextRun); if (!somethingFlushed && !hideErrors) { throw new Error('No pending animations ready to be closed or flushed'); } $rootScope.$digest(); } }; angular.forEach( ['animate','enter','leave','move','addClass','removeClass','setClass'], function(method) { animate[method] = function() { animate.queue.push({ event: method, element: arguments[0], options: arguments[arguments.length - 1], args: arguments }); return $delegate[method].apply($delegate, arguments); }; }); return animate; }]); }]); /** * @ngdoc function * @name angular.mock.dump * @description * * *NOTE*: This is not an injectable instance, just a globally available function. * * Method for serializing common AngularJS objects (scope, elements, etc..) into strings. * It is useful for logging objects to the console when debugging. * * @param {*} object - any object to turn into string. * @return {string} a serialized string of the argument */ angular.mock.dump = function(object) { return serialize(object); function serialize(object) { var out; if (angular.isElement(object)) { object = angular.element(object); out = angular.element('<div></div>'); angular.forEach(object, function(element) { out.append(angular.element(element).clone()); }); out = out.html(); } else if (angular.isArray(object)) { out = []; angular.forEach(object, function(o) { out.push(serialize(o)); }); out = '[ ' + out.join(', ') + ' ]'; } else if (angular.isObject(object)) { if (angular.isFunction(object.$eval) && angular.isFunction(object.$apply)) { out = serializeScope(object); } else if (object instanceof Error) { out = object.stack || ('' + object.name + ': ' + object.message); } else { // TODO(i): this prevents methods being logged, // we should have a better way to serialize objects out = angular.toJson(object, true); } } else { out = String(object); } return out; } function serializeScope(scope, offset) { offset = offset || ' '; var log = [offset + 'Scope(' + scope.$id + '): {']; for (var key in scope) { if (Object.prototype.hasOwnProperty.call(scope, key) && !key.match(/^(\$|this)/)) { log.push(' ' + key + ': ' + angular.toJson(scope[key])); } } var child = scope.$$childHead; while (child) { log.push(serializeScope(child, offset + ' ')); child = child.$$nextSibling; } log.push('}'); return log.join('\n' + offset); } }; /** * @ngdoc service * @name $httpBackend * @description * Fake HTTP backend implementation suitable for unit testing applications that use the * {@link ng.$http $http service}. * * <div class="alert alert-info"> * **Note**: For fake HTTP backend implementation suitable for end-to-end testing or backend-less * development please see {@link ngMockE2E.$httpBackend e2e $httpBackend mock}. * </div> * * During unit testing, we want our unit tests to run quickly and have no external dependencies so * we don’t want to send [XHR](https://developer.mozilla.org/en/xmlhttprequest) or * [JSONP](http://en.wikipedia.org/wiki/JSONP) requests to a real server. All we really need is * to verify whether a certain request has been sent or not, or alternatively just let the * application make requests, respond with pre-trained responses and assert that the end result is * what we expect it to be. * * This mock implementation can be used to respond with static or dynamic responses via the * `expect` and `when` apis and their shortcuts (`expectGET`, `whenPOST`, etc). * * When an AngularJS application needs some data from a server, it calls the $http service, which * sends the request to a real server using $httpBackend service. With dependency injection, it is * easy to inject $httpBackend mock (which has the same API as $httpBackend) and use it to verify * the requests and respond with some testing data without sending a request to a real server. * * There are two ways to specify what test data should be returned as http responses by the mock * backend when the code under test makes http requests: * * - `$httpBackend.expect` - specifies a request expectation * - `$httpBackend.when` - specifies a backend definition * * * ## Request Expectations vs Backend Definitions * * Request expectations provide a way to make assertions about requests made by the application and * to define responses for those requests. The test will fail if the expected requests are not made * or they are made in the wrong order. * * Backend definitions allow you to define a fake backend for your application which doesn't assert * if a particular request was made or not, it just returns a trained response if a request is made. * The test will pass whether or not the request gets made during testing. * * * <table class="table"> * <tr><th width="220px"></th><th>Request expectations</th><th>Backend definitions</th></tr> * <tr> * <th>Syntax</th> * <td>.expect(...).respond(...)</td> * <td>.when(...).respond(...)</td> * </tr> * <tr> * <th>Typical usage</th> * <td>strict unit tests</td> * <td>loose (black-box) unit testing</td> * </tr> * <tr> * <th>Fulfills multiple requests</th> * <td>NO</td> * <td>YES</td> * </tr> * <tr> * <th>Order of requests matters</th> * <td>YES</td> * <td>NO</td> * </tr> * <tr> * <th>Request required</th> * <td>YES</td> * <td>NO</td> * </tr> * <tr> * <th>Response required</th> * <td>optional (see below)</td> * <td>YES</td> * </tr> * </table> * * In cases where both backend definitions and request expectations are specified during unit * testing, the request expectations are evaluated first. * * If a request expectation has no response specified, the algorithm will search your backend * definitions for an appropriate response. * * If a request didn't match any expectation or if the expectation doesn't have the response * defined, the backend definitions are evaluated in sequential order to see if any of them match * the request. The response from the first matched definition is returned. * * * ## Flushing HTTP requests * * The $httpBackend used in production always responds to requests asynchronously. If we preserved * this behavior in unit testing, we'd have to create async unit tests, which are hard to write, * to follow and to maintain. But neither can the testing mock respond synchronously; that would * change the execution of the code under test. For this reason, the mock $httpBackend has a * `flush()` method, which allows the test to explicitly flush pending requests. This preserves * the async api of the backend, while allowing the test to execute synchronously. * * * ## Unit testing with mock $httpBackend * The following code shows how to setup and use the mock backend when unit testing a controller. * First we create the controller under test: * ```js // The module code angular .module('MyApp', []) .controller('MyController', MyController); // The controller code function MyController($scope, $http) { var authToken; $http.get('/auth.py').then(function(response) { authToken = response.headers('A-Token'); $scope.user = response.data; }).catch(function() { $scope.status = 'Failed...'; }); $scope.saveMessage = function(message) { var headers = { 'Authorization': authToken }; $scope.status = 'Saving...'; $http.post('/add-msg.py', message, { headers: headers } ).then(function(response) { $scope.status = ''; }).catch(function() { $scope.status = 'Failed...'; }); }; } ``` * * Now we setup the mock backend and create the test specs: * ```js // testing controller describe('MyController', function() { var $httpBackend, $rootScope, createController, authRequestHandler; // Set up the module beforeEach(module('MyApp')); beforeEach(inject(function($injector) { // Set up the mock http service responses $httpBackend = $injector.get('$httpBackend'); // backend definition common for all tests authRequestHandler = $httpBackend.when('GET', '/auth.py') .respond({userId: 'userX'}, {'A-Token': 'xxx'}); // Get hold of a scope (i.e. the root scope) $rootScope = $injector.get('$rootScope'); // The $controller service is used to create instances of controllers var $controller = $injector.get('$controller'); createController = function() { return $controller('MyController', {'$scope' : $rootScope }); }; })); afterEach(function() { $httpBackend.verifyNoOutstandingExpectation(); $httpBackend.verifyNoOutstandingRequest(); }); it('should fetch authentication token', function() { $httpBackend.expectGET('/auth.py'); var controller = createController(); $httpBackend.flush(); }); it('should fail authentication', function() { // Notice how you can change the response even after it was set authRequestHandler.respond(401, ''); $httpBackend.expectGET('/auth.py'); var controller = createController(); $httpBackend.flush(); expect($rootScope.status).toBe('Failed...'); }); it('should send msg to server', function() { var controller = createController(); $httpBackend.flush(); // now you don’t care about the authentication, but // the controller will still send the request and // $httpBackend will respond without you having to // specify the expectation and response for this request $httpBackend.expectPOST('/add-msg.py', 'message content').respond(201, ''); $rootScope.saveMessage('message content'); expect($rootScope.status).toBe('Saving...'); $httpBackend.flush(); expect($rootScope.status).toBe(''); }); it('should send auth header', function() { var controller = createController(); $httpBackend.flush(); $httpBackend.expectPOST('/add-msg.py', undefined, function(headers) { // check if the header was sent, if it wasn't the expectation won't // match the request and the test will fail return headers['Authorization'] === 'xxx'; }).respond(201, ''); $rootScope.saveMessage('whatever'); $httpBackend.flush(); }); }); ``` * * ## Dynamic responses * * You define a response to a request by chaining a call to `respond()` onto a definition or expectation. * If you provide a **callback** as the first parameter to `respond(callback)` then you can dynamically generate * a response based on the properties of the request. * * The `callback` function should be of the form `function(method, url, data, headers, params)`. * * ### Query parameters * * By default, query parameters on request URLs are parsed into the `params` object. So a request URL * of `/list?q=searchstr&orderby=-name` would set `params` to be `{q: 'searchstr', orderby: '-name'}`. * * ### Regex parameter matching * * If an expectation or definition uses a **regex** to match the URL, you can provide an array of **keys** via a * `params` argument. The index of each **key** in the array will match the index of a **group** in the * **regex**. * * The `params` object in the **callback** will now have properties with these keys, which hold the value of the * corresponding **group** in the **regex**. * * This also applies to the `when` and `expect` shortcut methods. * * * ```js * $httpBackend.expect('GET', /\/user\/(.+)/, undefined, undefined, ['id']) * .respond(function(method, url, data, headers, params) { * // for requested url of '/user/1234' params is {id: '1234'} * }); * * $httpBackend.whenPATCH(/\/user\/(.+)\/article\/(.+)/, undefined, undefined, ['user', 'article']) * .respond(function(method, url, data, headers, params) { * // for url of '/user/1234/article/567' params is {user: '1234', article: '567'} * }); * ``` * * ## Matching route requests * * For extra convenience, `whenRoute` and `expectRoute` shortcuts are available. These methods offer colon * delimited matching of the url path, ignoring the query string and trailing slashes. This allows declarations * similar to how application routes are configured with `$routeProvider`. Because these methods convert * the definition url to regex, declaration order is important. Combined with query parameter parsing, * the following is possible: * ```js $httpBackend.whenRoute('GET', '/users/:id') .respond(function(method, url, data, headers, params) { return [200, MockUserList[Number(params.id)]]; }); $httpBackend.whenRoute('GET', '/users') .respond(function(method, url, data, headers, params) { var userList = angular.copy(MockUserList), defaultSort = 'lastName', count, pages, isPrevious, isNext; // paged api response '/v1/users?page=2' params.page = Number(params.page) || 1; // query for last names '/v1/users?q=Archer' if (params.q) { userList = $filter('filter')({lastName: params.q}); } pages = Math.ceil(userList.length / pagingLength); isPrevious = params.page > 1; isNext = params.page < pages; return [200, { count: userList.length, previous: isPrevious, next: isNext, // sort field -> '/v1/users?sortBy=firstName' results: $filter('orderBy')(userList, params.sortBy || defaultSort) .splice((params.page - 1) * pagingLength, pagingLength) }]; }); ``` */ angular.mock.$httpBackendDecorator = ['$rootScope', '$timeout', '$delegate', createHttpBackendMock]; /** * General factory function for $httpBackend mock. * Returns instance for unit testing (when no arguments specified): * - passing through is disabled * - auto flushing is disabled * * Returns instance for e2e testing (when `$delegate` and `$browser` specified): * - passing through (delegating request to real backend) is enabled * - auto flushing is enabled * * @param {Object=} $delegate Real $httpBackend instance (allow passing through if specified) * @param {Object=} $browser Auto-flushing enabled if specified * @return {Object} Instance of $httpBackend mock */ function createHttpBackendMock($rootScope, $timeout, $delegate, $browser) { var definitions = [], expectations = [], matchLatestDefinition = false, responses = [], responsesPush = angular.bind(responses, responses.push), copy = angular.copy, // We cache the original backend so that if both ngMock and ngMockE2E override the // service the ngMockE2E version can pass through to the real backend originalHttpBackend = $delegate.$$originalHttpBackend || $delegate; function createResponse(status, data, headers, statusText) { if (angular.isFunction(status)) return status; return function() { return angular.isNumber(status) ? [status, data, headers, statusText, 'complete'] : [200, status, data, headers, 'complete']; }; } // TODO(vojta): change params to: method, url, data, headers, callback function $httpBackend(method, url, data, callback, headers, timeout, withCredentials, responseType, eventHandlers, uploadEventHandlers) { var xhr = new MockXhr(), expectation = expectations[0], wasExpected = false; xhr.$$events = eventHandlers; xhr.upload.$$events = uploadEventHandlers; function prettyPrint(data) { return (angular.isString(data) || angular.isFunction(data) || data instanceof RegExp) ? data : angular.toJson(data); } function wrapResponse(wrapped) { if (!$browser && timeout) { if (timeout.then) { timeout.then(function() { handlePrematureEnd(angular.isDefined(timeout.$$timeoutId) ? 'timeout' : 'abort'); }); } else { $timeout(function() { handlePrematureEnd('timeout'); }, timeout); } } handleResponse.description = method + ' ' + url; return handleResponse; function handleResponse() { var response = wrapped.response(method, url, data, headers, wrapped.params(url)); xhr.$$respHeaders = response[2]; callback(copy(response[0]), copy(response[1]), xhr.getAllResponseHeaders(), copy(response[3] || ''), copy(response[4])); } function handlePrematureEnd(reason) { for (var i = 0, ii = responses.length; i < ii; i++) { if (responses[i] === handleResponse) { responses.splice(i, 1); callback(-1, undefined, '', undefined, reason); break; } } } } function createFatalError(message) { var error = new Error(message); // In addition to being converted to a rejection, these errors also need to be passed to // t