angular-gem 1.3.1 → 1.3.2

Sign up to get free protection for your applications and to get access to all the features.
Files changed (27) hide show
  1. checksums.yaml +8 -8
  2. data/lib/angular-gem/version.rb +1 -1
  3. data/vendor/assets/javascripts/1.3.2/angular-animate.js +2136 -0
  4. data/vendor/assets/javascripts/1.3.2/angular-aria.js +261 -0
  5. data/vendor/assets/javascripts/1.3.2/angular-cookies.js +206 -0
  6. data/vendor/assets/javascripts/1.3.2/angular-loader.js +422 -0
  7. data/vendor/assets/javascripts/1.3.2/angular-messages.js +400 -0
  8. data/vendor/assets/javascripts/1.3.2/angular-mocks.js +2376 -0
  9. data/vendor/assets/javascripts/1.3.2/angular-resource.js +667 -0
  10. data/vendor/assets/javascripts/1.3.2/angular-route.js +982 -0
  11. data/vendor/assets/javascripts/1.3.2/angular-sanitize.js +678 -0
  12. data/vendor/assets/javascripts/1.3.2/angular-scenario.js +37076 -0
  13. data/vendor/assets/javascripts/1.3.2/angular-touch.js +622 -0
  14. data/vendor/assets/javascripts/1.3.2/angular.js +25722 -0
  15. data/vendor/assets/javascripts/angular-animate.js +1 -1
  16. data/vendor/assets/javascripts/angular-aria.js +12 -1
  17. data/vendor/assets/javascripts/angular-cookies.js +1 -1
  18. data/vendor/assets/javascripts/angular-loader.js +2 -2
  19. data/vendor/assets/javascripts/angular-messages.js +1 -1
  20. data/vendor/assets/javascripts/angular-mocks.js +88 -1
  21. data/vendor/assets/javascripts/angular-resource.js +1 -1
  22. data/vendor/assets/javascripts/angular-route.js +10 -6
  23. data/vendor/assets/javascripts/angular-sanitize.js +1 -1
  24. data/vendor/assets/javascripts/angular-scenario.js +143 -46
  25. data/vendor/assets/javascripts/angular-touch.js +1 -1
  26. data/vendor/assets/javascripts/angular.js +143 -46
  27. metadata +13 -1
