aboutsummaryrefslogtreecommitdiffstats
path: root/src/angular-mocks.js
blob: ae0ba65e5dea658f6ad8a3f33325a62b797990c5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
/**
 * @license AngularJS v"NG_VERSION_FULL"
 * (c) 2010-2011 AngularJS http://angularjs.org
 * License: MIT
 */


window.angular = window.angular || {};
angular.module = angular.module || {};

/**
 * @ngdoc overview
 * @name angular.module.ngMock
 * @description
 *
 * The `ngMock` is an angular module which is used with `ng` module and adds unit-test configuration as well as useful
 * mocks to the {@link angular.module.AUTO.$injector $injector}.
 */
angular.module.ngMock = function($provide){
  $provide.service('$browser', angular.module.ngMock.$BrowserProvider);
  $provide.service('$exceptionHandler', angular.module.ngMock.$ExceptionHandlerProvider);
  $provide.service('$log', angular.module.ngMock.$LogProvider);
};
angular.module.ngMock.$inject = ['$provide'];

/**
 * @ngdoc object
 * @name angular.module.ngMock.$browser
 *
 * @description
 * This service is a mock implementation of {@link angular.module.ng.$browser}. It provides fake
 * implementation for commonly used browser apis that are hard to test, e.g. setTimeout, xhr,
 * cookies, etc...
 *
 * The api of this service is the same as that of the real {@link angular.module.ng.$browser $browser}, except
 * that there are several helper methods available which can be used in tests.
 *
 * The following apis can be used in tests:
 *
 * - {@link #xhr} — enables testing of code that uses
 *   the {@link angular.module.ng.$xhr $xhr service} to make XmlHttpRequests.
 * - $browser.defer — enables testing of code that uses
 *   {@link angular.module.ng.$defer $defer} for executing functions via the `setTimeout` api.
 */
