angular-gem 1.2.26 → 1.3.0

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.0/angular-animate.js +2112 -0
  4. data/vendor/assets/javascripts/1.3.0/angular-aria.js +250 -0
  5. data/vendor/assets/javascripts/1.3.0/angular-cookies.js +206 -0
  6. data/vendor/assets/javascripts/1.3.0/angular-loader.js +422 -0
  7. data/vendor/assets/javascripts/1.3.0/angular-messages.js +400 -0
  8. data/vendor/assets/javascripts/1.3.0/angular-mocks.js +2287 -0
  9. data/vendor/assets/javascripts/1.3.0/angular-resource.js +667 -0
  10. data/vendor/assets/javascripts/1.3.0/angular-route.js +978 -0
  11. data/vendor/assets/javascripts/1.3.0/angular-sanitize.js +647 -0
  12. data/vendor/assets/javascripts/1.3.0/angular-scenario.js +36944 -0
  13. data/vendor/assets/javascripts/1.3.0/angular-touch.js +622 -0
  14. data/vendor/assets/javascripts/1.3.0/angular.js +25584 -0
  15. data/vendor/assets/javascripts/angular-animate.js +879 -456
  16. data/vendor/assets/javascripts/angular-aria.js +250 -0
  17. data/vendor/assets/javascripts/angular-cookies.js +1 -1
  18. data/vendor/assets/javascripts/angular-loader.js +17 -10
  19. data/vendor/assets/javascripts/angular-messages.js +400 -0
  20. data/vendor/assets/javascripts/angular-mocks.js +220 -110
  21. data/vendor/assets/javascripts/angular-resource.js +287 -247
  22. data/vendor/assets/javascripts/angular-route.js +111 -54
  23. data/vendor/assets/javascripts/angular-sanitize.js +1 -1
  24. data/vendor/assets/javascripts/angular-scenario.js +11579 -8665
  25. data/vendor/assets/javascripts/angular-touch.js +49 -11
  26. data/vendor/assets/javascripts/angular.js +6660 -3106
  27. metadata +15 -1