@@ -0,0 +1,2376 @@
1
+ /**
2
+ * @license AngularJS v1.3.2
3
+ * (c) 2010-2014 Google, Inc. http://angularjs.org
4
+ * License: MIT
5
+ */
6
+ (function(window, angular, undefined) {
7
+
8
+ 'use strict';
9
+
10
+ /**
11
+ * @ngdoc object
12
+ * @name angular.mock
13
+ * @description
14
+ *
15
+ * Namespace from 'angular-mocks.js' which contains testing related code.
16
+ */
17
+ angular.mock = {};
18
+
19
+ /**
20
+ * ! This is a private undocumented service !
21
+ *
22
+ * @name $browser
23
+ *
24
+ * @description
25
+ * This service is a mock implementation of {@link ng.$browser}. It provides fake
26
+ * implementation for commonly used browser apis that are hard to test, e.g. setTimeout, xhr,
27
+ * cookies, etc...
28
+ *
29
+ * The api of this service is the same as that of the real {@link ng.$browser $browser}, except
30
+ * that there are several helper methods available which can be used in tests.
31
+ */
32
+ angular.mock.$BrowserProvider = function() {
33
+ this.$get = function() {
34
+ return new angular.mock.$Browser();
35
+ };
36
+ };
37
+
38
+ angular.mock.$Browser = function() {
39
+ var self = this;
40
+
41
+ this.isMock = true;
42
+ self.$$url = "http://server/";
43
+ self.$$lastUrl = self.$$url; // used by url polling fn
44
+ self.pollFns = [];
45
+
46
+ // TODO(vojta): remove this temporary api
47
+ self.$$completeOutstandingRequest = angular.noop;
48
+ self.$$incOutstandingRequestCount = angular.noop;
49
+
50
+
51
+ // register url polling fn
52
+
53
+ self.onUrlChange = function(listener) {
54
+ self.pollFns.push(
55
+ function() {
56
+ if (self.$$lastUrl !== self.$$url || self.$$state !== self.$$lastState) {
57
+ self.$$lastUrl = self.$$url;
58
+ self.$$lastState = self.$$state;
59
+ listener(self.$$url, self.$$state);
60
+ }
61
+ }
62
+ );
63
+
64
+ return listener;
65
+ };
66
+
67
+ self.$$checkUrlChange = angular.noop;
68
+
69
+ self.cookieHash = {};
70
+ self.lastCookieHash = {};
71
+ self.deferredFns = [];
72
+ self.deferredNextId = 0;
73
+
74
+ self.defer = function(fn, delay) {
75
+ delay = delay || 0;
76
+ self.deferredFns.push({time:(self.defer.now + delay), fn:fn, id: self.deferredNextId});
77
+ self.deferredFns.sort(function(a, b) { return a.time - b.time;});
78
+ return self.deferredNextId++;
79
+ };
80
+
81
+
82
+ /**
83
+ * @name $browser#defer.now
84
+ *
85
+ * @description
86
+ * Current milliseconds mock time.
87
+ */
88
+ self.defer.now = 0;
89
+
90
+
91
+ self.defer.cancel = function(deferId) {
92
+ var fnIndex;
93
+
94
+ angular.forEach(self.deferredFns, function(fn, index) {
95
+ if (fn.id === deferId) fnIndex = index;
96
+ });
97
+
98
+ if (fnIndex !== undefined) {
99
+ self.deferredFns.splice(fnIndex, 1);
100
+ return true;
101
+ }
102
+
103
+ return false;
104
+ };
105
+
106
+
107
+ /**
108
+ * @name $browser#defer.flush
109
+ *
110
+ * @description
111
+ * Flushes all pending requests and executes the defer callbacks.
112
+ *
113
+ * @param {number=} number of milliseconds to flush. See {@link #defer.now}
114
+ */
115
+ self.defer.flush = function(delay) {
116
+ if (angular.isDefined(delay)) {
117
+ self.defer.now += delay;
118
+ } else {
119
+ if (self.deferredFns.length) {
120
+ self.defer.now = self.deferredFns[self.deferredFns.length-1].time;
121
+ } else {
122
+ throw new Error('No deferred tasks to be flushed');
123
+ }
124
+ }
125
+
126
+ while (self.deferredFns.length && self.deferredFns[0].time <= self.defer.now) {
127
+ self.deferredFns.shift().fn();
128
+ }
129
+ };
130
+
131
+ self.$$baseHref = '/';
132
+ self.baseHref = function() {
133
+ return this.$$baseHref;
134
+ };
135
+ };
136
+ angular.mock.$Browser.prototype = {
137
+
138
+ /**
139
+ * @name $browser#poll
140
+ *
141
+ * @description
142
+ * run all fns in pollFns
143
+ */
144
+ poll: function poll() {
145
+ angular.forEach(this.pollFns, function(pollFn) {
146
+ pollFn();
147
+ });
148
+ },
149
+
150
+ addPollFn: function(pollFn) {
151
+ this.pollFns.push(pollFn);
152
+ return pollFn;
153
+ },
154
+
155
+ url: function(url, replace, state) {
156
+ if (angular.isUndefined(state)) {
157
+ state = null;
158
+ }
159
+ if (url) {
160
+ this.$$url = url;
161
+ // Native pushState serializes & copies the object; simulate it.
162
+ this.$$state = angular.copy(state);
163
+ return this;
164
+ }
165
+
166
+ return this.$$url;
167
+ },
168
+
169
+ state: function() {
170
+ return this.$$state;
171
+ },
172
+
173
+ cookies: function(name, value) {
174
+ if (name) {
175
+ if (angular.isUndefined(value)) {
176
+ delete this.cookieHash[name];
177
+ } else {
178
+ if (angular.isString(value) && //strings only
179
+ value.length <= 4096) { //strict cookie storage limits
180
+ this.cookieHash[name] = value;
181
+ }
182
+ }
183
+ } else {
184
+ if (!angular.equals(this.cookieHash, this.lastCookieHash)) {
185
+ this.lastCookieHash = angular.copy(this.cookieHash);
186
+ this.cookieHash = angular.copy(this.cookieHash);
187
+ }
188
+ return this.cookieHash;
189
+ }
190
+ },
191
+
192
+ notifyWhenNoOutstandingRequests: function(fn) {
193
+ fn();
194
+ }
195
+ };
196
+
197
+
198
+ /**
199
+ * @ngdoc provider
200
+ * @name $exceptionHandlerProvider
201
+ *
202
+ * @description
203
+ * Configures the mock implementation of {@link ng.$exceptionHandler} to rethrow or to log errors
204
+ * passed to the `$exceptionHandler`.
205
+ */
206
+
207
+ /**
208
+ * @ngdoc service
209
+ * @name $exceptionHandler
210
+ *
211
+ * @description
212
+ * Mock implementation of {@link ng.$exceptionHandler} that rethrows or logs errors passed
213
+ * to it. See {@link ngMock.$exceptionHandlerProvider $exceptionHandlerProvider} for configuration
214
+ * information.
215
+ *
216
+ *
217
+ * ```js
218
+ * describe('$exceptionHandlerProvider', function() {
219
+ *
220
+ * it('should capture log messages and exceptions', function() {
221
+ *
222
+ * module(function($exceptionHandlerProvider) {
223
+ * $exceptionHandlerProvider.mode('log');
224
+ * });
225
+ *
226
+ * inject(function($log, $exceptionHandler, $timeout) {
227
+ * $timeout(function() { $log.log(1); });
228
+ * $timeout(function() { $log.log(2); throw 'banana peel'; });
229
+ * $timeout(function() { $log.log(3); });
230
+ * expect($exceptionHandler.errors).toEqual([]);
231
+ * expect($log.assertEmpty());
232
+ * $timeout.flush();
233
+ * expect($exceptionHandler.errors).toEqual(['banana peel']);
234
+ * expect($log.log.logs).toEqual([[1], [2], [3]]);
235
+ * });
236
+ * });
237
+ * });
238
+ * ```
239
+ */
240
+
241
+ angular.mock.$ExceptionHandlerProvider = function() {
242
+ var handler;
243
+
244
+ /**
245
+ * @ngdoc method
246
+ * @name $exceptionHandlerProvider#mode
247
+ *
248
+ * @description
249
+ * Sets the logging mode.
250
+ *
251
+ * @param {string} mode Mode of operation, defaults to `rethrow`.
252
+ *
253
+ * - `rethrow`: If any errors are passed to the handler in tests, it typically means that there
254
+ * is a bug in the application or test, so this mock will make these tests fail.
255
+ * - `log`: Sometimes it is desirable to test that an error is thrown, for this case the `log`
256
+ * mode stores an array of errors in `$exceptionHandler.errors`, to allow later
257
+ * assertion of them. See {@link ngMock.$log#assertEmpty assertEmpty()} and
258
+ * {@link ngMock.$log#reset reset()}
259
+ */
260
+ this.mode = function(mode) {
261
+ switch (mode) {
262
+ case 'rethrow':
263
+ handler = function(e) {
264
+ throw e;
265
+ };
266
+ break;
267
+ case 'log':
268
+ var errors = [];
269
+
270
+ handler = function(e) {
271
+ if (arguments.length == 1) {
272
+ errors.push(e);
273
+ } else {
274
+ errors.push([].slice.call(arguments, 0));
275
+ }
276
+ };
277
+
278
+ handler.errors = errors;
279
+ break;
280
+ default:
281
+ throw new Error("Unknown mode '" + mode + "', only 'log'/'rethrow' modes are allowed!");
282
+ }
283
+ };
284
+
285
+ this.$get = function() {
286
+ return handler;
287
+ };
288
+
289
+ this.mode('rethrow');
290
+ };
291
+
292
+
293
+ /**
294
+ * @ngdoc service
295
+ * @name $log
296
+ *
297
+ * @description
298
+ * Mock implementation of {@link ng.$log} that gathers all logged messages in arrays
299
+ * (one array per logging level). These arrays are exposed as `logs` property of each of the
300
+ * level-specific log function, e.g. for level `error` the array is exposed as `$log.error.logs`.
301
+ *
302
+ */
303
+ angular.mock.$LogProvider = function() {
304
+ var debug = true;
305
+
306
+ function concat(array1, array2, index) {
307
+ return array1.concat(Array.prototype.slice.call(array2, index));
308
+ }
309
+
310
+ this.debugEnabled = function(flag) {
311
+ if (angular.isDefined(flag)) {
312
+ debug = flag;
313
+ return this;
314
+ } else {
315
+ return debug;
316
+ }
317
+ };
318
+
319
+ this.$get = function() {
320
+ var $log = {
321
+ log: function() { $log.log.logs.push(concat([], arguments, 0)); },
322
+ warn: function() { $log.warn.logs.push(concat([], arguments, 0)); },
323
+ info: function() { $log.info.logs.push(concat([], arguments, 0)); },
324
+ error: function() { $log.error.logs.push(concat([], arguments, 0)); },
325
+ debug: function() {
326
+ if (debug) {
327
+ $log.debug.logs.push(concat([], arguments, 0));
328
+ }
329
+ }
330
+ };
331
+
332
+ /**
333
+ * @ngdoc method
334
+ * @name $log#reset
335
+ *
336
+ * @description
337
+ * Reset all of the logging arrays to empty.
338
+ */
339
+ $log.reset = function() {
340
+ /**
341
+ * @ngdoc property
342
+ * @name $log#log.logs
343
+ *
344
+ * @description
345
+ * Array of messages logged using {@link ng.$log#log `log()`}.
346
+ *
347
+ * @example
348
+ * ```js
349
+ * $log.log('Some Log');
350
+ * var first = $log.log.logs.unshift();
351
+ * ```
352
+ */
353
+ $log.log.logs = [];
354
+ /**
355
+ * @ngdoc property
356
+ * @name $log#info.logs
357
+ *
358
+ * @description
359
+ * Array of messages logged using {@link ng.$log#info `info()`}.
360
+ *
361
+ * @example
362
+ * ```js
363
+ * $log.info('Some Info');
364
+ * var first = $log.info.logs.unshift();
365
+ * ```
366
+ */
367
+ $log.info.logs = [];
368
+ /**
369
+ * @ngdoc property
370
+ * @name $log#warn.logs
371
+ *
372
+ * @description
373
+ * Array of messages logged using {@link ng.$log#warn `warn()`}.
374
+ *
375
+ * @example
376
+ * ```js
377
+ * $log.warn('Some Warning');
378
+ * var first = $log.warn.logs.unshift();
379
+ * ```
380
+ */
381
+ $log.warn.logs = [];
382
+ /**
383
+ * @ngdoc property
384
+ * @name $log#error.logs
385
+ *
386
+ * @description
387
+ * Array of messages logged using {@link ng.$log#error `error()`}.
388
+ *
389
+ * @example
390
+ * ```js
391
+ * $log.error('Some Error');
392
+ * var first = $log.error.logs.unshift();
393
+ * ```
394
+ */
395
+ $log.error.logs = [];
396
+ /**
397
+ * @ngdoc property
398
+ * @name $log#debug.logs
399
+ *
400
+ * @description
401
+ * Array of messages logged using {@link ng.$log#debug `debug()`}.
402
+ *
403
+ * @example
404
+ * ```js
405
+ * $log.debug('Some Error');
406
+ * var first = $log.debug.logs.unshift();
407
+ * ```
408
+ */
409
+ $log.debug.logs = [];
410
+ };
411
+
412
+ /**
413
+ * @ngdoc method
414
+ * @name $log#assertEmpty
415
+ *
416
+ * @description
417
+ * Assert that all of the logging methods have no logged messages. If any messages are present,
418
+ * an exception is thrown.
419
+ */
420
+ $log.assertEmpty = function() {
421
+ var errors = [];
422
+ angular.forEach(['error', 'warn', 'info', 'log', 'debug'], function(logLevel) {
423
+ angular.forEach($log[logLevel].logs, function(log) {
424
+ angular.forEach(log, function(logItem) {
425
+ errors.push('MOCK $log (' + logLevel + '): ' + String(logItem) + '\n' +
426
+ (logItem.stack || ''));
427
+ });
428
+ });
429
+ });
430
+ if (errors.length) {
431
+ errors.unshift("Expected $log to be empty! Either a message was logged unexpectedly, or "+
432
+ "an expected log message was not checked and removed:");
433
+ errors.push('');
434
+ throw new Error(errors.join('\n---------\n'));
435
+ }
436
+ };
437
+
438
+ $log.reset();
439
+ return $log;
440
+ };
441
+ };
442
+
443
+
444
+ /**
445
+ * @ngdoc service
446
+ * @name $interval
447
+ *
448
+ * @description
449
+ * Mock implementation of the $interval service.
450
+ *
451
+ * Use {@link ngMock.$interval#flush `$interval.flush(millis)`} to
452
+ * move forward by `millis` milliseconds and trigger any functions scheduled to run in that
453
+ * time.
454
+ *
455
+ * @param {function()} fn A function that should be called repeatedly.
456
+ * @param {number} delay Number of milliseconds between each function call.
457
+ * @param {number=} [count=0] Number of times to repeat. If not set, or 0, will repeat
458
+ * indefinitely.
459
+ * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
460
+ * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
461
+ * @returns {promise} A promise which will be notified on each iteration.
462
+ */
463
+ angular.mock.$IntervalProvider = function() {
464
+ this.$get = ['$rootScope', '$q',
465
+ function($rootScope, $q) {
466
+ var repeatFns = [],
467
+ nextRepeatId = 0,
468
+ now = 0;
469
+
470
+ var $interval = function(fn, delay, count, invokeApply) {
471
+ var deferred = $q.defer(),
472
+ promise = deferred.promise,
473
+ iteration = 0,
474
+ skipApply = (angular.isDefined(invokeApply) && !invokeApply);
475
+
476
+ count = (angular.isDefined(count)) ? count : 0;
477
+ promise.then(null, null, fn);
478
+
479
+ promise.$$intervalId = nextRepeatId;
480
+
481
+ function tick() {
482
+ deferred.notify(iteration++);
483
+
484
+ if (count > 0 && iteration >= count) {
485
+ var fnIndex;
486
+ deferred.resolve(iteration);
487
+
488
+ angular.forEach(repeatFns, function(fn, index) {
489
+ if (fn.id === promise.$$intervalId) fnIndex = index;
490
+ });
491
+
492
+ if (fnIndex !== undefined) {
493
+ repeatFns.splice(fnIndex, 1);
494
+ }
495
+ }
496
+
497
+ if (!skipApply) $rootScope.$apply();
498
+ }
499
+
500
+ repeatFns.push({
501
+ nextTime:(now + delay),
502
+ delay: delay,
503
+ fn: tick,
504
+ id: nextRepeatId,
505
+ deferred: deferred
506
+ });
507
+ repeatFns.sort(function(a, b) { return a.nextTime - b.nextTime;});
508
+
509
+ nextRepeatId++;
510
+ return promise;
511
+ };
512
+ /**
513
+ * @ngdoc method
514
+ * @name $interval#cancel
515
+ *
516
+ * @description
517
+ * Cancels a task associated with the `promise`.
518
+ *
519
+ * @param {promise} promise A promise from calling the `$interval` function.
520
+ * @returns {boolean} Returns `true` if the task was successfully cancelled.
521
+ */
522
+ $interval.cancel = function(promise) {
523
+ if (!promise) return false;
524
+ var fnIndex;
525
+
526
+ angular.forEach(repeatFns, function(fn, index) {
527
+ if (fn.id === promise.$$intervalId) fnIndex = index;
528
+ });
529
+
530
+ if (fnIndex !== undefined) {
531
+ repeatFns[fnIndex].deferred.reject('canceled');
532
+ repeatFns.splice(fnIndex, 1);
533
+ return true;
534
+ }
535
+
536
+ return false;
537
+ };
538
+
539
+ /**
540
+ * @ngdoc method
541
+ * @name $interval#flush
542
+ * @description
543
+ *
544
+ * Runs interval tasks scheduled to be run in the next `millis` milliseconds.
545
+ *
546
+ * @param {number=} millis maximum timeout amount to flush up until.
547
+ *
548
+ * @return {number} The amount of time moved forward.
549
+ */
550
+ $interval.flush = function(millis) {
551
+ now += millis;
552
+ while (repeatFns.length && repeatFns[0].nextTime <= now) {
553
+ var task = repeatFns[0];
554
+ task.fn();
555
+ task.nextTime += task.delay;
556
+ repeatFns.sort(function(a, b) { return a.nextTime - b.nextTime;});
557
+ }
558
+ return millis;
559
+ };
560
+
561
+ return $interval;
562
+ }];
563
+ };
564
+
565
+
566
+ /* jshint -W101 */
567
+ /* The R_ISO8061_STR regex is never going to fit into the 100 char limit!
568
+ * This directive should go inside the anonymous function but a bug in JSHint means that it would
569
+ * not be enacted early enough to prevent the warning.
570
+ */
571
+ var R_ISO8061_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?:\:?(\d\d)(?:\:?(\d\d)(?:\.(\d{3}))?)?)?(Z|([+-])(\d\d):?(\d\d)))?$/;
572
+
573
+ function jsonStringToDate(string) {
574
+ var match;
575
+ if (match = string.match(R_ISO8061_STR)) {
576
+ var date = new Date(0),
577
+ tzHour = 0,
578
+ tzMin = 0;
579
+ if (match[9]) {
580
+ tzHour = int(match[9] + match[10]);
581
+ tzMin = int(match[9] + match[11]);
582
+ }
583
+ date.setUTCFullYear(int(match[1]), int(match[2]) - 1, int(match[3]));
584
+ date.setUTCHours(int(match[4]||0) - tzHour,
585
+ int(match[5]||0) - tzMin,
586
+ int(match[6]||0),
587
+ int(match[7]||0));
588
+ return date;
589
+ }
590
+ return string;
591
+ }
592
+
593
+ function int(str) {
594
+ return parseInt(str, 10);
595
+ }
596
+
597
+ function padNumber(num, digits, trim) {
598
+ var neg = '';
599
+ if (num < 0) {
600
+ neg = '-';
601
+ num = -num;
602
+ }
603
+ num = '' + num;
604
+ while (num.length < digits) num = '0' + num;
605
+ if (trim)
606
+ num = num.substr(num.length - digits);
607
+ return neg + num;
608
+ }
609
+
610
+
611
+ /**
612
+ * @ngdoc type
613
+ * @name angular.mock.TzDate
614
+ * @description
615
+ *
616
+ * *NOTE*: this is not an injectable instance, just a globally available mock class of `Date`.
617
+ *
618
+ * Mock of the Date type which has its timezone specified via constructor arg.
619
+ *
620
+ * The main purpose is to create Date-like instances with timezone fixed to the specified timezone
621
+ * offset, so that we can test code that depends on local timezone settings without dependency on
622
+ * the time zone settings of the machine where the code is running.
623
+ *
624
+ * @param {number} offset Offset of the *desired* timezone in hours (fractions will be honored)
625
+ * @param {(number|string)} timestamp Timestamp representing the desired time in *UTC*
626
+ *
627
+ * @example
628
+ * !!!! WARNING !!!!!
629
+ * This is not a complete Date object so only methods that were implemented can be called safely.
630
+ * To make matters worse, TzDate instances inherit stuff from Date via a prototype.
631
+ *
632
+ * We do our best to intercept calls to "unimplemented" methods, but since the list of methods is
633
+ * incomplete we might be missing some non-standard methods. This can result in errors like:
634
+ * "Date.prototype.foo called on incompatible Object".
635
+ *
636
+ * ```js
637
+ * var newYearInBratislava = new TzDate(-1, '2009-12-31T23:00:00Z');
638
+ * newYearInBratislava.getTimezoneOffset() => -60;
639
+ * newYearInBratislava.getFullYear() => 2010;
640
+ * newYearInBratislava.getMonth() => 0;
641
+ * newYearInBratislava.getDate() => 1;
642
+ * newYearInBratislava.getHours() => 0;
643
+ * newYearInBratislava.getMinutes() => 0;
644
+ * newYearInBratislava.getSeconds() => 0;
645
+ * ```
646
+ *
647
+ */
648
+ angular.mock.TzDate = function(offset, timestamp) {
649
+ var self = new Date(0);
650
+ if (angular.isString(timestamp)) {
651
+ var tsStr = timestamp;
652
+
653
+ self.origDate = jsonStringToDate(timestamp);
654
+
655
+ timestamp = self.origDate.getTime();
656
+ if (isNaN(timestamp))
657
+ throw {
658
+ name: "Illegal Argument",
659
+ message: "Arg '" + tsStr + "' passed into TzDate constructor is not a valid date string"
660
+ };
661
+ } else {
662
+ self.origDate = new Date(timestamp);
663
+ }
664
+
665
+ var localOffset = new Date(timestamp).getTimezoneOffset();
666
+ self.offsetDiff = localOffset*60*1000 - offset*1000*60*60;
667
+ self.date = new Date(timestamp + self.offsetDiff);
668
+
669
+ self.getTime = function() {
670
+ return self.date.getTime() - self.offsetDiff;
671
+ };
672
+
673
+ self.toLocaleDateString = function() {
674
+ return self.date.toLocaleDateString();
675
+ };
676
+
677
+ self.getFullYear = function() {
678
+ return self.date.getFullYear();
679
+ };
680
+
681
+ self.getMonth = function() {
682
+ return self.date.getMonth();
683
+ };
684
+
685
+ self.getDate = function() {
686
+ return self.date.getDate();
687
+ };
688
+
689
+ self.getHours = function() {
690
+ return self.date.getHours();
691
+ };
692
+
693
+ self.getMinutes = function() {
694
+ return self.date.getMinutes();
695
+ };
696
+
697
+ self.getSeconds = function() {
698
+ return self.date.getSeconds();
699
+ };
700
+
701
+ self.getMilliseconds = function() {
702
+ return self.date.getMilliseconds();
703
+ };
704
+
705
+ self.getTimezoneOffset = function() {
706
+ return offset * 60;
707
+ };
708
+
709
+ self.getUTCFullYear = function() {
710
+ return self.origDate.getUTCFullYear();
711
+ };
712
+
713
+ self.getUTCMonth = function() {
714
+ return self.origDate.getUTCMonth();
715
+ };
716
+
717
+ self.getUTCDate = function() {
718
+ return self.origDate.getUTCDate();
719
+ };
720
+
721
+ self.getUTCHours = function() {
722
+ return self.origDate.getUTCHours();
723
+ };
724
+
725
+ self.getUTCMinutes = function() {
726
+ return self.origDate.getUTCMinutes();
727
+ };
728
+
729
+ self.getUTCSeconds = function() {
730
+ return self.origDate.getUTCSeconds();
731
+ };
732
+
733
+ self.getUTCMilliseconds = function() {
734
+ return self.origDate.getUTCMilliseconds();
735
+ };
736
+
737
+ self.getDay = function() {
738
+ return self.date.getDay();
739
+ };
740
+
741
+ // provide this method only on browsers that already have it
742
+ if (self.toISOString) {
743
+ self.toISOString = function() {
744
+ return padNumber(self.origDate.getUTCFullYear(), 4) + '-' +
745
+ padNumber(self.origDate.getUTCMonth() + 1, 2) + '-' +
746
+ padNumber(self.origDate.getUTCDate(), 2) + 'T' +
747
+ padNumber(self.origDate.getUTCHours(), 2) + ':' +
748
+ padNumber(self.origDate.getUTCMinutes(), 2) + ':' +
749
+ padNumber(self.origDate.getUTCSeconds(), 2) + '.' +
750
+ padNumber(self.origDate.getUTCMilliseconds(), 3) + 'Z';
751
+ };
752
+ }
753
+
754
+ //hide all methods not implemented in this mock that the Date prototype exposes
755
+ var unimplementedMethods = ['getUTCDay',
756
+ 'getYear', 'setDate', 'setFullYear', 'setHours', 'setMilliseconds',
757
+ 'setMinutes', 'setMonth', 'setSeconds', 'setTime', 'setUTCDate', 'setUTCFullYear',
758
+ 'setUTCHours', 'setUTCMilliseconds', 'setUTCMinutes', 'setUTCMonth', 'setUTCSeconds',
759
+ 'setYear', 'toDateString', 'toGMTString', 'toJSON', 'toLocaleFormat', 'toLocaleString',
760
+ 'toLocaleTimeString', 'toSource', 'toString', 'toTimeString', 'toUTCString', 'valueOf'];
761
+
762
+ angular.forEach(unimplementedMethods, function(methodName) {
763
+ self[methodName] = function() {
764
+ throw new Error("Method '" + methodName + "' is not implemented in the TzDate mock");
765
+ };
766
+ });
767
+
768
+ return self;
769
+ };
770
+
771
+ //make "tzDateInstance instanceof Date" return true
772
+ angular.mock.TzDate.prototype = Date.prototype;
773
+ /* jshint +W101 */
774
+
775
+ angular.mock.animate = angular.module('ngAnimateMock', ['ng'])
776
+
777
+ .config(['$provide', function($provide) {
778
+
779
+ var reflowQueue = [];
780
+ $provide.value('$$animateReflow', function(fn) {
781
+ var index = reflowQueue.length;
782
+ reflowQueue.push(fn);
783
+ return function cancel() {
784
+ reflowQueue.splice(index, 1);
785
+ };
786
+ });
787
+
788
+ $provide.decorator('$animate', ['$delegate', '$$asyncCallback', '$timeout', '$browser',
789
+ function($delegate, $$asyncCallback, $timeout, $browser) {
790
+ var animate = {
791
+ queue: [],
792
+ cancel: $delegate.cancel,
793
+ enabled: $delegate.enabled,
794
+ triggerCallbackEvents: function() {
795
+ $$asyncCallback.flush();
796
+ },
797
+ triggerCallbackPromise: function() {
798
+ $timeout.flush(0);
799
+ },
800
+ triggerCallbacks: function() {
801
+ this.triggerCallbackEvents();
802
+ this.triggerCallbackPromise();
803
+ },
804
+ triggerReflow: function() {
805
+ angular.forEach(reflowQueue, function(fn) {
806
+ fn();
807
+ });
808
+ reflowQueue = [];
809
+ }
810
+ };
811
+
812
+ angular.forEach(
813
+ ['animate','enter','leave','move','addClass','removeClass','setClass'], function(method) {
814
+ animate[method] = function() {
815
+ animate.queue.push({
816
+ event: method,
817
+ element: arguments[0],
818
+ options: arguments[arguments.length-1],
819
+ args: arguments
820
+ });
821
+ return $delegate[method].apply($delegate, arguments);
822
+ };
823
+ });
824
+
825
+ return animate;
826
+ }]);
827
+
828
+ }]);
829
+
830
+
831
+ /**
832
+ * @ngdoc function
833
+ * @name angular.mock.dump
834
+ * @description
835
+ *
836
+ * *NOTE*: this is not an injectable instance, just a globally available function.
837
+ *
838
+ * Method for serializing common angular objects (scope, elements, etc..) into strings, useful for
839
+ * debugging.
840
+ *
841
+ * This method is also available on window, where it can be used to display objects on debug
842
+ * console.
843
+ *
844
+ * @param {*} object - any object to turn into string.
845
+ * @return {string} a serialized string of the argument
846
+ */
847
+ angular.mock.dump = function(object) {
848
+ return serialize(object);
849
+
850
+ function serialize(object) {
851
+ var out;
852
+
853
+ if (angular.isElement(object)) {
854
+ object = angular.element(object);
855
+ out = angular.element('<div></div>');
856
+ angular.forEach(object, function(element) {
857
+ out.append(angular.element(element).clone());
858
+ });
859
+ out = out.html();
860
+ } else if (angular.isArray(object)) {
861
+ out = [];
862
+ angular.forEach(object, function(o) {
863
+ out.push(serialize(o));
864
+ });
865
+ out = '[ ' + out.join(', ') + ' ]';
866
+ } else if (angular.isObject(object)) {
867
+ if (angular.isFunction(object.$eval) && angular.isFunction(object.$apply)) {
868
+ out = serializeScope(object);
869
+ } else if (object instanceof Error) {
870
+ out = object.stack || ('' + object.name + ': ' + object.message);
871
+ } else {
872
+ // TODO(i): this prevents methods being logged,
873
+ // we should have a better way to serialize objects
874
+ out = angular.toJson(object, true);
875
+ }
876
+ } else {
877
+ out = String(object);
878
+ }
879
+
880
+ return out;
881
+ }
882
+
883
+ function serializeScope(scope, offset) {
884
+ offset = offset || ' ';
885
+ var log = [offset + 'Scope(' + scope.$id + '): {'];
886
+ for (var key in scope) {
887
+ if (Object.prototype.hasOwnProperty.call(scope, key) && !key.match(/^(\$|this)/)) {
888
+ log.push(' ' + key + ': ' + angular.toJson(scope[key]));
889
+ }
890
+ }
891
+ var child = scope.$$childHead;
892
+ while (child) {
893
+ log.push(serializeScope(child, offset + ' '));
894
+ child = child.$$nextSibling;
895
+ }
896
+ log.push('}');
897
+ return log.join('\n' + offset);
898
+ }
899
+ };
900
+
901
+ /**
902
+ * @ngdoc service
903
+ * @name $httpBackend
904
+ * @description
905
+ * Fake HTTP backend implementation suitable for unit testing applications that use the
906
+ * {@link ng.$http $http service}.
907
+ *
908
+ * *Note*: For fake HTTP backend implementation suitable for end-to-end testing or backend-less
909
+ * development please see {@link ngMockE2E.$httpBackend e2e $httpBackend mock}.
910
+ *
911
+ * During unit testing, we want our unit tests to run quickly and have no external dependencies so
912
+ * we don’t want to send [XHR](https://developer.mozilla.org/en/xmlhttprequest) or
913
+ * [JSONP](http://en.wikipedia.org/wiki/JSONP) requests to a real server. All we really need is
914
+ * to verify whether a certain request has been sent or not, or alternatively just let the
915
+ * application make requests, respond with pre-trained responses and assert that the end result is
916
+ * what we expect it to be.
917
+ *
918
+ * This mock implementation can be used to respond with static or dynamic responses via the
919
+ * `expect` and `when` apis and their shortcuts (`expectGET`, `whenPOST`, etc).
920
+ *
921
+ * When an Angular application needs some data from a server, it calls the $http service, which
922
+ * sends the request to a real server using $httpBackend service. With dependency injection, it is
923
+ * easy to inject $httpBackend mock (which has the same API as $httpBackend) and use it to verify
924
+ * the requests and respond with some testing data without sending a request to a real server.
925
+ *
926
+ * There are two ways to specify what test data should be returned as http responses by the mock
927
+ * backend when the code under test makes http requests:
928
+ *
929
+ * - `$httpBackend.expect` - specifies a request expectation
930
+ * - `$httpBackend.when` - specifies a backend definition
931
+ *
932
+ *
933
+ * # Request Expectations vs Backend Definitions
934
+ *
935
+ * Request expectations provide a way to make assertions about requests made by the application and
936
+ * to define responses for those requests. The test will fail if the expected requests are not made
937
+ * or they are made in the wrong order.
938
+ *
939
+ * Backend definitions allow you to define a fake backend for your application which doesn't assert
940
+ * if a particular request was made or not, it just returns a trained response if a request is made.
941
+ * The test will pass whether or not the request gets made during testing.
942
+ *
943
+ *
944
+ * <table class="table">
945
+ * <tr><th width="220px"></th><th>Request expectations</th><th>Backend definitions</th></tr>
946
+ * <tr>
947
+ * <th>Syntax</th>
948
+ * <td>.expect(...).respond(...)</td>
949
+ * <td>.when(...).respond(...)</td>
950
+ * </tr>
951
+ * <tr>
952
+ * <th>Typical usage</th>
953
+ * <td>strict unit tests</td>
954
+ * <td>loose (black-box) unit testing</td>
955
+ * </tr>
956
+ * <tr>
957
+ * <th>Fulfills multiple requests</th>
958
+ * <td>NO</td>
959
+ * <td>YES</td>
960
+ * </tr>
961
+ * <tr>
962
+ * <th>Order of requests matters</th>
963
+ * <td>YES</td>
964
+ * <td>NO</td>
965
+ * </tr>
966
+ * <tr>
967
+ * <th>Request required</th>
968
+ * <td>YES</td>
969
+ * <td>NO</td>
970
+ * </tr>
971
+ * <tr>
972
+ * <th>Response required</th>
973
+ * <td>optional (see below)</td>
974
+ * <td>YES</td>
975
+ * </tr>
976
+ * </table>
977
+ *
978
+ * In cases where both backend definitions and request expectations are specified during unit
979
+ * testing, the request expectations are evaluated first.
980
+ *
981
+ * If a request expectation has no response specified, the algorithm will search your backend
982
+ * definitions for an appropriate response.
983
+ *
984
+ * If a request didn't match any expectation or if the expectation doesn't have the response
985
+ * defined, the backend definitions are evaluated in sequential order to see if any of them match
986
+ * the request. The response from the first matched definition is returned.
987
+ *
988
+ *
989
+ * # Flushing HTTP requests
990
+ *
991
+ * The $httpBackend used in production always responds to requests asynchronously. If we preserved
992
+ * this behavior in unit testing, we'd have to create async unit tests, which are hard to write,
993
+ * to follow and to maintain. But neither can the testing mock respond synchronously; that would
994
+ * change the execution of the code under test. For this reason, the mock $httpBackend has a
995
+ * `flush()` method, which allows the test to explicitly flush pending requests. This preserves
996
+ * the async api of the backend, while allowing the test to execute synchronously.
997
+ *
998
+ *
999
+ * # Unit testing with mock $httpBackend
1000
+ * The following code shows how to setup and use the mock backend when unit testing a controller.
1001
+ * First we create the controller under test:
1002
+ *
1003
+ ```js
1004
+ // The module code
1005
+ angular
1006
+ .module('MyApp', [])
1007
+ .controller('MyController', MyController);
1008
+
1009
+ // The controller code
1010
+ function MyController($scope, $http) {
1011
+ var authToken;
1012
+
1013
+ $http.get('/auth.py').success(function(data, status, headers) {
1014
+ authToken = headers('A-Token');
1015
+ $scope.user = data;
1016
+ });
1017
+
1018
+ $scope.saveMessage = function(message) {
1019
+ var headers = { 'Authorization': authToken };
1020
+ $scope.status = 'Saving...';
1021
+
1022
+ $http.post('/add-msg.py', message, { headers: headers } ).success(function(response) {
1023
+ $scope.status = '';
1024
+ }).error(function() {
1025
+ $scope.status = 'ERROR!';
1026
+ });
1027
+ };
1028
+ }
1029
+ ```
1030
+ *
1031
+ * Now we setup the mock backend and create the test specs:
1032
+ *
1033
+ ```js
1034
+ // testing controller
1035
+ describe('MyController', function() {
1036
+ var $httpBackend, $rootScope, createController, authRequestHandler;
1037
+
1038
+ // Set up the module
1039
+ beforeEach(module('MyApp'));
1040
+
1041
+ beforeEach(inject(function($injector) {
1042
+ // Set up the mock http service responses
1043
+ $httpBackend = $injector.get('$httpBackend');
1044
+ // backend definition common for all tests
1045
+ authRequestHandler = $httpBackend.when('GET', '/auth.py')
1046
+ .respond({userId: 'userX'}, {'A-Token': 'xxx'});
1047
+
1048
+ // Get hold of a scope (i.e. the root scope)
1049
+ $rootScope = $injector.get('$rootScope');
1050
+ // The $controller service is used to create instances of controllers
1051
+ var $controller = $injector.get('$controller');
1052
+
1053
+ createController = function() {
1054
+ return $controller('MyController', {'$scope' : $rootScope });
1055
+ };
1056
+ }));
1057
+
1058
+
1059
+ afterEach(function() {
1060
+ $httpBackend.verifyNoOutstandingExpectation();
1061
+ $httpBackend.verifyNoOutstandingRequest();
1062
+ });
1063
+
1064
+
1065
+ it('should fetch authentication token', function() {
1066
+ $httpBackend.expectGET('/auth.py');
1067
+ var controller = createController();
1068
+ $httpBackend.flush();
1069
+ });
1070
+
1071
+
1072
+ it('should fail authentication', function() {
1073
+
1074
+ // Notice how you can change the response even after it was set
1075
+ authRequestHandler.respond(401, '');
1076
+
1077
+ $httpBackend.expectGET('/auth.py');
1078
+ var controller = createController();
1079
+ $httpBackend.flush();
1080
+ expect($rootScope.status).toBe('Failed...');
1081
+ });
1082
+
1083
+
1084
+ it('should send msg to server', function() {
1085
+ var controller = createController();
1086
+ $httpBackend.flush();
1087
+
1088
+ // now you don’t care about the authentication, but
1089
+ // the controller will still send the request and
1090
+ // $httpBackend will respond without you having to
1091
+ // specify the expectation and response for this request
1092
+
1093
+ $httpBackend.expectPOST('/add-msg.py', 'message content').respond(201, '');
1094
+ $rootScope.saveMessage('message content');
1095
+ expect($rootScope.status).toBe('Saving...');
1096
+ $httpBackend.flush();
1097
+ expect($rootScope.status).toBe('');
1098
+ });
1099
+
1100
+
1101
+ it('should send auth header', function() {
1102
+ var controller = createController();
1103
+ $httpBackend.flush();
1104
+
1105
+ $httpBackend.expectPOST('/add-msg.py', undefined, function(headers) {
1106
+ // check if the header was send, if it wasn't the expectation won't
1107
+ // match the request and the test will fail
1108
+ return headers['Authorization'] == 'xxx';
1109
+ }).respond(201, '');
1110
+
1111
+ $rootScope.saveMessage('whatever');
1112
+ $httpBackend.flush();
1113
+ });
1114
+ });
1115
+ ```
1116
+ */
1117
+ angular.mock.$HttpBackendProvider = function() {
1118
+ this.$get = ['$rootScope', createHttpBackendMock];
1119
+ };
1120
+
1121
+ /**
1122
+ * General factory function for $httpBackend mock.
1123
+ * Returns instance for unit testing (when no arguments specified):
1124
+ * - passing through is disabled
1125
+ * - auto flushing is disabled
1126
+ *
1127
+ * Returns instance for e2e testing (when `$delegate` and `$browser` specified):
1128
+ * - passing through (delegating request to real backend) is enabled
1129
+ * - auto flushing is enabled
1130
+ *
1131
+ * @param {Object=} $delegate Real $httpBackend instance (allow passing through if specified)
1132
+ * @param {Object=} $browser Auto-flushing enabled if specified
1133
+ * @return {Object} Instance of $httpBackend mock
1134
+ */
1135
+ function createHttpBackendMock($rootScope, $delegate, $browser) {
1136
+ var definitions = [],
1137
+ expectations = [],
1138
+ responses = [],
1139
+ responsesPush = angular.bind(responses, responses.push),
1140
+ copy = angular.copy;
1141
+
1142
+ function createResponse(status, data, headers, statusText) {
1143
+ if (angular.isFunction(status)) return status;
1144
+
1145
+ return function() {
1146
+ return angular.isNumber(status)
1147
+ ? [status, data, headers, statusText]
1148
+ : [200, status, data];
1149
+ };
1150
+ }
1151
+
1152
+ // TODO(vojta): change params to: method, url, data, headers, callback
1153
+ function $httpBackend(method, url, data, callback, headers, timeout, withCredentials) {
1154
+ var xhr = new MockXhr(),
1155
+ expectation = expectations[0],
1156
+ wasExpected = false;
1157
+
1158
+ function prettyPrint(data) {
1159
+ return (angular.isString(data) || angular.isFunction(data) || data instanceof RegExp)
1160
+ ? data
1161
+ : angular.toJson(data);
1162
+ }
1163
+
1164
+ function wrapResponse(wrapped) {
1165
+ if (!$browser && timeout && timeout.then) timeout.then(handleTimeout);
1166
+
1167
+ return handleResponse;
1168
+
1169
+ function handleResponse() {
1170
+ var response = wrapped.response(method, url, data, headers);
1171
+ xhr.$$respHeaders = response[2];
1172
+ callback(copy(response[0]), copy(response[1]), xhr.getAllResponseHeaders(),
1173
+ copy(response[3] || ''));
1174
+ }
1175
+
1176
+ function handleTimeout() {
1177
+ for (var i = 0, ii = responses.length; i < ii; i++) {
1178
+ if (responses[i] === handleResponse) {
1179
+ responses.splice(i, 1);
1180
+ callback(-1, undefined, '');
1181
+ break;
1182
+ }
1183
+ }
1184
+ }
1185
+ }
1186
+
1187
+ if (expectation && expectation.match(method, url)) {
1188
+ if (!expectation.matchData(data))
1189
+ throw new Error('Expected ' + expectation + ' with different data\n' +
1190
+ 'EXPECTED: ' + prettyPrint(expectation.data) + '\nGOT: ' + data);
1191
+
1192
+ if (!expectation.matchHeaders(headers))
1193
+ throw new Error('Expected ' + expectation + ' with different headers\n' +
1194
+ 'EXPECTED: ' + prettyPrint(expectation.headers) + '\nGOT: ' +
1195
+ prettyPrint(headers));
1196
+
1197
+ expectations.shift();
1198
+
1199
+ if (expectation.response) {
1200
+ responses.push(wrapResponse(expectation));
1201
+ return;
1202
+ }
1203
+ wasExpected = true;
1204
+ }
1205
+
1206
+ var i = -1, definition;
1207
+ while ((definition = definitions[++i])) {
1208
+ if (definition.match(method, url, data, headers || {})) {
1209
+ if (definition.response) {
1210
+ // if $browser specified, we do auto flush all requests
1211
+ ($browser ? $browser.defer : responsesPush)(wrapResponse(definition));
1212
+ } else if (definition.passThrough) {
1213
+ $delegate(method, url, data, callback, headers, timeout, withCredentials);
1214
+ } else throw new Error('No response defined !');
1215
+ return;
1216
+ }
1217
+ }
1218
+ throw wasExpected ?
1219
+ new Error('No response defined !') :
1220
+ new Error('Unexpected request: ' + method + ' ' + url + '\n' +
1221
+ (expectation ? 'Expected ' + expectation : 'No more request expected'));
1222
+ }
1223
+
1224
+ /**
1225
+ * @ngdoc method
1226
+ * @name $httpBackend#when
1227
+ * @description
1228
+ * Creates a new backend definition.
1229
+ *
1230
+ * @param {string} method HTTP method.
1231
+ * @param {string|RegExp|function(string)} url HTTP url or function that receives the url
1232
+ * and returns true if the url match the current definition.
1233
+ * @param {(string|RegExp|function(string))=} data HTTP request body or function that receives
1234
+ * data string and returns true if the data is as expected.
1235
+ * @param {(Object|function(Object))=} headers HTTP headers or function that receives http header
1236
+ * object and returns true if the headers match the current definition.
1237
+ * @returns {requestHandler} Returns an object with `respond` method that controls how a matched
1238
+ * request is handled. You can save this object for later use and invoke `respond` again in
1239
+ * order to change how a matched request is handled.
1240
+ *
1241
+ * - respond –
1242
+ * `{function([status,] data[, headers, statusText])
1243
+ * | function(function(method, url, data, headers)}`
1244
+ * – The respond method takes a set of static data to be returned or a function that can
1245
+ * return an array containing response status (number), response data (string), response
1246
+ * headers (Object), and the text for the status (string). The respond method returns the
1247
+ * `requestHandler` object for possible overrides.
1248
+ */
1249
+ $httpBackend.when = function(method, url, data, headers) {
1250
+ var definition = new MockHttpExpectation(method, url, data, headers),
1251
+ chain = {
1252
+ respond: function(status, data, headers, statusText) {
1253
+ definition.passThrough = undefined;
1254
+ definition.response = createResponse(status, data, headers, statusText);
1255
+ return chain;
1256
+ }
1257
+ };
1258
+
1259
+ if ($browser) {
1260
+ chain.passThrough = function() {
1261
+ definition.response = undefined;
1262
+ definition.passThrough = true;
1263
+ return chain;
1264
+ };
1265
+ }
1266
+
1267
+ definitions.push(definition);
1268
+ return chain;
1269
+ };
1270
+
1271
+ /**
1272
+ * @ngdoc method
1273
+ * @name $httpBackend#whenGET
1274
+ * @description
1275
+ * Creates a new backend definition for GET requests. For more info see `when()`.
1276
+ *
1277
+ * @param {string|RegExp|function(string)} url HTTP url or function that receives the url
1278
+ * and returns true if the url match the current definition.
1279
+ * @param {(Object|function(Object))=} headers HTTP headers.
1280
+ * @returns {requestHandler} Returns an object with `respond` method that control how a matched
1281
+ * request is handled. You can save this object for later use and invoke `respond` again in
1282
+ * order to change how a matched request is handled.
1283
+ */
1284
+
1285
+ /**
1286
+ * @ngdoc method
1287
+ * @name $httpBackend#whenHEAD
1288
+ * @description
1289
+ * Creates a new backend definition for HEAD requests. For more info see `when()`.
1290
+ *
1291
+ * @param {string|RegExp|function(string)} url HTTP url or function that receives the url
1292
+ * and returns true if the url match the current definition.
1293
+ * @param {(Object|function(Object))=} headers HTTP headers.
1294
+ * @returns {requestHandler} Returns an object with `respond` method that control how a matched
1295
+ * request is handled. You can save this object for later use and invoke `respond` again in
1296
+ * order to change how a matched request is handled.
1297
+ */
1298
+
1299
+ /**
1300
+ * @ngdoc method
1301
+ * @name $httpBackend#whenDELETE
1302
+ * @description
1303
+ * Creates a new backend definition for DELETE requests. For more info see `when()`.
1304
+ *
1305
+ * @param {string|RegExp|function(string)} url HTTP url or function that receives the url
1306
+ * and returns true if the url match the current definition.
1307
+ * @param {(Object|function(Object))=} headers HTTP headers.
1308
+ * @returns {requestHandler} Returns an object with `respond` method that control how a matched
1309
+ * request is handled. You can save this object for later use and invoke `respond` again in
1310
+ * order to change how a matched request is handled.
1311
+ */
1312
+
1313
+ /**
1314
+ * @ngdoc method
1315
+ * @name $httpBackend#whenPOST
1316
+ * @description
1317
+ * Creates a new backend definition for POST requests. For more info see `when()`.
1318
+ *
1319
+ * @param {string|RegExp|function(string)} url HTTP url or function that receives the url
1320
+ * and returns true if the url match the current definition.
1321
+ * @param {(string|RegExp|function(string))=} data HTTP request body or function that receives
1322
+ * data string and returns true if the data is as expected.
1323
+ * @param {(Object|function(Object))=} headers HTTP headers.
1324
+ * @returns {requestHandler} Returns an object with `respond` method that control how a matched
1325
+ * request is handled. You can save this object for later use and invoke `respond` again in
1326
+ * order to change how a matched request is handled.
1327
+ */
1328
+
1329
+ /**
1330
+ * @ngdoc method
1331
+ * @name $httpBackend#whenPUT
1332
+ * @description
1333
+ * Creates a new backend definition for PUT requests. For more info see `when()`.
1334
+ *
1335
+ * @param {string|RegExp|function(string)} url HTTP url or function that receives the url
1336
+ * and returns true if the url match the current definition.
1337
+ * @param {(string|RegExp|function(string))=} data HTTP request body or function that receives
1338
+ * data string and returns true if the data is as expected.
1339
+ * @param {(Object|function(Object))=} headers HTTP headers.
1340
+ * @returns {requestHandler} Returns an object with `respond` method that control how a matched
1341
+ * request is handled. You can save this object for later use and invoke `respond` again in
1342
+ * order to change how a matched request is handled.
1343
+ */
1344
+
1345
+ /**
1346
+ * @ngdoc method
1347
+ * @name $httpBackend#whenJSONP
1348
+ * @description
1349
+ * Creates a new backend definition for JSONP requests. For more info see `when()`.
1350
+ *
1351
+ * @param {string|RegExp|function(string)} url HTTP url or function that receives the url
1352
+ * and returns true if the url match the current definition.
1353
+ * @returns {requestHandler} Returns an object with `respond` method that control how a matched
1354
+ * request is handled. You can save this object for later use and invoke `respond` again in
1355
+ * order to change how a matched request is handled.
1356
+ */
1357
+ createShortMethods('when');
1358
+
1359
+
1360
+ /**
1361
+ * @ngdoc method
1362
+ * @name $httpBackend#expect
1363
+ * @description
1364
+ * Creates a new request expectation.
1365
+ *
1366
+ * @param {string} method HTTP method.
1367
+ * @param {string|RegExp|function(string)} url HTTP url or function that receives the url
1368
+ * and returns true if the url match the current definition.
1369
+ * @param {(string|RegExp|function(string)|Object)=} data HTTP request body or function that
1370
+ * receives data string and returns true if the data is as expected, or Object if request body
1371
+ * is in JSON format.
1372
+ * @param {(Object|function(Object))=} headers HTTP headers or function that receives http header
1373
+ * object and returns true if the headers match the current expectation.
1374
+ * @returns {requestHandler} Returns an object with `respond` method that control how a matched
1375
+ * request is handled. You can save this object for later use and invoke `respond` again in
1376
+ * order to change how a matched request is handled.
1377
+ *
1378
+ * - respond –
1379
+ * `{function([status,] data[, headers, statusText])
1380
+ * | function(function(method, url, data, headers)}`
1381
+ * – The respond method takes a set of static data to be returned or a function that can
1382
+ * return an array containing response status (number), response data (string), response
1383
+ * headers (Object), and the text for the status (string). The respond method returns the
1384
+ * `requestHandler` object for possible overrides.
1385
+ */
1386
+ $httpBackend.expect = function(method, url, data, headers) {
1387
+ var expectation = new MockHttpExpectation(method, url, data, headers),
1388
+ chain = {
1389
+ respond: function(status, data, headers, statusText) {
1390
+ expectation.response = createResponse(status, data, headers, statusText);
1391
+ return chain;
1392
+ }
1393
+ };
1394
+
1395
+ expectations.push(expectation);
1396
+ return chain;
1397
+ };
1398
+
1399
+
1400
+ /**
1401
+ * @ngdoc method
1402
+ * @name $httpBackend#expectGET
1403
+ * @description
1404
+ * Creates a new request expectation for GET requests. For more info see `expect()`.
1405
+ *
1406
+ * @param {string|RegExp|function(string)} url HTTP url or function that receives the url
1407
+ * and returns true if the url match the current definition.
1408
+ * @param {Object=} headers HTTP headers.
1409
+ * @returns {requestHandler} Returns an object with `respond` method that control how a matched
1410
+ * request is handled. You can save this object for later use and invoke `respond` again in
1411
+ * order to change how a matched request is handled. See #expect for more info.
1412
+ */
1413
+
1414
+ /**
1415
+ * @ngdoc method
1416
+ * @name $httpBackend#expectHEAD
1417
+ * @description
1418
+ * Creates a new request expectation for HEAD requests. For more info see `expect()`.
1419
+ *
1420
+ * @param {string|RegExp|function(string)} url HTTP url or function that receives the url
1421
+ * and returns true if the url match the current definition.
1422
+ * @param {Object=} headers HTTP headers.
1423
+ * @returns {requestHandler} Returns an object with `respond` method that control how a matched
1424
+ * request is handled. You can save this object for later use and invoke `respond` again in
1425
+ * order to change how a matched request is handled.
1426
+ */
1427
+
1428
+ /**
1429
+ * @ngdoc method
1430
+ * @name $httpBackend#expectDELETE
1431
+ * @description
1432
+ * Creates a new request expectation for DELETE requests. For more info see `expect()`.
1433
+ *
1434
+ * @param {string|RegExp|function(string)} url HTTP url or function that receives the url
1435
+ * and returns true if the url match the current definition.
1436
+ * @param {Object=} headers HTTP headers.
1437
+ * @returns {requestHandler} Returns an object with `respond` method that control how a matched
1438
+ * request is handled. You can save this object for later use and invoke `respond` again in
1439
+ * order to change how a matched request is handled.
1440
+ */
1441
+
1442
+ /**
1443
+ * @ngdoc method
1444
+ * @name $httpBackend#expectPOST
1445
+ * @description
1446
+ * Creates a new request expectation for POST requests. For more info see `expect()`.
1447
+ *
1448
+ * @param {string|RegExp|function(string)} url HTTP url or function that receives the url
1449
+ * and returns true if the url match the current definition.
1450
+ * @param {(string|RegExp|function(string)|Object)=} data HTTP request body or function that
1451
+ * receives data string and returns true if the data is as expected, or Object if request body
1452
+ * is in JSON format.
1453
+ * @param {Object=} headers HTTP headers.
1454
+ * @returns {requestHandler} Returns an object with `respond` method that control how a matched
1455
+ * request is handled. You can save this object for later use and invoke `respond` again in
1456
+ * order to change how a matched request is handled.
1457
+ */
1458
+
1459
+ /**
1460
+ * @ngdoc method
1461
+ * @name $httpBackend#expectPUT
1462
+ * @description
1463
+ * Creates a new request expectation for PUT requests. For more info see `expect()`.
1464
+ *
1465
+ * @param {string|RegExp|function(string)} url HTTP url or function that receives the url
1466
+ * and returns true if the url match the current definition.
1467
+ * @param {(string|RegExp|function(string)|Object)=} data HTTP request body or function that
1468
+ * receives data string and returns true if the data is as expected, or Object if request body
1469
+ * is in JSON format.
1470
+ * @param {Object=} headers HTTP headers.
1471
+ * @returns {requestHandler} Returns an object with `respond` method that control how a matched
1472
+ * request is handled. You can save this object for later use and invoke `respond` again in
1473
+ * order to change how a matched request is handled.
1474
+ */
1475
+
1476
+ /**
1477
+ * @ngdoc method
1478
+ * @name $httpBackend#expectPATCH
1479
+ * @description
1480
+ * Creates a new request expectation for PATCH requests. For more info see `expect()`.
1481
+ *
1482
+ * @param {string|RegExp|function(string)} url HTTP url or function that receives the url
1483
+ * and returns true if the url match the current definition.
1484
+ * @param {(string|RegExp|function(string)|Object)=} data HTTP request body or function that
1485
+ * receives data string and returns true if the data is as expected, or Object if request body
1486
+ * is in JSON format.
1487
+ * @param {Object=} headers HTTP headers.
1488
+ * @returns {requestHandler} Returns an object with `respond` method that control how a matched
1489
+ * request is handled. You can save this object for later use and invoke `respond` again in
1490
+ * order to change how a matched request is handled.
1491
+ */
1492
+
1493
+ /**
1494
+ * @ngdoc method
1495
+ * @name $httpBackend#expectJSONP
1496
+ * @description
1497
+ * Creates a new request expectation for JSONP requests. For more info see `expect()`.
1498
+ *
1499
+ * @param {string|RegExp|function(string)} url HTTP url or function that receives the url
1500
+ * and returns true if the url match the current definition.
1501
+ * @returns {requestHandler} Returns an object with `respond` method that control how a matched
1502
+ * request is handled. You can save this object for later use and invoke `respond` again in
1503
+ * order to change how a matched request is handled.
1504
+ */
1505
+ createShortMethods('expect');
1506
+
1507
+
1508
+ /**
1509
+ * @ngdoc method
1510
+ * @name $httpBackend#flush
1511
+ * @description
1512
+ * Flushes all pending requests using the trained responses.
1513
+ *
1514
+ * @param {number=} count Number of responses to flush (in the order they arrived). If undefined,
1515
+ * all pending requests will be flushed. If there are no pending requests when the flush method
1516
+ * is called an exception is thrown (as this typically a sign of programming error).
1517
+ */
1518
+ $httpBackend.flush = function(count, digest) {
1519
+ if (digest !== false) $rootScope.$digest();
1520
+ if (!responses.length) throw new Error('No pending request to flush !');
1521
+
1522
+ if (angular.isDefined(count) && count !== null) {
1523
+ while (count--) {
1524
+ if (!responses.length) throw new Error('No more pending request to flush !');
1525
+ responses.shift()();
1526
+ }
1527
+ } else {
1528
+ while (responses.length) {
1529
+ responses.shift()();
1530
+ }
1531
+ }
1532
+ $httpBackend.verifyNoOutstandingExpectation(digest);
1533
+ };
1534
+
1535
+
1536
+ /**
1537
+ * @ngdoc method
1538
+ * @name $httpBackend#verifyNoOutstandingExpectation
1539
+ * @description
1540
+ * Verifies that all of the requests defined via the `expect` api were made. If any of the
1541
+ * requests were not made, verifyNoOutstandingExpectation throws an exception.
1542
+ *
1543
+ * Typically, you would call this method following each test case that asserts requests using an
1544
+ * "afterEach" clause.
1545
+ *
1546
+ * ```js
1547
+ * afterEach($httpBackend.verifyNoOutstandingExpectation);
1548
+ * ```
1549
+ */
1550
+ $httpBackend.verifyNoOutstandingExpectation = function(digest) {
1551
+ if (digest !== false) $rootScope.$digest();
1552
+ if (expectations.length) {
1553
+ throw new Error('Unsatisfied requests: ' + expectations.join(', '));
1554
+ }
1555
+ };
1556
+
1557
+
1558
+ /**
1559
+ * @ngdoc method
1560
+ * @name $httpBackend#verifyNoOutstandingRequest
1561
+ * @description
1562
+ * Verifies that there are no outstanding requests that need to be flushed.
1563
+ *
1564
+ * Typically, you would call this method following each test case that asserts requests using an
1565
+ * "afterEach" clause.
1566
+ *
1567
+ * ```js
1568
+ * afterEach($httpBackend.verifyNoOutstandingRequest);
1569
+ * ```
1570
+ */
1571
+ $httpBackend.verifyNoOutstandingRequest = function() {
1572
+ if (responses.length) {
1573
+ throw new Error('Unflushed requests: ' + responses.length);
1574
+ }
1575
+ };
1576
+
1577
+
1578
+ /**
1579
+ * @ngdoc method
1580
+ * @name $httpBackend#resetExpectations
1581
+ * @description
1582
+ * Resets all request expectations, but preserves all backend definitions. Typically, you would
1583
+ * call resetExpectations during a multiple-phase test when you want to reuse the same instance of
1584
+ * $httpBackend mock.
1585
+ */
1586
+ $httpBackend.resetExpectations = function() {
1587
+ expectations.length = 0;
1588
+ responses.length = 0;
1589
+ };
1590
+
1591
+ return $httpBackend;
1592
+
1593
+
1594
+ function createShortMethods(prefix) {
1595
+ angular.forEach(['GET', 'DELETE', 'JSONP', 'HEAD'], function(method) {
1596
+ $httpBackend[prefix + method] = function(url, headers) {
1597
+ return $httpBackend[prefix](method, url, undefined, headers);
1598
+ };
1599
+ });
1600
+
1601
+ angular.forEach(['PUT', 'POST', 'PATCH'], function(method) {
1602
+ $httpBackend[prefix + method] = function(url, data, headers) {
1603
+ return $httpBackend[prefix](method, url, data, headers);
1604
+ };
1605
+ });
1606
+ }
1607
+ }
1608
+
1609
+ function MockHttpExpectation(method, url, data, headers) {
1610
+
1611
+ this.data = data;
1612
+ this.headers = headers;
1613
+
1614
+ this.match = function(m, u, d, h) {
1615
+ if (method != m) return false;
1616
+ if (!this.matchUrl(u)) return false;
1617
+ if (angular.isDefined(d) && !this.matchData(d)) return false;
1618
+ if (angular.isDefined(h) && !this.matchHeaders(h)) return false;
1619
+ return true;
1620
+ };
1621
+
1622
+ this.matchUrl = function(u) {
1623
+ if (!url) return true;
1624
+ if (angular.isFunction(url.test)) return url.test(u);
1625
+ if (angular.isFunction(url)) return url(u);
1626
+ return url == u;
1627
+ };
1628
+
1629
+ this.matchHeaders = function(h) {
1630
+ if (angular.isUndefined(headers)) return true;
1631
+ if (angular.isFunction(headers)) return headers(h);
1632
+ return angular.equals(headers, h);
1633
+ };
1634
+
1635
+ this.matchData = function(d) {
1636
+ if (angular.isUndefined(data)) return true;
1637
+ if (data && angular.isFunction(data.test)) return data.test(d);
1638
+ if (data && angular.isFunction(data)) return data(d);
1639
+ if (data && !angular.isString(data)) {
1640
+ return angular.equals(angular.fromJson(angular.toJson(data)), angular.fromJson(d));
1641
+ }
1642
+ return data == d;
1643
+ };
1644
+
1645
+ this.toString = function() {
1646
+ return method + ' ' + url;
1647
+ };
1648
+ }
1649
+
1650
+ function createMockXhr() {
1651
+ return new MockXhr();
1652
+ }
1653
+
1654
+ function MockXhr() {
1655
+
1656
+ // hack for testing $http, $httpBackend
1657
+ MockXhr.$$lastInstance = this;
1658
+
1659
+ this.open = function(method, url, async) {
1660
+ this.$$method = method;
1661
+ this.$$url = url;
1662
+ this.$$async = async;
1663
+ this.$$reqHeaders = {};
1664
+ this.$$respHeaders = {};
1665
+ };
1666
+
1667
+ this.send = function(data) {
1668
+ this.$$data = data;
1669
+ };
1670
+
1671
+ this.setRequestHeader = function(key, value) {
1672
+ this.$$reqHeaders[key] = value;
1673
+ };
1674
+
1675
+ this.getResponseHeader = function(name) {
1676
+ // the lookup must be case insensitive,
1677
+ // that's why we try two quick lookups first and full scan last
1678
+ var header = this.$$respHeaders[name];
1679
+ if (header) return header;
1680
+
1681
+ name = angular.lowercase(name);
1682
+ header = this.$$respHeaders[name];
1683
+ if (header) return header;
1684
+
1685
+ header = undefined;
1686
+ angular.forEach(this.$$respHeaders, function(headerVal, headerName) {
1687
+ if (!header && angular.lowercase(headerName) == name) header = headerVal;
1688
+ });
1689
+ return header;
1690
+ };
1691
+
1692
+ this.getAllResponseHeaders = function() {
1693
+ var lines = [];
1694
+
1695
+ angular.forEach(this.$$respHeaders, function(value, key) {
1696
+ lines.push(key + ': ' + value);
1697
+ });
1698
+ return lines.join('\n');
1699
+ };
1700
+
1701
+ this.abort = angular.noop;
1702
+ }
1703
+
1704
+
1705
+ /**
1706
+ * @ngdoc service
1707
+ * @name $timeout
1708
+ * @description
1709
+ *
1710
+ * This service is just a simple decorator for {@link ng.$timeout $timeout} service
1711
+ * that adds a "flush" and "verifyNoPendingTasks" methods.
1712
+ */
1713
+
1714
+ angular.mock.$TimeoutDecorator = ['$delegate', '$browser', function($delegate, $browser) {
1715
+
1716
+ /**
1717
+ * @ngdoc method
1718
+ * @name $timeout#flush
1719
+ * @description
1720
+ *
1721
+ * Flushes the queue of pending tasks.
1722
+ *
1723
+ * @param {number=} delay maximum timeout amount to flush up until
1724
+ */
1725
+ $delegate.flush = function(delay) {
1726
+ $browser.defer.flush(delay);
1727
+ };
1728
+
1729
+ /**
1730
+ * @ngdoc method
1731
+ * @name $timeout#verifyNoPendingTasks
1732
+ * @description
1733
+ *
1734
+ * Verifies that there are no pending tasks that need to be flushed.
1735
+ */
1736
+ $delegate.verifyNoPendingTasks = function() {
1737
+ if ($browser.deferredFns.length) {
1738
+ throw new Error('Deferred tasks to flush (' + $browser.deferredFns.length + '): ' +
1739
+ formatPendingTasksAsString($browser.deferredFns));
1740
+ }
1741
+ };
1742
+
1743
+ function formatPendingTasksAsString(tasks) {
1744
+ var result = [];
1745
+ angular.forEach(tasks, function(task) {
1746
+ result.push('{id: ' + task.id + ', ' + 'time: ' + task.time + '}');
1747
+ });
1748
+
1749
+ return result.join(', ');
1750
+ }
1751
+
1752
+ return $delegate;
1753
+ }];
1754
+
1755
+ angular.mock.$RAFDecorator = ['$delegate', function($delegate) {
1756
+ var queue = [];
1757
+ var rafFn = function(fn) {
1758
+ var index = queue.length;
1759
+ queue.push(fn);
1760
+ return function() {
1761
+ queue.splice(index, 1);
1762
+ };
1763
+ };
1764
+
1765
+ rafFn.supported = $delegate.supported;
1766
+
1767
+ rafFn.flush = function() {
1768
+ if (queue.length === 0) {
1769
+ throw new Error('No rAF callbacks present');
1770
+ }
1771
+
1772
+ var length = queue.length;
1773
+ for (var i=0;i<length;i++) {
1774
+ queue[i]();
1775
+ }
1776
+
1777
+ queue = [];
1778
+ };
1779
+
1780
+ return rafFn;
1781
+ }];
1782
+
1783
+ angular.mock.$AsyncCallbackDecorator = ['$delegate', function($delegate) {
1784
+ var callbacks = [];
1785
+ var addFn = function(fn) {
1786
+ callbacks.push(fn);
1787
+ };
1788
+ addFn.flush = function() {
1789
+ angular.forEach(callbacks, function(fn) {
1790
+ fn();
1791
+ });
1792
+ callbacks = [];
1793
+ };
1794
+ return addFn;
1795
+ }];
1796
+
1797
+ /**
1798
+ *
1799
+ */
1800
+ angular.mock.$RootElementProvider = function() {
1801
+ this.$get = function() {
1802
+ return angular.element('<div ng-app></div>');
1803
+ };
1804
+ };
1805
+
1806
+ /**
1807
+ * @ngdoc module
1808
+ * @name ngMock
1809
+ * @packageName angular-mocks
1810
+ * @description
1811
+ *
1812
+ * # ngMock
1813
+ *
1814
+ * The `ngMock` module provides support to inject and mock Angular services into unit tests.
1815
+ * In addition, ngMock also extends various core ng services such that they can be
1816
+ * inspected and controlled in a synchronous manner within test code.
1817
+ *
1818
+ *
1819
+ * <div doc-module-components="ngMock"></div>
1820
+ *
1821
+ */
1822
+ angular.module('ngMock', ['ng']).provider({
1823
+ $browser: angular.mock.$BrowserProvider,
1824
+ $exceptionHandler: angular.mock.$ExceptionHandlerProvider,
1825
+ $log: angular.mock.$LogProvider,
1826
+ $interval: angular.mock.$IntervalProvider,
1827
+ $httpBackend: angular.mock.$HttpBackendProvider,
1828
+ $rootElement: angular.mock.$RootElementProvider
1829
+ }).config(['$provide', function($provide) {
1830
+ $provide.decorator('$timeout', angular.mock.$TimeoutDecorator);
1831
+ $provide.decorator('$$rAF', angular.mock.$RAFDecorator);
1832
+ $provide.decorator('$$asyncCallback', angular.mock.$AsyncCallbackDecorator);
1833
+ $provide.decorator('$rootScope', angular.mock.$RootScopeDecorator);
1834
+ }]);
1835
+
1836
+ /**
1837
+ * @ngdoc module
1838
+ * @name ngMockE2E
1839
+ * @module ngMockE2E
1840
+ * @packageName angular-mocks
1841
+ * @description
1842
+ *
1843
+ * The `ngMockE2E` is an angular module which contains mocks suitable for end-to-end testing.
1844
+ * Currently there is only one mock present in this module -
1845
+ * the {@link ngMockE2E.$httpBackend e2e $httpBackend} mock.
1846
+ */
1847
+ angular.module('ngMockE2E', ['ng']).config(['$provide', function($provide) {
1848
+ $provide.decorator('$httpBackend', angular.mock.e2e.$httpBackendDecorator);
1849
+ }]);
1850
+
1851
+ /**
1852
+ * @ngdoc service
1853
+ * @name $httpBackend
1854
+ * @module ngMockE2E
1855
+ * @description
1856
+ * Fake HTTP backend implementation suitable for end-to-end testing or backend-less development of
1857
+ * applications that use the {@link ng.$http $http service}.
1858
+ *
1859
+ * *Note*: For fake http backend implementation suitable for unit testing please see
1860
+ * {@link ngMock.$httpBackend unit-testing $httpBackend mock}.
1861
+ *
1862
+ * This implementation can be used to respond with static or dynamic responses via the `when` api
1863
+ * and its shortcuts (`whenGET`, `whenPOST`, etc) and optionally pass through requests to the
1864
+ * real $httpBackend for specific requests (e.g. to interact with certain remote apis or to fetch
1865
+ * templates from a webserver).
1866
+ *
1867
+ * As opposed to unit-testing, in an end-to-end testing scenario or in scenario when an application
1868
+ * is being developed with the real backend api replaced with a mock, it is often desirable for
1869
+ * certain category of requests to bypass the mock and issue a real http request (e.g. to fetch
1870
+ * templates or static files from the webserver). To configure the backend with this behavior
1871
+ * use the `passThrough` request handler of `when` instead of `respond`.
1872
+ *
1873
+ * Additionally, we don't want to manually have to flush mocked out requests like we do during unit
1874
+ * testing. For this reason the e2e $httpBackend flushes mocked out requests
1875
+ * automatically, closely simulating the behavior of the XMLHttpRequest object.
1876
+ *
1877
+ * To setup the application to run with this http backend, you have to create a module that depends
1878
+ * on the `ngMockE2E` and your application modules and defines the fake backend:
1879
+ *
1880
+ * ```js
1881
+ * myAppDev = angular.module('myAppDev', ['myApp', 'ngMockE2E']);
1882
+ * myAppDev.run(function($httpBackend) {
1883
+ * phones = [{name: 'phone1'}, {name: 'phone2'}];
1884
+ *
1885
+ * // returns the current list of phones
1886
+ * $httpBackend.whenGET('/phones').respond(phones);
1887
+ *
1888
+ * // adds a new phone to the phones array
1889
+ * $httpBackend.whenPOST('/phones').respond(function(method, url, data) {
1890
+ * var phone = angular.fromJson(data);
1891
+ * phones.push(phone);
1892
+ * return [200, phone, {}];
1893
+ * });
1894
+ * $httpBackend.whenGET(/^\/templates\//).passThrough();
1895
+ * //...
1896
+ * });
1897
+ * ```
1898
+ *
1899
+ * Afterwards, bootstrap your app with this new module.
1900
+ */
1901
+
1902
+ /**
1903
+ * @ngdoc method
1904
+ * @name $httpBackend#when
1905
+ * @module ngMockE2E
1906
+ * @description
1907
+ * Creates a new backend definition.
1908
+ *
1909
+ * @param {string} method HTTP method.
1910
+ * @param {string|RegExp|function(string)} url HTTP url or function that receives the url
1911
+ * and returns true if the url match the current definition.
1912
+ * @param {(string|RegExp)=} data HTTP request body.
1913
+ * @param {(Object|function(Object))=} headers HTTP headers or function that receives http header
1914
+ * object and returns true if the headers match the current definition.
1915
+ * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
1916
+ * control how a matched request is handled. You can save this object for later use and invoke
1917
+ * `respond` or `passThrough` again in order to change how a matched request is handled.
1918
+ *
1919
+ * - respond –
1920
+ * `{function([status,] data[, headers, statusText])
1921
+ * | function(function(method, url, data, headers)}`
1922
+ * – The respond method takes a set of static data to be returned or a function that can return
1923
+ * an array containing response status (number), response data (string), response headers
1924
+ * (Object), and the text for the status (string).
1925
+ * - passThrough – `{function()}` – Any request matching a backend definition with
1926
+ * `passThrough` handler will be passed through to the real backend (an XHR request will be made
1927
+ * to the server.)
1928
+ * - Both methods return the `requestHandler` object for possible overrides.
1929
+ */
1930
+
1931
+ /**
1932
+ * @ngdoc method
1933
+ * @name $httpBackend#whenGET
1934
+ * @module ngMockE2E
1935
+ * @description
1936
+ * Creates a new backend definition for GET requests. For more info see `when()`.
1937
+ *
1938
+ * @param {string|RegExp|function(string)} url HTTP url or function that receives the url
1939
+ * and returns true if the url match the current definition.
1940
+ * @param {(Object|function(Object))=} headers HTTP headers.
1941
+ * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
1942
+ * control how a matched request is handled. You can save this object for later use and invoke
1943
+ * `respond` or `passThrough` again in order to change how a matched request is handled.
1944
+ */
1945
+
1946
+ /**
1947
+ * @ngdoc method
1948
+ * @name $httpBackend#whenHEAD
1949
+ * @module ngMockE2E
1950
+ * @description
1951
+ * Creates a new backend definition for HEAD requests. For more info see `when()`.
1952
+ *
1953
+ * @param {string|RegExp|function(string)} url HTTP url or function that receives the url
1954
+ * and returns true if the url match the current definition.
1955
+ * @param {(Object|function(Object))=} headers HTTP headers.
1956
+ * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
1957
+ * control how a matched request is handled. You can save this object for later use and invoke
1958
+ * `respond` or `passThrough` again in order to change how a matched request is handled.
1959
+ */
1960
+
1961
+ /**
1962
+ * @ngdoc method
1963
+ * @name $httpBackend#whenDELETE
1964
+ * @module ngMockE2E
1965
+ * @description
1966
+ * Creates a new backend definition for DELETE requests. For more info see `when()`.
1967
+ *
1968
+ * @param {string|RegExp|function(string)} url HTTP url or function that receives the url
1969
+ * and returns true if the url match the current definition.
1970
+ * @param {(Object|function(Object))=} headers HTTP headers.
1971
+ * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
1972
+ * control how a matched request is handled. You can save this object for later use and invoke
1973
+ * `respond` or `passThrough` again in order to change how a matched request is handled.
1974
+ */
1975
+
1976
+ /**
1977
+ * @ngdoc method
1978
+ * @name $httpBackend#whenPOST
1979
+ * @module ngMockE2E
1980
+ * @description
1981
+ * Creates a new backend definition for POST requests. For more info see `when()`.
1982
+ *
1983
+ * @param {string|RegExp|function(string)} url HTTP url or function that receives the url
1984
+ * and returns true if the url match the current definition.
1985
+ * @param {(string|RegExp)=} data HTTP request body.
1986
+ * @param {(Object|function(Object))=} headers HTTP headers.
1987
+ * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
1988
+ * control how a matched request is handled. You can save this object for later use and invoke
1989
+ * `respond` or `passThrough` again in order to change how a matched request is handled.
1990
+ */
1991
+
1992
+ /**
1993
+ * @ngdoc method
1994
+ * @name $httpBackend#whenPUT
1995
+ * @module ngMockE2E
1996
+ * @description
1997
+ * Creates a new backend definition for PUT requests. For more info see `when()`.
1998
+ *
1999
+ * @param {string|RegExp|function(string)} url HTTP url or function that receives the url
2000
+ * and returns true if the url match the current definition.
2001
+ * @param {(string|RegExp)=} data HTTP request body.
2002
+ * @param {(Object|function(Object))=} headers HTTP headers.
2003
+ * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
2004
+ * control how a matched request is handled. You can save this object for later use and invoke
2005
+ * `respond` or `passThrough` again in order to change how a matched request is handled.
2006
+ */
2007
+
2008
+ /**
2009
+ * @ngdoc method
2010
+ * @name $httpBackend#whenPATCH
2011
+ * @module ngMockE2E
2012
+ * @description
2013
+ * Creates a new backend definition for PATCH requests. For more info see `when()`.
2014
+ *
2015
+ * @param {string|RegExp|function(string)} url HTTP url or function that receives the url
2016
+ * and returns true if the url match the current definition.
2017
+ * @param {(string|RegExp)=} data HTTP request body.
2018
+ * @param {(Object|function(Object))=} headers HTTP headers.
2019
+ * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
2020
+ * control how a matched request is handled. You can save this object for later use and invoke
2021
+ * `respond` or `passThrough` again in order to change how a matched request is handled.
2022
+ */
2023
+
2024
+ /**
2025
+ * @ngdoc method
2026
+ * @name $httpBackend#whenJSONP
2027
+ * @module ngMockE2E
2028
+ * @description
2029
+ * Creates a new backend definition for JSONP requests. For more info see `when()`.
2030
+ *
2031
+ * @param {string|RegExp|function(string)} url HTTP url or function that receives the url
2032
+ * and returns true if the url match the current definition.
2033
+ * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
2034
+ * control how a matched request is handled. You can save this object for later use and invoke
2035
+ * `respond` or `passThrough` again in order to change how a matched request is handled.
2036
+ */
2037
+ angular.mock.e2e = {};
2038
+ angular.mock.e2e.$httpBackendDecorator =
2039
+ ['$rootScope', '$delegate', '$browser', createHttpBackendMock];
2040
+
2041
+
2042
+ /**
2043
+ * @ngdoc type
2044
+ * @name $rootScope.Scope
2045
+ * @module ngMock
2046
+ * @description
2047
+ * {@link ng.$rootScope.Scope Scope} type decorated with helper methods useful for testing. These
2048
+ * methods are automatically available on any {@link ng.$rootScope.Scope Scope} instance when
2049
+ * `ngMock` module is loaded.
2050
+ *
2051
+ * In addition to all the regular `Scope` methods, the following helper methods are available:
2052
+ */
2053
+ angular.mock.$RootScopeDecorator = function($delegate) {
2054
+
2055
+ var $rootScopePrototype = Object.getPrototypeOf($delegate);
2056
+
2057
+ $rootScopePrototype.$countChildScopes = countChildScopes;
2058
+ $rootScopePrototype.$countWatchers = countWatchers;
2059
+
2060
+ return $delegate;
2061
+
2062
+ // ------------------------------------------------------------------------------------------ //
2063
+
2064
+ /**
2065
+ * @ngdoc method
2066
+ * @name $rootScope.Scope#$countChildScopes
2067
+ * @module ngMock
2068
+ * @description
2069
+ * Counts all the direct and indirect child scopes of the current scope.
2070
+ *
2071
+ * The current scope is excluded from the count. The count includes all isolate child scopes.
2072
+ *
2073
+ * @returns {number} Total number of child scopes.
2074
+ */
2075
+ function countChildScopes() {
2076
+ // jshint validthis: true
2077
+ var count = 0; // exclude the current scope
2078
+ var pendingChildHeads = [this.$$childHead];
2079
+ var currentScope;
2080
+
2081
+ while (pendingChildHeads.length) {
2082
+ currentScope = pendingChildHeads.shift();
2083
+
2084
+ while (currentScope) {
2085
+ count += 1;
2086
+ pendingChildHeads.push(currentScope.$$childHead);
2087
+ currentScope = currentScope.$$nextSibling;
2088
+ }
2089
+ }
2090
+
2091
+ return count;
2092
+ }
2093
+
2094
+
2095
+ /**
2096
+ * @ngdoc method
2097
+ * @name $rootScope.Scope#$countWatchers
2098
+ * @module ngMock
2099
+ * @description
2100
+ * Counts all the watchers of direct and indirect child scopes of the current scope.
2101
+ *
2102
+ * The watchers of the current scope are included in the count and so are all the watchers of
2103
+ * isolate child scopes.
2104
+ *
2105
+ * @returns {number} Total number of watchers.
2106
+ */
2107
+ function countWatchers() {
2108
+ // jshint validthis: true
2109
+ var count = this.$$watchers ? this.$$watchers.length : 0; // include the current scope
2110
+ var pendingChildHeads = [this.$$childHead];
2111
+ var currentScope;
2112
+
2113
+ while (pendingChildHeads.length) {
2114
+ currentScope = pendingChildHeads.shift();
2115
+
2116
+ while (currentScope) {
2117
+ count += currentScope.$$watchers ? currentScope.$$watchers.length : 0;
2118
+ pendingChildHeads.push(currentScope.$$childHead);
2119
+ currentScope = currentScope.$$nextSibling;
2120
+ }
2121
+ }
2122
+
2123
+ return count;
2124
+ }
2125
+ };
2126
+
2127
+
2128
+ if (window.jasmine || window.mocha) {
2129
+
2130
+ var currentSpec = null,
2131
+ isSpecRunning = function() {
2132
+ return !!currentSpec;
2133
+ };
2134
+
2135
+
2136
+ (window.beforeEach || window.setup)(function() {
2137
+ currentSpec = this;
2138
+ });
2139
+
2140
+ (window.afterEach || window.teardown)(function() {
2141
+ var injector = currentSpec.$injector;
2142
+
2143
+ angular.forEach(currentSpec.$modules, function(module) {
2144
+ if (module && module.$$hashKey) {
2145
+ module.$$hashKey = undefined;
2146
+ }
2147
+ });
2148
+
2149
+ currentSpec.$injector = null;
2150
+ currentSpec.$modules = null;
2151
+ currentSpec = null;
2152
+
2153
+ if (injector) {
2154
+ injector.get('$rootElement').off();
2155
+ injector.get('$browser').pollFns.length = 0;
2156
+ }
2157
+
2158
+ // clean up jquery's fragment cache
2159
+ angular.forEach(angular.element.fragments, function(val, key) {
2160
+ delete angular.element.fragments[key];
2161
+ });
2162
+
2163
+ MockXhr.$$lastInstance = null;
2164
+
2165
+ angular.forEach(angular.callbacks, function(val, key) {
2166
+ delete angular.callbacks[key];
2167
+ });
2168
+ angular.callbacks.counter = 0;
2169
+ });
2170
+
2171
+ /**
2172
+ * @ngdoc function
2173
+ * @name angular.mock.module
2174
+ * @description
2175
+ *
2176
+ * *NOTE*: This function is also published on window for easy access.<br>
2177
+ * *NOTE*: This function is declared ONLY WHEN running tests with jasmine or mocha
2178
+ *
2179
+ * This function registers a module configuration code. It collects the configuration information
2180
+ * which will be used when the injector is created by {@link angular.mock.inject inject}.
2181
+ *
2182
+ * See {@link angular.mock.inject inject} for usage example
2183
+ *
2184
+ * @param {...(string|Function|Object)} fns any number of modules which are represented as string
2185
+ * aliases or as anonymous module initialization functions. The modules are used to
2186
+ * configure the injector. The 'ng' and 'ngMock' modules are automatically loaded. If an
2187
+ * object literal is passed they will be registered as values in the module, the key being
2188
+ * the module name and the value being what is returned.
2189
+ */
2190
+ window.module = angular.mock.module = function() {
2191
+ var moduleFns = Array.prototype.slice.call(arguments, 0);
2192
+ return isSpecRunning() ? workFn() : workFn;
2193
+ /////////////////////
2194
+ function workFn() {
2195
+ if (currentSpec.$injector) {
2196
+ throw new Error('Injector already created, can not register a module!');
2197
+ } else {
2198
+ var modules = currentSpec.$modules || (currentSpec.$modules = []);
2199
+ angular.forEach(moduleFns, function(module) {
2200
+ if (angular.isObject(module) && !angular.isArray(module)) {
2201
+ modules.push(function($provide) {
2202
+ angular.forEach(module, function(value, key) {
2203
+ $provide.value(key, value);
2204
+ });
2205
+ });
2206
+ } else {
2207
+ modules.push(module);
2208
+ }
2209
+ });
2210
+ }
2211
+ }
2212
+ };
2213
+
2214
+ /**
2215
+ * @ngdoc function
2216
+ * @name angular.mock.inject
2217
+ * @description
2218
+ *
2219
+ * *NOTE*: This function is also published on window for easy access.<br>
2220
+ * *NOTE*: This function is declared ONLY WHEN running tests with jasmine or mocha
2221
+ *
2222
+ * The inject function wraps a function into an injectable function. The inject() creates new
2223
+ * instance of {@link auto.$injector $injector} per test, which is then used for
2224
+ * resolving references.
2225
+ *
2226
+ *
2227
+ * ## Resolving References (Underscore Wrapping)
2228
+ * Often, we would like to inject a reference once, in a `beforeEach()` block and reuse this
2229
+ * in multiple `it()` clauses. To be able to do this we must assign the reference to a variable
2230
+ * that is declared in the scope of the `describe()` block. Since we would, most likely, want
2231
+ * the variable to have the same name of the reference we have a problem, since the parameter
2232
+ * to the `inject()` function would hide the outer variable.
2233
+ *
2234
+ * To help with this, the injected parameters can, optionally, be enclosed with underscores.
2235
+ * These are ignored by the injector when the reference name is resolved.
2236
+ *
2237
+ * For example, the parameter `_myService_` would be resolved as the reference `myService`.
2238
+ * Since it is available in the function body as _myService_, we can then assign it to a variable
2239
+ * defined in an outer scope.
2240
+ *
2241
+ * ```
2242
+ * // Defined out reference variable outside
2243
+ * var myService;
2244
+ *
2245
+ * // Wrap the parameter in underscores
2246
+ * beforeEach( inject( function(_myService_){
2247
+ * myService = _myService_;
2248
+ * }));
2249
+ *
2250
+ * // Use myService in a series of tests.
2251
+ * it('makes use of myService', function() {
2252
+ * myService.doStuff();
2253
+ * });
2254
+ *
2255
+ * ```
2256
+ *
2257
+ * See also {@link angular.mock.module angular.mock.module}
2258
+ *
2259
+ * ## Example
2260
+ * Example of what a typical jasmine tests looks like with the inject method.
2261
+ * ```js
2262
+ *
2263
+ * angular.module('myApplicationModule', [])
2264
+ * .value('mode', 'app')
2265
+ * .value('version', 'v1.0.1');
2266
+ *
2267
+ *
2268
+ * describe('MyApp', function() {
2269
+ *
2270
+ * // You need to load modules that you want to test,
2271
+ * // it loads only the "ng" module by default.
2272
+ * beforeEach(module('myApplicationModule'));
2273
+ *
2274
+ *
2275
+ * // inject() is used to inject arguments of all given functions
2276
+ * it('should provide a version', inject(function(mode, version) {
2277
+ * expect(version).toEqual('v1.0.1');
2278
+ * expect(mode).toEqual('app');
2279
+ * }));
2280
+ *
2281
+ *
2282
+ * // The inject and module method can also be used inside of the it or beforeEach
2283
+ * it('should override a version and test the new version is injected', function() {
2284
+ * // module() takes functions or strings (module aliases)
2285
+ * module(function($provide) {
2286
+ * $provide.value('version', 'overridden'); // override version here
2287
+ * });
2288
+ *
2289
+ * inject(function(version) {
2290
+ * expect(version).toEqual('overridden');
2291
+ * });
2292
+ * });
2293
+ * });
2294
+ *
2295
+ * ```
2296
+ *
2297
+ * @param {...Function} fns any number of functions which will be injected using the injector.
2298
+ */
2299
+
2300
+
2301
+
2302
+ var ErrorAddingDeclarationLocationStack = function(e, errorForStack) {
2303
+ this.message = e.message;
2304
+ this.name = e.name;
2305
+ if (e.line) this.line = e.line;
2306
+ if (e.sourceId) this.sourceId = e.sourceId;
2307
+ if (e.stack && errorForStack)
2308
+ this.stack = e.stack + '\n' + errorForStack.stack;
2309
+ if (e.stackArray) this.stackArray = e.stackArray;
2310
+ };
2311
+ ErrorAddingDeclarationLocationStack.prototype.toString = Error.prototype.toString;
2312
+
2313
+ window.inject = angular.mock.inject = function() {
2314
+ var blockFns = Array.prototype.slice.call(arguments, 0);
2315
+ var errorForStack = new Error('Declaration Location');
2316
+ return isSpecRunning() ? workFn.call(currentSpec) : workFn;
2317
+ /////////////////////
2318
+ function workFn() {
2319
+ var modules = currentSpec.$modules || [];
2320
+ var strictDi = !!currentSpec.$injectorStrict;
2321
+ modules.unshift('ngMock');
2322
+ modules.unshift('ng');
2323
+ var injector = currentSpec.$injector;
2324
+ if (!injector) {
2325
+ if (strictDi) {
2326
+ // If strictDi is enabled, annotate the providerInjector blocks
2327
+ angular.forEach(modules, function(moduleFn) {
2328
+ if (typeof moduleFn === "function") {
2329
+ angular.injector.$$annotate(moduleFn);
2330
+ }
2331
+ });
2332
+ }
2333
+ injector = currentSpec.$injector = angular.injector(modules, strictDi);
2334
+ currentSpec.$injectorStrict = strictDi;
2335
+ }
2336
+ for (var i = 0, ii = blockFns.length; i < ii; i++) {
2337
+ if (currentSpec.$injectorStrict) {
2338
+ // If the injector is strict / strictDi, and the spec wants to inject using automatic
2339
+ // annotation, then annotate the function here.
2340
+ injector.annotate(blockFns[i]);
2341
+ }
2342
+ try {
2343
+ /* jshint -W040 *//* Jasmine explicitly provides a `this` object when calling functions */
2344
+ injector.invoke(blockFns[i] || angular.noop, this);
2345
+ /* jshint +W040 */
2346
+ } catch (e) {
2347
+ if (e.stack && errorForStack) {
2348
+ throw new ErrorAddingDeclarationLocationStack(e, errorForStack);
2349
+ }
2350
+ throw e;
2351
+ } finally {
2352
+ errorForStack = null;
2353
+ }
2354
+ }
2355
+ }
2356
+ };
2357
+
2358
+
2359
+ angular.mock.inject.strictDi = function(value) {
2360
+ value = arguments.length ? !!value : true;
2361
+ return isSpecRunning() ? workFn() : workFn;
2362
+
2363
+ function workFn() {
2364
+ if (value !== currentSpec.$injectorStrict) {
2365
+ if (currentSpec.$injector) {
2366
+ throw new Error('Injector already created, can not modify strict annotations');
2367
+ } else {
2368
+ currentSpec.$injectorStrict = value;
2369
+ }
2370
+ }
2371
+ }
2372
+ };
2373
+ }
2374
+
2375
+
2376
+ })(window, window.angular);