angular.module.ngMock.$BrowserProvider = function(){
  this.$get = function(){
    return new angular.module.ngMock.$Browser();
  };
};
angular.module.ngMock.$Browser = function() {
  var self = this,
      expectations = {},
      requests = [];

  this.isMock = true;
  self.$$url = "http://server";
  self.$$lastUrl = self.$$url; // used by url polling fn
  self.pollFns = [];


  // register url polling fn

  self.onUrlChange = function(listener) {
    self.pollFns.push(
      function() {
        if (self.$$lastUrl != self.$$url) {
          self.$$lastUrl = self.$$url;
          listener(self.$$url);
        }
      }
    );

    return listener;
  };


  /**
    * @ngdoc method
    * @name angular.module.ngMock.$browser#xhr
    * @methodOf angular.module.ngMock.$browser
    *
    * @description
    * Generic method for training browser to expect a request in a test and respond to it.
    *
    * See also convenience methods for browser training:
    *
    * - {@link #xhr.expectGET}
    * - {@link #xhr.expectPOST}
    * - {@link #xhr.expectPUT}
    * - {@link #xhr.expectDELETE}
    * - {@link #xhr.expectJSON}
    *
    * To flush pending requests in tests use
    * {@link #xhr.flush}.
    *
    * @param {string} method Expected HTTP method.
    * @param {string} url Url path for which a request is expected.
    * @param {(object|string)=} data Expected body of the (POST) HTTP request.
    * @param {function(number, *)} callback Callback to call when response is flushed.
    * @param {object} headers Key-value pairs of expected headers.
    * @returns {object} Response configuration object. You can call its `respond()` method to
    *   configure what should the browser mock return when the response is
    *   {@link #xhr.flush flushed}.
    */
  self.xhr = function(method, url, data, callback, headers) {
    headers = headers || {};
    if (data && angular.isObject(data)) data = angular.toJson(data);
    if (data && angular.isString(data)) url += "|" + data;
    var expect = expectations[method] || {};
    var expectation = expect[url];
    if (!expectation) {
      throw new Error("Unexpected request for method '" + method + "' and url '" + url + "'.");
    }
    requests.push(function() {
      angular.forEach(expectation.headers, function(value, key){
        if (headers[key] !== value) {
          throw new Error("Missing HTTP request header: " + key + ": " + value);
        }
      });
      callback(expectation.code, expectation.response);
    });
  };
  self.xhr.expectations = expectations;
  self.xhr.requests = requests;
  self.xhr.expect = function(method, url, data, headers) {
    if (data && angular.isObject(data)) data = angular.toJson(data);
    if (data && angular.isString(data)) url += "|" + data;
    var expect = expectations[method] || (expectations[method] = {});
    return {
      respond: function(code, response) {
        if (!angular.isNumber(code)) {
          response = code;
          code = 200;
        }
        expect[url] = {code:code, response:response, headers: headers || {}};
      }
    };
  };

  /**
    * @ngdoc method
    * @name angular.module.ngMock.$browser#xhr.expectGET
    * @methodOf angular.module.ngMock.$browser
    *
    * @description
    * Trains browser to expect a `GET` request and respond to it.
    *
    * @param {string} url Url path for which a request is expected.
    * @returns {object} Response configuration object. You can call its `respond()` method to
    *   configure what should the browser mock return when the response is
    *   {@link angular.module.ngMock.$browser#xhr.flush flushed}.
    */
  self.xhr.expectGET    = angular.bind(self, self.xhr.expect, 'GET');

  /**
   * @ngdoc method
   * @name angular.module.ngMock.$browser#xhr.expectPOST
   * @methodOf angular.module.ngMock.$browser
    *
    * @description
    * Trains browser to expect a `POST` request and respond to it.
    *
    * @param {string} url Url path for which a request is expected.
    * @returns {object} Response configuration object. You can call its `respond()` method to
    *   configure what should the browser mock return when the response is
    *   {@link angular.module.ngMock.$browser#xhr.flush flushed}.
    */
  self.xhr.expectPOST   = angular.bind(self, self.xhr.expect, 'POST');

  /**
   * @ngdoc method
   * @name angular.module.ngMock.$browser#xhr.expectDELETE
   * @methodOf angular.module.ngMock.$browser
    *
    * @description
    * Trains browser to expect a `DELETE` request and respond to it.
    *
    * @param {string} url Url path for which a request is expected.
    * @returns {object} Response configuration object. You can call its `respond()` method to
    *   configure what should the browser mock return when the response is
    *   {@link angular.module.ngMock.$browser#xhr.flush flushed}.
    */
  self.xhr.expectDELETE = angular.bind(self, self.xhr.expect, 'DELETE');

  /**
   * @ngdoc method
   * @name angular.module.ngMock.$browser#xhr.expectPUT
   * @methodOf angular.module.ngMock.$browser
    *
    * @description
    * Trains browser to expect a `PUT` request and respond to it.
    *
    * @param {string} url Url path for which a request is expected.
    * @returns {object} Response configuration object. You can call its `respond()` method to
    *   configure what should the browser mock return when the response is
    *   {@link angular.module.ngMock.$browser#xhr.flush flushed}.
    */
  self.xhr.expectPUT    = angular.bind(self, self.xhr.expect, 'PUT');

  /**
   * @ngdoc method
   * @name angular.module.ngMock.$browser#xhr.expectJSON
   * @methodOf angular.module.ngMock.$browser
    *
    * @description
    * Trains browser to expect a `JSON` request and respond to it.
    *
    * @param {string} url Url path for which a request is expected.
    * @returns {object} Response configuration object. You can call its `respond()` method to
    *   configure what should the browser mock return when the response is
    *   {@link angular.module.ngMock.$browser#xhr.flush flushed}.
    */
  self.xhr.expectJSON   = angular.bind(self, self.xhr.expect, 'JSON');

  /**
   * @ngdoc method
   * @name angular.module.ngMock.$browser#xhr.flush
   * @methodOf angular.module.ngMock.$browser
    *
    * @description
    * Flushes all pending requests and executes xhr callbacks with the trained response as the
    * argument.
    */
  self.xhr.flush = function() {
    if (requests.length == 0) {
      throw new Error("No xhr requests to be flushed!");
    }

    while(requests.length) {
      requests.pop()();
    }
  };

  self.cookieHash = {};
  self.lastCookieHash = {};
  self.deferredFns = [];
  self.deferredNextId = 0;

  self.defer = function(fn, delay) {
    delay = delay || 0;
    self.deferredFns.push({time:(self.defer.now + delay), fn:fn, id: self.deferredNextId});
    self.deferredFns.sort(function(a,b){ return a.time - b.time;});
    return self.deferredNextId++;
  };


  self.defer.now = 0;


  self.defer.cancel = function(deferId) {
    var fnIndex;

    angular.forEach(self.deferredFns, function(fn, index) {
      if (fn.id === deferId) fnIndex = index;
    });

    if (fnIndex !== undefined) {
      self.deferredFns.splice(fnIndex, 1);
      return true;
    }

    return false;
  };


  /**
   * @ngdoc method
   * @name angular.module.ngMock.$browser#defer.flush
   * @methodOf angular.module.ngMock.$browser
   *
   * @description
   * Flushes all pending requests and executes the defer callbacks.
   *
   * @param {number=} number of miliseconds to flush. See {@link #defer.now}
   */
  self.defer.flush = function(delay) {
    if (angular.isDefined(delay)) {
      self.defer.now += delay;
    } else {
      if (self.deferredFns.length) {
        self.defer.now = self.deferredFns[self.deferredFns.length-1].time;
      }
    }

    while (self.deferredFns.length && self.deferredFns[0].time <= self.defer.now) {
      self.deferredFns.shift().fn();
    }
  };
  /**
   * @ngdoc property
   * @name angular.module.ngMock.$browser#defer.now
   * @propertyOf angular.module.ngMock.$browser
   *
   * @description
   * Current milliseconds mock time.
   */

  self.$$baseHref = '';
  self.baseHref = function() {
    return this.$$baseHref;
  };
}
angular.module.ngMock.$Browser.prototype = {

/**
  * @name angular.module.ngMock.$browser#poll
  * @methodOf angular.module.ngMock.$browser
  *
  * @description
  * run all fns in pollFns
  */
  poll: function poll() {
    angular.forEach(this.pollFns, function(pollFn){
      pollFn();
    });
  },

  addPollFn: function(pollFn) {
    this.pollFns.push(pollFn);
    return pollFn;
  },

  url: function(url, replace) {
    if (url) {
      this.$$url = url;
      return this;
    }

    return this.$$url;
  },

  cookies:  function(name, value) {
    if (name) {
      if (value == undefined) {
        delete this.cookieHash[name];
      } else {
        if (angular.isString(value) &&       //strings only
            value.length <= 4096) {          //strict cookie storage limits
          this.cookieHash[name] = value;
        }
      }
    } else {
      if (!angular.equals(this.cookieHash, this.lastCookieHash)) {
        this.lastCookieHash = angular.copy(this.cookieHash);
        this.cookieHash = angular.copy(this.cookieHash);
      }
      return this.cookieHash;
    }
  },

  notifyWhenNoOutstandingRequests: function(fn) {
    fn();
  }
};


