vendor/assets/javascripts/angular-mocks.js in angularjs-rails-1.2.0.rc3 vs vendor/assets/javascripts/angular-mocks.js in angularjs-rails-1.2.0
- old
+ new
@@ -1,7 +1,9 @@
+'use strict';
+
/**
- * @license AngularJS v1.2.0-rc.3
+ * @license AngularJS v1.2.0
* (c) 2010-2012 Google, Inc. http://angularjs.org
* License: MIT
*
* TODO(vojta): wrap whole file into closure during build
*/
@@ -115,11 +117,11 @@
self.defer.now += delay;
} else {
if (self.deferredFns.length) {
self.defer.now = self.deferredFns[self.deferredFns.length-1].time;
} else {
- throw Error('No deferred tasks to be flushed');
+ throw new Error('No deferred tasks to be flushed');
}
}
while (self.deferredFns.length && self.deferredFns[0].time <= self.defer.now) {
self.deferredFns.shift().fn();
@@ -160,11 +162,11 @@
return this.$$url;
},
cookies: function(name, value) {
if (name) {
- if (value == undefined) {
+ if (angular.isUndefined(value)) {
delete this.cookieHash[name];
} else {
if (angular.isString(value) && //strings only
value.length <= 4096) { //strict cookie storage limits
this.cookieHash[name] = value;
@@ -188,12 +190,12 @@
/**
* @ngdoc object
* @name ngMock.$exceptionHandlerProvider
*
* @description
- * Configures the mock implementation of {@link ng.$exceptionHandler} to rethrow or to log errors passed
- * into the `$exceptionHandler`.
+ * Configures the mock implementation of {@link ng.$exceptionHandler} to rethrow or to log errors
+ * passed into the `$exceptionHandler`.
*/
/**
* @ngdoc object
* @name ngMock.$exceptionHandler
@@ -242,14 +244,14 @@
* @param {string} mode Mode of operation, defaults to `rethrow`.
*
* - `rethrow`: If any errors are passed into 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.
- * - `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()}
+ * - `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()}
*/
this.mode = function(mode) {
switch(mode) {
case 'rethrow':
handler = function(e) {
@@ -268,11 +270,11 @@
};
handler.errors = errors;
break;
default:
- throw Error("Unknown mode '" + mode + "', only 'log'/'rethrow' modes are allowed!");
+ throw new Error("Unknown mode '" + mode + "', only 'log'/'rethrow' modes are allowed!");
}
};
this.$get = function() {
return handler;
@@ -298,16 +300,16 @@
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;
- }
+ 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)); },
@@ -402,33 +404,35 @@
* <pre>
* $log.debug('Some Error');
* var first = $log.debug.logs.unshift();
* </pre>
*/
- $log.debug.logs = []
+ $log.debug.logs = [];
};
/**
* @ngdoc method
* @name ngMock.$log#assertEmpty
* @methodOf ngMock.$log
*
* @description
- * Assert that the all of the logging methods have no logged messages. If messages present, an exception is thrown.
+ * Assert that the all of the logging methods have no logged messages. If messages 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 || ''));
+ 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.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'));
}
};
@@ -443,20 +447,20 @@
* @name ngMock.$interval
*
* @description
* Mock implementation of the $interval service.
*
- * Use {@link ngMock.$interval#flush `$interval.flush(millis)`} to
+ * Use {@link ngMock.$interval#methods_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.
+ * will invoke `fn` within the {@link ng.$rootScope.Scope#methods_$apply $apply} block.
* @returns {promise} A promise which will be notified on each iteration.
*/
angular.mock.$IntervalProvider = function() {
this.$get = ['$rootScope', '$q',
function($rootScope, $q) {
@@ -465,14 +469,14 @@
now = 0;
var $interval = function(fn, delay, count, invokeApply) {
var deferred = $q.defer(),
promise = deferred.promise,
- count = (angular.isDefined(count)) ? count : 0,
iteration = 0,
skipApply = (angular.isDefined(invokeApply) && !invokeApply);
+ count = (angular.isDefined(count)) ? count : 0,
promise.then(null, null, fn);
promise.$$intervalId = nextRepeatId;
function tick() {
@@ -490,11 +494,11 @@
repeatFns.splice(fnIndex, 1);
}
}
if (!skipApply) $rootScope.$apply();
- };
+ }
repeatFns.push({
nextTime:(now + delay),
delay: delay,
fn: tick,
@@ -549,10 +553,15 @@
return $interval;
}];
};
+/* jshint -W101 */
+/* The R_ISO8061_STR regex is never going to fit into the 100 char limit!
+ * This directive should go inside the anonymous function but a bug in JSHint means that it would
+ * not be enacted early enough to prevent the warning.
+ */
(function() {
var R_ISO8061_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?:\:?(\d\d)(?:\:?(\d\d)(?:\.(\d{3}))?)?)?(Z|([+-])(\d\d):?(\d\d)))?$/;
function jsonStringToDate(string) {
var match;
@@ -563,11 +572,14 @@
if (match[9]) {
tzHour = int(match[9] + match[10]);
tzMin = int(match[9] + match[11]);
}
date.setUTCFullYear(int(match[1]), int(match[2]) - 1, int(match[3]));
- date.setUTCHours(int(match[4]||0) - tzHour, int(match[5]||0) - tzMin, int(match[6]||0), int(match[7]||0));
+ date.setUTCHours(int(match[4]||0) - tzHour,
+ int(match[5]||0) - tzMin,
+ int(match[6]||0),
+ int(match[7]||0));
return date;
}
return string;
}
@@ -726,12 +738,12 @@
padNumber(self.origDate.getUTCMonth() + 1, 2) + '-' +
padNumber(self.origDate.getUTCDate(), 2) + 'T' +
padNumber(self.origDate.getUTCHours(), 2) + ':' +
padNumber(self.origDate.getUTCMinutes(), 2) + ':' +
padNumber(self.origDate.getUTCSeconds(), 2) + '.' +
- padNumber(self.origDate.getUTCMilliseconds(), 3) + 'Z'
- }
+ padNumber(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',
@@ -740,20 +752,21 @@
'setYear', 'toDateString', 'toGMTString', 'toJSON', 'toLocaleFormat', 'toLocaleString',
'toLocaleTimeString', 'toSource', 'toString', 'toTimeString', 'toUTCString', 'valueOf'];
angular.forEach(unimplementedMethods, function(methodName) {
self[methodName] = function() {
- throw Error("Method '" + methodName + "' is not implemented in the TzDate mock");
+ 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;
})();
+/* jshint +W101 */
angular.mock.animate = angular.module('mock.animate', ['ng'])
.config(['$provide', function($provide) {
@@ -761,11 +774,16 @@
var animate = {
queue : [],
enabled : $delegate.enabled,
flushNext : function(name) {
var tick = animate.queue.shift();
- expect(tick.method).toBe(name);
+
+ if (!tick) throw new Error('No animation to be flushed');
+ if(tick.method !== name) {
+ throw new Error('The next animation is not "' + name +
+ '", but is "' + tick.method + '"');
+ }
tick.fn();
return tick;
}
};
@@ -796,13 +814,15 @@
* @name angular.mock.dump
* @description
*
* *NOTE*: this is not an injectable instance, just a globally available function.
*
- * Method for serializing common angular objects (scope, elements, etc..) into strings, useful for debugging.
+ * Method for serializing common angular objects (scope, elements, etc..) into strings, useful for
+ * debugging.
*
- * This method is also available on window, where it can be used to display objects on debug console.
+ * This method is also available on window, where it can be used to display objects on debug
+ * console.
*
* @param {*} object - any object to turn into string.
* @return {string} a serialized string of the argument
*/
angular.mock.dump = function(object) {
@@ -828,11 +848,12 @@
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 to be logged, we should have a better way to serialize objects
+ // 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);
}
@@ -1127,11 +1148,12 @@
throw new Error('Expected ' + expectation + ' with different data\n' +
'EXPECTED: ' + prettyPrint(expectation.data) + '\nGOT: ' + data);
if (!expectation.matchHeaders(headers))
throw new Error('Expected ' + expectation + ' with different headers\n' +
- 'EXPECTED: ' + prettyPrint(expectation.headers) + '\nGOT: ' + prettyPrint(headers));
+ 'EXPECTED: ' + prettyPrint(expectation.headers) + '\nGOT: ' +
+ prettyPrint(headers));
expectations.shift();
if (expectation.response) {
responses.push(wrapResponse(expectation));
@@ -1146,11 +1168,11 @@
if (definition.response) {
// if $browser specified, we do auto flush all requests
($browser ? $browser.defer : responsesPush)(wrapResponse(definition));
} else if (definition.passThrough) {
$delegate(method, url, data, callback, headers, timeout, withCredentials);
- } else throw Error('No response defined !');
+ } else throw new Error('No response defined !');
return;
}
}
throw wasExpected ?
new Error('No response defined !') :
@@ -1169,14 +1191,15 @@
* @param {string|RegExp} url HTTP url.
* @param {(string|RegExp|function(string))=} data HTTP request body or function that receives
* data string and returns true if the data is as expected.
* @param {(Object|function(Object))=} headers HTTP headers or function that receives http header
* object and returns true if the headers match the current definition.
- * @returns {requestHandler} Returns an object with `respond` method that control how a matched
+ * @returns {requestHandler} Returns an object with `respond` method that controls how a matched
* request is handled.
*
- * - respond – `{function([status,] data[, headers])|function(function(method, url, data, headers)}`
+ * - respond –
+ * `{function([status,] data[, headers])|function(function(method, url, data, headers)}`
* – The respond method takes a set of static data to be returned or a function that can return
* an array containing response status (number), response data (string) and response headers
* (Object).
*/
$httpBackend.when = function(method, url, data, headers) {
@@ -1295,11 +1318,12 @@
* @param {(Object|function(Object))=} headers HTTP headers or function that receives http header
* object and returns true if the headers match the current expectation.
* @returns {requestHandler} Returns an object with `respond` method that control how a matched
* request is handled.
*
- * - respond – `{function([status,] data[, headers])|function(function(method, url, data, headers)}`
+ * - respond –
+ * `{function([status,] data[, headers])|function(function(method, url, data, headers)}`
* – The respond method takes a set of static data to be returned or a function that can return
* an array containing response status (number), response data (string) and response headers
* (Object).
*/
$httpBackend.expect = function(method, url, data, headers) {
@@ -1425,15 +1449,15 @@
* all pending requests will be flushed. If there are no pending requests when the flush method
* is called an exception is thrown (as this typically a sign of programming error).
*/
$httpBackend.flush = function(count) {
$rootScope.$digest();
- if (!responses.length) throw Error('No pending request to flush !');
+ if (!responses.length) throw new Error('No pending request to flush !');
if (angular.isDefined(count)) {
while (count--) {
- if (!responses.length) throw Error('No more pending request to flush !');
+ if (!responses.length) throw new Error('No more pending request to flush !');
responses.shift()();
}
} else {
while (responses.length) {
responses.shift()();
@@ -1480,11 +1504,11 @@
* afterEach($httpBackend.verifyNoOutstandingRequest);
* </pre>
*/
$httpBackend.verifyNoOutstandingRequest = function() {
if (responses.length) {
- throw Error('Unflushed requests: ' + responses.length);
+ throw new Error('Unflushed requests: ' + responses.length);
}
};
/**
@@ -1505,18 +1529,18 @@
function createShortMethods(prefix) {
angular.forEach(['GET', 'DELETE', 'JSONP'], function(method) {
$httpBackend[prefix + method] = function(url, headers) {
- return $httpBackend[prefix](method, url, undefined, headers)
- }
+ return $httpBackend[prefix](method, url, undefined, headers);
+ };
});
angular.forEach(['PUT', 'POST', 'PATCH'], function(method) {
$httpBackend[prefix + method] = function(url, data, headers) {
- return $httpBackend[prefix](method, url, data, headers)
- }
+ return $httpBackend[prefix](method, url, data, headers);
+ };
});
}
}
function MockHttpExpectation(method, url, data, headers) {
@@ -1577,11 +1601,12 @@
this.setRequestHeader = function(key, value) {
this.$$reqHeaders[key] = value;
};
this.getResponseHeader = function(name) {
- // the lookup must be case insensitive, that's why we try two quick lookups and full scan at last
+ // the lookup must be case insensitive,
+ // that's why we try two quick lookups first and full scan last
var header = this.$$respHeaders[name];
if (header) return header;
name = angular.lowercase(name);
header = this.$$respHeaders[name];
@@ -1638,11 +1663,12 @@
* @methodOf ngMock.$timeout
* @description
*
* Flushes the next timeout in the queue and compares it to the provided delay
*
- * @param {number=} expectedDelay the delay value that will be asserted against the delay of the next timeout function
+ * @param {number=} expectedDelay the delay value that will be asserted against the delay of the
+ * next timeout function
*/
$delegate.flushNext = function(expectedDelay) {
$browser.defer.flushNext(expectedDelay);
};
@@ -1677,44 +1703,52 @@
*
*/
angular.mock.$RootElementProvider = function() {
this.$get = function() {
return angular.element('<div ng-app></div>');
- }
+ };
};
/**
* @ngdoc overview
* @name ngMock
* @description
*
- * The `ngMock` is an angular module which is used with `ng` module and adds unit-test configuration as well as useful
- * mocks to the {@link AUTO.$injector $injector}.
+ * # ngMock
+ *
+ * The `ngMock` module providers support to inject and mock Angular services into unit tests.
+ * In addition, ngMock also extends various core ng services such that they can be
+ * inspected and controlled in a synchronous manner within test code.
+ *
+ * {@installModule mocks}
+ *
+ * <div doc-module-components="ngMock"></div>
+ *
*/
angular.module('ngMock', ['ng']).provider({
$browser: angular.mock.$BrowserProvider,
$exceptionHandler: angular.mock.$ExceptionHandlerProvider,
$log: angular.mock.$LogProvider,
$interval: angular.mock.$IntervalProvider,
$httpBackend: angular.mock.$HttpBackendProvider,
$rootElement: angular.mock.$RootElementProvider
-}).config(function($provide) {
+}).config(['$provide', function($provide) {
$provide.decorator('$timeout', angular.mock.$TimeoutDecorator);
-});
+}]);
/**
* @ngdoc overview
* @name ngMockE2E
* @description
*
* The `ngMockE2E` is an angular module which contains mocks suitable for end-to-end testing.
* Currently there is only one mock present in this module -
* the {@link ngMockE2E.$httpBackend e2e $httpBackend} mock.
*/
-angular.module('ngMockE2E', ['ng']).config(function($provide) {
+angular.module('ngMockE2E', ['ng']).config(['$provide', function($provide) {
$provide.decorator('$httpBackend', angular.mock.e2e.$httpBackendDecorator);
-});
+}]);
/**
* @ngdoc object
* @name ngMockE2E.$httpBackend
* @description
@@ -1775,11 +1809,12 @@
* @param {(Object|function(Object))=} headers HTTP headers or function that receives http header
* object and returns true if the headers match the current definition.
* @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
* control how a matched request is handled.
*
- * - respond – `{function([status,] data[, headers])|function(function(method, url, data, headers)}`
+ * - respond –
+ * `{function([status,] data[, headers])|function(function(method, url, data, headers)}`
* – The respond method takes a set of static data to be returned or a function that can return
* an array containing response status (number), response data (string) and response headers
* (Object).
* - passThrough – `{function()}` – Any request matching a backend definition with `passThrough`
* handler, will be pass through to the real backend (an XHR request will be made to the
@@ -1877,11 +1912,12 @@
* @param {string|RegExp} url HTTP url.
* @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
* control how a matched request is handled.
*/
angular.mock.e2e = {};
-angular.mock.e2e.$httpBackendDecorator = ['$rootScope', '$delegate', '$browser', createHttpBackendMock];
+angular.mock.e2e.$httpBackendDecorator =
+ ['$rootScope', '$delegate', '$browser', createHttpBackendMock];
angular.mock.clearDataCache = function() {
var key,
cache = angular.element.cache;
@@ -1949,21 +1985,21 @@
*
* See {@link angular.mock.inject inject} for usage example
*
* @param {...(string|Function|Object)} fns any number of modules which are represented as string
* aliases or as anonymous module initialization functions. The modules are used to
- * configure the injector. The 'ng' and 'ngMock' modules are automatically loaded. If an
+ * configure the injector. The 'ng' and 'ngMock' modules are automatically loaded. If an
* object literal is passed they will be register as values in the module, the key being
* the module name and the value being what is returned.
*/
window.module = angular.mock.module = function() {
var moduleFns = Array.prototype.slice.call(arguments, 0);
return isSpecRunning() ? workFn() : workFn;
/////////////////////
function workFn() {
if (currentSpec.$injector) {
- throw Error('Injector already created, can not register a module!');
+ throw new Error('Injector already created, can not register a module!');
} else {
var modules = currentSpec.$modules || (currentSpec.$modules = []);
angular.forEach(moduleFns, function(module) {
if (angular.isObject(module) && !angular.isArray(module)) {
modules.push(function($provide) {
@@ -1992,37 +2028,37 @@
*
*
* ## Resolving References (Underscore Wrapping)
* Often, we would like to inject a reference once, in a `beforeEach()` block and reuse this
* in multiple `it()` clauses. To be able to do this we must assign the reference to a variable
- * that is declared in the scope of the `describe()` block. Since we would, most likely, want
+ * that is declared in the scope of the `describe()` block. Since we would, most likely, want
* the variable to have the same name of the reference we have a problem, since the parameter
* to the `inject()` function would hide the outer variable.
*
* To help with this, the injected parameters can, optionally, be enclosed with underscores.
* These are ignored by the injector when the reference name is resolved.
- *
+ *
* For example, the parameter `_myService_` would be resolved as the reference `myService`.
* Since it is available in the function body as _myService_, we can then assign it to a variable
* defined in an outer scope.
- *
+ *
* ```
* // Defined out reference variable outside
* var myService;
*
* // Wrap the parameter in underscores
* beforeEach( inject( function(_myService_){
* myService = _myService_;
- * }));
+ * }));
*
* // Use myService in a series of tests.
* it('makes use of myService', function() {
* myService.doStuff();
* });
- *
+ *
* ```
- *
+ *
* See also {@link angular.mock.module angular.mock.module}
*
* ## Example
* Example of what a typical jasmine tests looks like with the inject method.
* <pre>
@@ -2058,11 +2094,11 @@
* });
* });
* });
*
* </pre>
- *
+ *
* @param {...Function} fns any number of functions which will be injected using the injector.
*/
window.inject = angular.mock.inject = function() {
var blockFns = Array.prototype.slice.call(arguments, 0);
var errorForStack = new Error('Declaration Location');
@@ -2077,16 +2113,18 @@
if (!injector) {
injector = currentSpec.$injector = angular.injector(modules);
}
for(var i = 0, ii = blockFns.length; i < ii; i++) {
try {
+ /* jshint -W040 *//* Jasmine explicitly provides a `this` object when calling functions */
injector.invoke(blockFns[i] || angular.noop, this);
+ /* jshint +W040 */
} catch (e) {
if(e.stack && errorForStack) e.stack += '\n' + errorForStack.stack;
throw e;
} finally {
errorForStack = null;
}
}
}
};
-})(window);
+})(window);
\ No newline at end of file