angular-mocks.js 78 KB

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