/**
 * @ngdoc object
 * @name angular.module.ngMock.$exceptionHandlerProvider
 *
 * @description
 * Configures the mock implementation of {@link angular.module.ng.$exceptionHandler} to rethrow or to log errors passed
 * into the `$exceptionHandler`.
 */

/**
 * @ngdoc object
 * @name angular.module.ngMock.$exceptionHandler
 *
 * @description
 * Mock implementation of {@link angular.module.ng.$exceptionHandler} that rethrows or logs errors passed
 * into it. See {@link angular.module.ngMock.$exceptionHandlerProvider $exceptionHandlerProvider} for configuration
 * information.
 */

angular.module.ngMock.$ExceptionHandlerProvider = function(){
  var handler;

  /**
   * @ngdoc method
   * @name angular.module.ngMock.$exceptionHandlerProvider#mode
   * @methodOf angular.module.ngMock.$exceptionHandlerProvider
   *
   * @description
   * Sets the logging mode.
   *
   * @param {string} mode Mode of operation, defaults to `rethrow`.
   *
   *   - `rethrow`: If any errors are are passed into the handler in tests, it typically
   *                means that there is a bug in the application or test, so this mock will
   *                make these tests fail.
   *   - `log`: Sometimes it is desirable to test that an error is throw, for this case the `log` mode stores the
   *            error and allows later assertion of it.
   *            See {@link angular.module.ngMock.$log#assertEmpty assertEmpty()} and
   *             {@link angular.module.ngMock.$log#reset reset()}
   */
  this.mode = function(mode){
    switch(mode) {
      case 'rethrow':
        handler = function(e) {
          throw e;
        }
        break;
      case 'log':
        var errors = [];
        handler = function(e) {
          errors.push(e);
        }
        handler.errors = errors;
        break;
      default:
        throw Error("Unknown mode '" + mode + "', only 'log'/'rethrow' modes are allowed!");
    }
  };

  this.$get = function(){
    return handler;
  };

  this.mode('rethrow');
};


