CNAS取数仪器端升级
25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.

2453 satır
80KB

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