@@ -0,0 +1,2287 @@
1
+ /**
2
+ * @license AngularJS v1.3.0
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)) return angular.equals(data, angular.fromJson(d));
1640
+ return data == d;
1641
+ };
1642
+
1643
+ this.toString = function() {
1644
+ return method + ' ' + url;
1645
+ };
1646
+ }
1647
+
1648
+ function createMockXhr() {
1649
+ return new MockXhr();
1650
+ }
1651
+
1652
+ function MockXhr() {
1653
+
1654
+ // hack for testing $http, $httpBackend
1655
+ MockXhr.$$lastInstance = this;
1656
+
1657
+ this.open = function(method, url, async) {
1658
+ this.$$method = method;
1659
+ this.$$url = url;
1660
+ this.$$async = async;
1661
+ this.$$reqHeaders = {};
1662
+ this.$$respHeaders = {};
1663
+ };
1664
+
1665
+ this.send = function(data) {
1666
+ this.$$data = data;
1667
+ };
1668
+
1669
+ this.setRequestHeader = function(key, value) {
1670
+ this.$$reqHeaders[key] = value;
1671
+ };
1672
+
1673
+ this.getResponseHeader = function(name) {
1674
+ // the lookup must be case insensitive,
1675
+ // that's why we try two quick lookups first and full scan last
1676
+ var header = this.$$respHeaders[name];
1677
+ if (header) return header;
1678
+
1679
+ name = angular.lowercase(name);
1680
+ header = this.$$respHeaders[name];
1681
+ if (header) return header;
1682
+
1683
+ header = undefined;
1684
+ angular.forEach(this.$$respHeaders, function(headerVal, headerName) {
1685
+ if (!header && angular.lowercase(headerName) == name) header = headerVal;
1686
+ });
1687
+ return header;
1688
+ };
1689
+
1690
+ this.getAllResponseHeaders = function() {
1691
+ var lines = [];
1692
+
1693
+ angular.forEach(this.$$respHeaders, function(value, key) {
1694
+ lines.push(key + ': ' + value);
1695
+ });
1696
+ return lines.join('\n');
1697
+ };
1698
+
1699
+ this.abort = angular.noop;
1700
+ }
1701
+
1702
+
1703
+ /**
1704
+ * @ngdoc service
1705
+ * @name $timeout
1706
+ * @description
1707
+ *
1708
+ * This service is just a simple decorator for {@link ng.$timeout $timeout} service
1709
+ * that adds a "flush" and "verifyNoPendingTasks" methods.
1710
+ */
1711
+
1712
+ angular.mock.$TimeoutDecorator = ['$delegate', '$browser', function ($delegate, $browser) {
1713
+
1714
+ /**
1715
+ * @ngdoc method
1716
+ * @name $timeout#flush
1717
+ * @description
1718
+ *
1719
+ * Flushes the queue of pending tasks.
1720
+ *
1721
+ * @param {number=} delay maximum timeout amount to flush up until
1722
+ */
1723
+ $delegate.flush = function(delay) {
1724
+ $browser.defer.flush(delay);
1725
+ };
1726
+
1727
+ /**
1728
+ * @ngdoc method
1729
+ * @name $timeout#verifyNoPendingTasks
1730
+ * @description
1731
+ *
1732
+ * Verifies that there are no pending tasks that need to be flushed.
1733
+ */
1734
+ $delegate.verifyNoPendingTasks = function() {
1735
+ if ($browser.deferredFns.length) {
1736
+ throw new Error('Deferred tasks to flush (' + $browser.deferredFns.length + '): ' +
1737
+ formatPendingTasksAsString($browser.deferredFns));
1738
+ }
1739
+ };
1740
+
1741
+ function formatPendingTasksAsString(tasks) {
1742
+ var result = [];
1743
+ angular.forEach(tasks, function(task) {
1744
+ result.push('{id: ' + task.id + ', ' + 'time: ' + task.time + '}');
1745
+ });
1746
+
1747
+ return result.join(', ');
1748
+ }
1749
+
1750
+ return $delegate;
1751
+ }];
1752
+
1753
+ angular.mock.$RAFDecorator = ['$delegate', function($delegate) {
1754
+ var queue = [];
1755
+ var rafFn = function(fn) {
1756
+ var index = queue.length;
1757
+ queue.push(fn);
1758
+ return function() {
1759
+ queue.splice(index, 1);
1760
+ };
1761
+ };
1762
+
1763
+ rafFn.supported = $delegate.supported;
1764
+
1765
+ rafFn.flush = function() {
1766
+ if(queue.length === 0) {
1767
+ throw new Error('No rAF callbacks present');
1768
+ }
1769
+
1770
+ var length = queue.length;
1771
+ for(var i=0;i<length;i++) {
1772
+ queue[i]();
1773
+ }
1774
+
1775
+ queue = [];
1776
+ };
1777
+
1778
+ return rafFn;
1779
+ }];
1780
+
1781
+ angular.mock.$AsyncCallbackDecorator = ['$delegate', function($delegate) {
1782
+ var callbacks = [];
1783
+ var addFn = function(fn) {
1784
+ callbacks.push(fn);
1785
+ };
1786
+ addFn.flush = function() {
1787
+ angular.forEach(callbacks, function(fn) {
1788
+ fn();
1789
+ });
1790
+ callbacks = [];
1791
+ };
1792
+ return addFn;
1793
+ }];
1794
+
1795
+ /**
1796
+ *
1797
+ */
1798
+ angular.mock.$RootElementProvider = function() {
1799
+ this.$get = function() {
1800
+ return angular.element('<div ng-app></div>');
1801
+ };
1802
+ };
1803
+
1804
+ /**
1805
+ * @ngdoc module
1806
+ * @name ngMock
1807
+ * @packageName angular-mocks
1808
+ * @description
1809
+ *
1810
+ * # ngMock
1811
+ *
1812
+ * The `ngMock` module provides support to inject and mock Angular services into unit tests.
1813
+ * In addition, ngMock also extends various core ng services such that they can be
1814
+ * inspected and controlled in a synchronous manner within test code.
1815
+ *
1816
+ *
1817
+ * <div doc-module-components="ngMock"></div>
1818
+ *
1819
+ */
1820
+ angular.module('ngMock', ['ng']).provider({
1821
+ $browser: angular.mock.$BrowserProvider,
1822
+ $exceptionHandler: angular.mock.$ExceptionHandlerProvider,
1823
+ $log: angular.mock.$LogProvider,
1824
+ $interval: angular.mock.$IntervalProvider,
1825
+ $httpBackend: angular.mock.$HttpBackendProvider,
1826
+ $rootElement: angular.mock.$RootElementProvider
1827
+ }).config(['$provide', function($provide) {
1828
+ $provide.decorator('$timeout', angular.mock.$TimeoutDecorator);
1829
+ $provide.decorator('$$rAF', angular.mock.$RAFDecorator);
1830
+ $provide.decorator('$$asyncCallback', angular.mock.$AsyncCallbackDecorator);
1831
+ }]);
1832
+
1833
+ /**
1834
+ * @ngdoc module
1835
+ * @name ngMockE2E
1836
+ * @module ngMockE2E
1837
+ * @packageName angular-mocks
1838
+ * @description
1839
+ *
1840
+ * The `ngMockE2E` is an angular module which contains mocks suitable for end-to-end testing.
1841
+ * Currently there is only one mock present in this module -
1842
+ * the {@link ngMockE2E.$httpBackend e2e $httpBackend} mock.
1843
+ */
1844
+ angular.module('ngMockE2E', ['ng']).config(['$provide', function($provide) {
1845
+ $provide.decorator('$httpBackend', angular.mock.e2e.$httpBackendDecorator);
1846
+ }]);
1847
+
1848
+ /**
1849
+ * @ngdoc service
1850
+ * @name $httpBackend
1851
+ * @module ngMockE2E
1852
+ * @description
1853
+ * Fake HTTP backend implementation suitable for end-to-end testing or backend-less development of
1854
+ * applications that use the {@link ng.$http $http service}.
1855
+ *
1856
+ * *Note*: For fake http backend implementation suitable for unit testing please see
1857
+ * {@link ngMock.$httpBackend unit-testing $httpBackend mock}.
1858
+ *
1859
+ * This implementation can be used to respond with static or dynamic responses via the `when` api
1860
+ * and its shortcuts (`whenGET`, `whenPOST`, etc) and optionally pass through requests to the
1861
+ * real $httpBackend for specific requests (e.g. to interact with certain remote apis or to fetch
1862
+ * templates from a webserver).
1863
+ *
1864
+ * As opposed to unit-testing, in an end-to-end testing scenario or in scenario when an application
1865
+ * is being developed with the real backend api replaced with a mock, it is often desirable for
1866
+ * certain category of requests to bypass the mock and issue a real http request (e.g. to fetch
1867
+ * templates or static files from the webserver). To configure the backend with this behavior
1868
+ * use the `passThrough` request handler of `when` instead of `respond`.
1869
+ *
1870
+ * Additionally, we don't want to manually have to flush mocked out requests like we do during unit
1871
+ * testing. For this reason the e2e $httpBackend flushes mocked out requests
1872
+ * automatically, closely simulating the behavior of the XMLHttpRequest object.
1873
+ *
1874
+ * To setup the application to run with this http backend, you have to create a module that depends
1875
+ * on the `ngMockE2E` and your application modules and defines the fake backend:
1876
+ *
1877
+ * ```js
1878
+ * myAppDev = angular.module('myAppDev', ['myApp', 'ngMockE2E']);
1879
+ * myAppDev.run(function($httpBackend) {
1880
+ * phones = [{name: 'phone1'}, {name: 'phone2'}];
1881
+ *
1882
+ * // returns the current list of phones
1883
+ * $httpBackend.whenGET('/phones').respond(phones);
1884
+ *
1885
+ * // adds a new phone to the phones array
1886
+ * $httpBackend.whenPOST('/phones').respond(function(method, url, data) {
1887
+ * var phone = angular.fromJson(data);
1888
+ * phones.push(phone);
1889
+ * return [200, phone, {}];
1890
+ * });
1891
+ * $httpBackend.whenGET(/^\/templates\//).passThrough();
1892
+ * //...
1893
+ * });
1894
+ * ```
1895
+ *
1896
+ * Afterwards, bootstrap your app with this new module.
1897
+ */
1898
+
1899
+ /**
1900
+ * @ngdoc method
1901
+ * @name $httpBackend#when
1902
+ * @module ngMockE2E
1903
+ * @description
1904
+ * Creates a new backend definition.
1905
+ *
1906
+ * @param {string} method HTTP method.
1907
+ * @param {string|RegExp|function(string)} url HTTP url or function that receives the url
1908
+ * and returns true if the url match the current definition.
1909
+ * @param {(string|RegExp)=} data HTTP request body.
1910
+ * @param {(Object|function(Object))=} headers HTTP headers or function that receives http header
1911
+ * object and returns true if the headers match the current definition.
1912
+ * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
1913
+ * control how a matched request is handled. You can save this object for later use and invoke
1914
+ * `respond` or `passThrough` again in order to change how a matched request is handled.
1915
+ *
1916
+ * - respond –
1917
+ * `{function([status,] data[, headers, statusText])
1918
+ * | function(function(method, url, data, headers)}`
1919
+ * – The respond method takes a set of static data to be returned or a function that can return
1920
+ * an array containing response status (number), response data (string), response headers
1921
+ * (Object), and the text for the status (string).
1922
+ * - passThrough – `{function()}` – Any request matching a backend definition with
1923
+ * `passThrough` handler will be passed through to the real backend (an XHR request will be made
1924
+ * to the server.)
1925
+ * - Both methods return the `requestHandler` object for possible overrides.
1926
+ */
1927
+
1928
+ /**
1929
+ * @ngdoc method
1930
+ * @name $httpBackend#whenGET
1931
+ * @module ngMockE2E
1932
+ * @description
1933
+ * Creates a new backend definition for GET requests. For more info see `when()`.
1934
+ *
1935
+ * @param {string|RegExp|function(string)} url HTTP url or function that receives the url
1936
+ * and returns true if the url match the current definition.
1937
+ * @param {(Object|function(Object))=} headers HTTP headers.
1938
+ * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
1939
+ * control how a matched request is handled. You can save this object for later use and invoke
1940
+ * `respond` or `passThrough` again in order to change how a matched request is handled.
1941
+ */
1942
+
1943
+ /**
1944
+ * @ngdoc method
1945
+ * @name $httpBackend#whenHEAD
1946
+ * @module ngMockE2E
1947
+ * @description
1948
+ * Creates a new backend definition for HEAD requests. For more info see `when()`.
1949
+ *
1950
+ * @param {string|RegExp|function(string)} url HTTP url or function that receives the url
1951
+ * and returns true if the url match the current definition.
1952
+ * @param {(Object|function(Object))=} headers HTTP headers.
1953
+ * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
1954
+ * control how a matched request is handled. You can save this object for later use and invoke
1955
+ * `respond` or `passThrough` again in order to change how a matched request is handled.
1956
+ */
1957
+
1958
+ /**
1959
+ * @ngdoc method
1960
+ * @name $httpBackend#whenDELETE
1961
+ * @module ngMockE2E
1962
+ * @description
1963
+ * Creates a new backend definition for DELETE requests. For more info see `when()`.
1964
+ *
1965
+ * @param {string|RegExp|function(string)} url HTTP url or function that receives the url
1966
+ * and returns true if the url match the current definition.
1967
+ * @param {(Object|function(Object))=} headers HTTP headers.
1968
+ * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
1969
+ * control how a matched request is handled. You can save this object for later use and invoke
1970
+ * `respond` or `passThrough` again in order to change how a matched request is handled.
1971
+ */
1972
+
1973
+ /**
1974
+ * @ngdoc method
1975
+ * @name $httpBackend#whenPOST
1976
+ * @module ngMockE2E
1977
+ * @description
1978
+ * Creates a new backend definition for POST requests. For more info see `when()`.
1979
+ *
1980
+ * @param {string|RegExp|function(string)} url HTTP url or function that receives the url
1981
+ * and returns true if the url match the current definition.
1982
+ * @param {(string|RegExp)=} data HTTP request body.
1983
+ * @param {(Object|function(Object))=} headers HTTP headers.
1984
+ * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
1985
+ * control how a matched request is handled. You can save this object for later use and invoke
1986
+ * `respond` or `passThrough` again in order to change how a matched request is handled.
1987
+ */
1988
+
1989
+ /**
1990
+ * @ngdoc method
1991
+ * @name $httpBackend#whenPUT
1992
+ * @module ngMockE2E
1993
+ * @description
1994
+ * Creates a new backend definition for PUT requests. For more info see `when()`.
1995
+ *
1996
+ * @param {string|RegExp|function(string)} url HTTP url or function that receives the url
1997
+ * and returns true if the url match the current definition.
1998
+ * @param {(string|RegExp)=} data HTTP request body.
1999
+ * @param {(Object|function(Object))=} headers HTTP headers.
2000
+ * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
2001
+ * control how a matched request is handled. You can save this object for later use and invoke
2002
+ * `respond` or `passThrough` again in order to change how a matched request is handled.
2003
+ */
2004
+
2005
+ /**
2006
+ * @ngdoc method
2007
+ * @name $httpBackend#whenPATCH
2008
+ * @module ngMockE2E
2009
+ * @description
2010
+ * Creates a new backend definition for PATCH requests. For more info see `when()`.
2011
+ *
2012
+ * @param {string|RegExp|function(string)} url HTTP url or function that receives the url
2013
+ * and returns true if the url match the current definition.
2014
+ * @param {(string|RegExp)=} data HTTP request body.
2015
+ * @param {(Object|function(Object))=} headers HTTP headers.
2016
+ * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
2017
+ * control how a matched request is handled. You can save this object for later use and invoke
2018
+ * `respond` or `passThrough` again in order to change how a matched request is handled.
2019
+ */
2020
+
2021
+ /**
2022
+ * @ngdoc method
2023
+ * @name $httpBackend#whenJSONP
2024
+ * @module ngMockE2E
2025
+ * @description
2026
+ * Creates a new backend definition for JSONP requests. For more info see `when()`.
2027
+ *
2028
+ * @param {string|RegExp|function(string)} url HTTP url or function that receives the url
2029
+ * and returns true if the url match the current definition.
2030
+ * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
2031
+ * control how a matched request is handled. You can save this object for later use and invoke
2032
+ * `respond` or `passThrough` again in order to change how a matched request is handled.
2033
+ */
2034
+ angular.mock.e2e = {};
2035
+ angular.mock.e2e.$httpBackendDecorator =
2036
+ ['$rootScope', '$delegate', '$browser', createHttpBackendMock];
2037
+
2038
+
2039
+ if(window.jasmine || window.mocha) {
2040
+
2041
+ var currentSpec = null,
2042
+ isSpecRunning = function() {
2043
+ return !!currentSpec;
2044
+ };
2045
+
2046
+
2047
+ (window.beforeEach || window.setup)(function() {
2048
+ currentSpec = this;
2049
+ });
2050
+
2051
+ (window.afterEach || window.teardown)(function() {
2052
+ var injector = currentSpec.$injector;
2053
+
2054
+ angular.forEach(currentSpec.$modules, function(module) {
2055
+ if (module && module.$$hashKey) {
2056
+ module.$$hashKey = undefined;
2057
+ }
2058
+ });
2059
+
2060
+ currentSpec.$injector = null;
2061
+ currentSpec.$modules = null;
2062
+ currentSpec = null;
2063
+
2064
+ if (injector) {
2065
+ injector.get('$rootElement').off();
2066
+ injector.get('$browser').pollFns.length = 0;
2067
+ }
2068
+
2069
+ // clean up jquery's fragment cache
2070
+ angular.forEach(angular.element.fragments, function(val, key) {
2071
+ delete angular.element.fragments[key];
2072
+ });
2073
+
2074
+ MockXhr.$$lastInstance = null;
2075
+
2076
+ angular.forEach(angular.callbacks, function(val, key) {
2077
+ delete angular.callbacks[key];
2078
+ });
2079
+ angular.callbacks.counter = 0;
2080
+ });
2081
+
2082
+ /**
2083
+ * @ngdoc function
2084
+ * @name angular.mock.module
2085
+ * @description
2086
+ *
2087
+ * *NOTE*: This function is also published on window for easy access.<br>
2088
+ * *NOTE*: This function is declared ONLY WHEN running tests with jasmine or mocha
2089
+ *
2090
+ * This function registers a module configuration code. It collects the configuration information
2091
+ * which will be used when the injector is created by {@link angular.mock.inject inject}.
2092
+ *
2093
+ * See {@link angular.mock.inject inject} for usage example
2094
+ *
2095
+ * @param {...(string|Function|Object)} fns any number of modules which are represented as string
2096
+ * aliases or as anonymous module initialization functions. The modules are used to
2097
+ * configure the injector. The 'ng' and 'ngMock' modules are automatically loaded. If an
2098
+ * object literal is passed they will be registered as values in the module, the key being
2099
+ * the module name and the value being what is returned.
2100
+ */
2101
+ window.module = angular.mock.module = function() {
2102
+ var moduleFns = Array.prototype.slice.call(arguments, 0);
2103
+ return isSpecRunning() ? workFn() : workFn;
2104
+ /////////////////////
2105
+ function workFn() {
2106
+ if (currentSpec.$injector) {
2107
+ throw new Error('Injector already created, can not register a module!');
2108
+ } else {
2109
+ var modules = currentSpec.$modules || (currentSpec.$modules = []);
2110
+ angular.forEach(moduleFns, function(module) {
2111
+ if (angular.isObject(module) && !angular.isArray(module)) {
2112
+ modules.push(function($provide) {
2113
+ angular.forEach(module, function(value, key) {
2114
+ $provide.value(key, value);
2115
+ });
2116
+ });
2117
+ } else {
2118
+ modules.push(module);
2119
+ }
2120
+ });
2121
+ }
2122
+ }
2123
+ };
2124
+
2125
+ /**
2126
+ * @ngdoc function
2127
+ * @name angular.mock.inject
2128
+ * @description
2129
+ *
2130
+ * *NOTE*: This function is also published on window for easy access.<br>
2131
+ * *NOTE*: This function is declared ONLY WHEN running tests with jasmine or mocha
2132
+ *
2133
+ * The inject function wraps a function into an injectable function. The inject() creates new
2134
+ * instance of {@link auto.$injector $injector} per test, which is then used for
2135
+ * resolving references.
2136
+ *
2137
+ *
2138
+ * ## Resolving References (Underscore Wrapping)
2139
+ * Often, we would like to inject a reference once, in a `beforeEach()` block and reuse this
2140
+ * in multiple `it()` clauses. To be able to do this we must assign the reference to a variable
2141
+ * that is declared in the scope of the `describe()` block. Since we would, most likely, want
2142
+ * the variable to have the same name of the reference we have a problem, since the parameter
2143
+ * to the `inject()` function would hide the outer variable.
2144
+ *
2145
+ * To help with this, the injected parameters can, optionally, be enclosed with underscores.
2146
+ * These are ignored by the injector when the reference name is resolved.
2147
+ *
2148
+ * For example, the parameter `_myService_` would be resolved as the reference `myService`.
2149
+ * Since it is available in the function body as _myService_, we can then assign it to a variable
2150
+ * defined in an outer scope.
2151
+ *
2152
+ * ```
2153
+ * // Defined out reference variable outside
2154
+ * var myService;
2155
+ *
2156
+ * // Wrap the parameter in underscores
2157
+ * beforeEach( inject( function(_myService_){
2158
+ * myService = _myService_;
2159
+ * }));
2160
+ *
2161
+ * // Use myService in a series of tests.
2162
+ * it('makes use of myService', function() {
2163
+ * myService.doStuff();
2164
+ * });
2165
+ *
2166
+ * ```
2167
+ *
2168
+ * See also {@link angular.mock.module angular.mock.module}
2169
+ *
2170
+ * ## Example
2171
+ * Example of what a typical jasmine tests looks like with the inject method.
2172
+ * ```js
2173
+ *
2174
+ * angular.module('myApplicationModule', [])
2175
+ * .value('mode', 'app')
2176
+ * .value('version', 'v1.0.1');
2177
+ *
2178
+ *
2179
+ * describe('MyApp', function() {
2180
+ *
2181
+ * // You need to load modules that you want to test,
2182
+ * // it loads only the "ng" module by default.
2183
+ * beforeEach(module('myApplicationModule'));
2184
+ *
2185
+ *
2186
+ * // inject() is used to inject arguments of all given functions
2187
+ * it('should provide a version', inject(function(mode, version) {
2188
+ * expect(version).toEqual('v1.0.1');
2189
+ * expect(mode).toEqual('app');
2190
+ * }));
2191
+ *
2192
+ *
2193
+ * // The inject and module method can also be used inside of the it or beforeEach
2194
+ * it('should override a version and test the new version is injected', function() {
2195
+ * // module() takes functions or strings (module aliases)
2196
+ * module(function($provide) {
2197
+ * $provide.value('version', 'overridden'); // override version here
2198
+ * });
2199
+ *
2200
+ * inject(function(version) {
2201
+ * expect(version).toEqual('overridden');
2202
+ * });
2203
+ * });
2204
+ * });
2205
+ *
2206
+ * ```
2207
+ *
2208
+ * @param {...Function} fns any number of functions which will be injected using the injector.
2209
+ */
2210
+
2211
+
2212
+
2213
+ var ErrorAddingDeclarationLocationStack = function(e, errorForStack) {
2214
+ this.message = e.message;
2215
+ this.name = e.name;
2216
+ if (e.line) this.line = e.line;
2217
+ if (e.sourceId) this.sourceId = e.sourceId;
2218
+ if (e.stack && errorForStack)
2219
+ this.stack = e.stack + '\n' + errorForStack.stack;
2220
+ if (e.stackArray) this.stackArray = e.stackArray;
2221
+ };
2222
+ ErrorAddingDeclarationLocationStack.prototype.toString = Error.prototype.toString;
2223
+
2224
+ window.inject = angular.mock.inject = function() {
2225
+ var blockFns = Array.prototype.slice.call(arguments, 0);
2226
+ var errorForStack = new Error('Declaration Location');
2227
+ return isSpecRunning() ? workFn.call(currentSpec) : workFn;
2228
+ /////////////////////
2229
+ function workFn() {
2230
+ var modules = currentSpec.$modules || [];
2231
+ var strictDi = !!currentSpec.$injectorStrict;
2232
+ modules.unshift('ngMock');
2233
+ modules.unshift('ng');
2234
+ var injector = currentSpec.$injector;
2235
+ if (!injector) {
2236
+ if (strictDi) {
2237
+ // If strictDi is enabled, annotate the providerInjector blocks
2238
+ angular.forEach(modules, function(moduleFn) {
2239
+ if (typeof moduleFn === "function") {
2240
+ angular.injector.$$annotate(moduleFn);
2241
+ }
2242
+ });
2243
+ }
2244
+ injector = currentSpec.$injector = angular.injector(modules, strictDi);
2245
+ currentSpec.$injectorStrict = strictDi;
2246
+ }
2247
+ for(var i = 0, ii = blockFns.length; i < ii; i++) {
2248
+ if (currentSpec.$injectorStrict) {
2249
+ // If the injector is strict / strictDi, and the spec wants to inject using automatic
2250
+ // annotation, then annotate the function here.
2251
+ injector.annotate(blockFns[i]);
2252
+ }
2253
+ try {
2254
+ /* jshint -W040 *//* Jasmine explicitly provides a `this` object when calling functions */
2255
+ injector.invoke(blockFns[i] || angular.noop, this);
2256
+ /* jshint +W040 */
2257
+ } catch (e) {
2258
+ if (e.stack && errorForStack) {
2259
+ throw new ErrorAddingDeclarationLocationStack(e, errorForStack);
2260
+ }
2261
+ throw e;
2262
+ } finally {
2263
+ errorForStack = null;
2264
+ }
2265
+ }
2266
+ }
2267
+ };
2268
+
2269
+
2270
+ angular.mock.inject.strictDi = function(value) {
2271
+ value = arguments.length ? !!value : true;
2272
+ return isSpecRunning() ? workFn() : workFn;
2273
+
2274
+ function workFn() {
2275
+ if (value !== currentSpec.$injectorStrict) {
2276
+ if (currentSpec.$injector) {
2277
+ throw new Error('Injector already created, can not modify strict annotations');
2278
+ } else {
2279
+ currentSpec.$injectorStrict = value;
2280
+ }
2281
+ }
2282
+ }
2283
+ };
2284
+ }
2285
+
2286
+
2287
+ })(window, window.angular);