/**
 * @ngdoc service
 * @name angular.module.ngMock.$log
 *
 * @description
 * Mock implementation of {@link angular.module.ng.$log} that gathers all logged messages in arrays
 * (one array per logging level). These arrays are exposed as `logs` property of each of the
 * level-specific log function, e.g. for level `error` the array is exposed as `$log.error.logs`.
 *
 */
angular.module.ngMock.$LogProvider = function(){

  function concat(array1, array2, index) {
    return array1.concat(Array.prototype.slice.call(array2, index));
  }


  this.$get = function () {
    var $log = {
      log: function() { $log.log.logs.push(concat([], arguments, 0)); },
      warn: function() { $log.warn.logs.push(concat([], arguments, 0)); },
      info: function() { $log.info.logs.push(concat([], arguments, 0)); },
      error: function() { $log.error.logs.push(concat([], arguments, 0)); }
    };

    /**
     * @ngdoc method
     * @name angular.module.ngMock.$log#reset
     * @methodOf angular.module.ngMock.$log
     *
     * @description
     * Reset all of the logging arrays to empty.
     */
    $log.reset = function (){
      /**
       * @ngdoc property
       * @name angular.module.ngMock.$log#log.logs
       * @propertyOf angular.module.ngMock.$log
       *
       * @description
       * Array of logged messages.
       */
      $log.log.logs = [];
      /**
       * @ngdoc property
       * @name angular.module.ngMock.$log#warn.logs
       * @propertyOf angular.module.ngMock.$log
       *
       * @description
       * Array of logged messages.
       */
      $log.warn.logs = [];
      /**
       * @ngdoc property
       * @name angular.module.ngMock.$log#info.logs
       * @propertyOf angular.module.ngMock.$log
       *
       * @description
       * Array of logged messages.
       */
      $log.info.logs = [];
      /**
       * @ngdoc property
       * @name angular.module.ngMock.$log#error.logs
       * @propertyOf angular.module.ngMock.$log
       *
       * @description
       * Array of logged messages.
       */
      $log.error.logs = [];
    };

    /**
     * @ngdoc method
     * @name angular.module.ngMock.$log#assertEmpty
     * @methodOf angular.module.ngMock.$log
     *
     * @description
     * Assert that the all of the logging methods have no logged messages. If messages present, an exception is thrown.
     */
    $log.assertEmpty = function() {
      var errors = [];
      angular.forEach(['error', 'warn', 'info', 'log'], function(logLevel) {
        angular.forEach($log[logLevel].logs, function(log) {
          angular.forEach(log, function (logItem) {
            errors.push('MOCK $log (' + logLevel + '): ' + String(logItem) + '\n' + (logItem.stack || ''));
          });
        });
      });
      if (errors.length) {
        errors.unshift("Expected $log to be empty! Either a message was logged unexpectedly, or an expected " +
          "log message was not checked and removed:");
        errors.push('')
        throw new Error(errors.join('\n---------\n'));
      }
    };

    $log.reset();
    return $log;
  };
};


/**
 * @ngdoc object
 * @name angular.module.ngMock.TzDate
 * @description
 *
 * *NOTE*: this is not an injectable instance, just a globally available mock class of `Date`.
 *
 * Mock of the Date type which has its timezone specified via constroctor arg.
 *
 * The main purpose is to create Date-like instances with timezone fixed to the specified timezone
 * offset, so that we can test code that depends on local timezone settings without dependency on
 * the time zone settings of the machine where the code is running.
 *
 * @param {number} offset Offset of the *desired* timezone in hours (fractions will be honored)
 * @param {(number|string)} timestamp Timestamp representing the desired time in *UTC*
 *
 * @example
 * !!!! WARNING !!!!!
 * This is not a complete Date object so only methods that were implemented can be called safely.
 * To make matters worse, TzDate instances inherit stuff from Date via a prototype.
 *
 * We do our best to intercept calls to "unimplemented" methods, but since the list of methods is
 * incomplete we might be missing some non-standard methods. This can result in errors like:
 * "Date.prototype.foo called on incompatible Object".
 *
 * <pre>
 * var newYearInBratislava = new TzDate(-1, '2009-12-31T23:00:00Z');
 * newYearInBratislava.getTimezoneOffset() => -60;
 * newYearInBratislava.getFullYear() => 2010;
 * newYearInBratislava.getMonth() => 0;
 * newYearInBratislava.getDate() => 1;
 * newYearInBratislava.getHours() => 0;
 * newYearInBratislava.getMinutes() => 0;
 * </pre>
 *
 */
angular.module.ngMock.TzDate = function (offset, timestamp) {
  var self = new Date(0);
  if (angular.isString(timestamp)) {
    var tsStr = timestamp;

    self.origDate = angular.fromJson(angular.toJson({date:timestamp})).date;

    timestamp = self.origDate.getTime();
    if (isNaN(timestamp))
      throw {
        name: "Illegal Argument",
        message: "Arg '" + tsStr + "' passed into TzDate constructor is not a valid date string"
      };
  } else {
    self.origDate = new Date(timestamp);
  }

  var localOffset = new Date(timestamp).getTimezoneOffset();
  self.offsetDiff = localOffset*60*1000 - offset*1000*60*60;
  self.date = new Date(timestamp + self.offsetDiff);

  self.getTime = function() {
    return self.date.getTime() - self.offsetDiff;
  };

  self.toLocaleDateString = function() {
    return self.date.toLocaleDateString();
  };

  self.getFullYear = function() {
    return self.date.getFullYear();
  };

  self.getMonth = function() {
    return self.date.getMonth();
  };

  self.getDate = function() {
    return self.date.getDate();
  };

  self.getHours = function() {
    return self.date.getHours();
  };

  self.getMinutes = function() {
    return self.date.getMinutes();
  };

  self.getSeconds = function() {
    return self.date.getSeconds();
  };

  self.getTimezoneOffset = function() {
    return offset * 60;
  };

  self.getUTCFullYear = function() {
    return self.origDate.getUTCFullYear();
  };

  self.getUTCMonth = function() {
    return self.origDate.getUTCMonth();
  };

  self.getUTCDate = function() {
    return self.origDate.getUTCDate();
  };

  self.getUTCHours = function() {
    return self.origDate.getUTCHours();
  };

  self.getUTCMinutes = function() {
    return self.origDate.getUTCMinutes();
  };

  self.getUTCSeconds = function() {
    return self.origDate.getUTCSeconds();
  };

  self.getDay = function() {
    return self.origDate.getDay();
  };

  //hide all methods not implemented in this mock that the Date prototype exposes
  var unimplementedMethods = ['getMilliseconds', 'getUTCDay',
      'getUTCMilliseconds', 'getYear', 'setDate', 'setFullYear', 'setHours', 'setMilliseconds',
      'setMinutes', 'setMonth', 'setSeconds', 'setTime', 'setUTCDate', 'setUTCFullYear',
      'setUTCHours', 'setUTCMilliseconds', 'setUTCMinutes', 'setUTCMonth', 'setUTCSeconds',
      'setYear', 'toDateString', 'toJSON', 'toGMTString', 'toLocaleFormat', 'toLocaleString',
      'toLocaleTimeString', 'toSource', 'toString', 'toTimeString', 'toUTCString', 'valueOf'];

  angular.forEach(unimplementedMethods, function(methodName) {
    self[methodName] = function() {
      throw Error("Method '" + methodName + "' is not implemented in the TzDate mock");
    };
  });

  return self;
}

//make "tzDateInstance instanceof Date" return true
angular.module.ngMock.TzDate.prototype = Date.prototype;


/**
 * @ngdoc function
 * @name angular.module.ngMock.debug
 * @description
 *
 * *NOTE*: this is not an injectable instance, just a globally available function.
 *
 * Method for serializing common angular objects (scope, elements, etc..) into strings, useful for debugging.
 *
 * This method is also available on window, where it can be used to display objects on debug console.
 *
 * @param {*} object - any object to turn into string.
 * @return a serialized string of the argument
 */
angular.module.ngMock.dump = function(object){
  var out;
  if (angular.isElement(object)) {
    object = angular.element(object);
    out = angular.element('<div></div>')
    angular.forEach(object, function(element){
      out.append(angular.element(element).clone());
    });
    out = out.html();
  } else if (angular.isObject(object)) {
    if (angular.isFunction(object.$eval) && angular.isFunction(object.$apply)) {
      out = serializeScope(object);
    } else {
      out = angular.toJson(object, true);
    }
  } else {
    out = String(object);
  }
  return out;

  function serializeScope(scope, offset) {
    offset = offset ||  '  ';
    var log = [offset + 'Scope(' + scope.$id + '): {'];
    for ( var key in scope ) {
      if (scope.hasOwnProperty(key) && !key.match(/^(\$|this)/)) {
        log.push('  ' + key + ': ' + angular.toJson(scope[key]));
      }
    }
    var child = scope.$$childHead;
    while(child) {
      log.push(serializeScope(child, offset + '  '));
      child = child.$$nextSibling;
    }
    log.push('}');
    return log.join('\n' + offset);
  }
};

window.jstestdriver && (function(window){
  /**
   * Global method to output any number of objects into JSTD console. Useful for debugging.
   */
  window.dump = function() {
    var args = [];
    angular.forEach(arguments, function(arg){
      args.push(angular.module.ngMock.dump(arg));
    });
    jstestdriver.console.log.apply(jstestdriver.console, args);
  };
})(window);


/**
 * @ngdoc function
 * @name angular.module.ngMock.inject
 * @description
 *
 * *NOTE*: this is not an injectable instance, just a globally available function on window.
 *
 * This function wraps a test method into an injectable method. It create one
 * {@link angular.module.AUTO.$injector $injector} per test, which is then used for testing.
 *
 * Here is an example of what a typical jasmine tests looks like with the inject method.
 * <pre>
 *   describe('MyApp', function() {
 *
 *     // Argument inference is used to inject the $provide service
 *     beforeEach(inject(function($provide, $rootScope) {
 *       // $provide service is configured as needed
 *       $provide.value('version', 'v1.0.1');
 *       $rootScope.value = 123;
 *     });
 *
 *     // Argument inference is used to inject the $rootScope as well as the version
 *     it('should provide a version', inject(function($rootScope, version){
 *       expect(version).toEqual('v1.0.1');
 *       expect($rootScope.value).toEqual(123);
 *     });
 *
 *     // The inject can also chain the methods
 *     it('should override a version and test the new version is injected', inject(
 *       function($provide) {
 *         $provide.value('version', 'overridden'); // override version here
 *       },
 *       function(version) {
 *         expect(version).toEqual('overridden');
 *       }
 *     ));
 *
 *   });
 *
 * </pre>
 *
 * @param {*} fns... any number of functions which will be injected using the injector.
 * @return a method
 */
window.jasmine && (function(window){
  window.inject = function (){
    var blockFns = Array.prototype.slice.call(arguments, 0);
    return function(){
      var injector = this.$injector;
      if (!injector) {
        injector = this.$injector =  angular.injector('ng', 'ngMock');
      }
      for(var i = 0, ii = blockFns.length; i < ii; i++) {
        injector.invoke(this, blockFns[i]);
      }
    };
  }
})(window);