No Description

angular-mocks.js 106KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127
  1. /**
  2. * @license AngularJS v1.5.8
  3. * (c) 2010-2016 Google, Inc. http://angularjs.org
  4. * License: MIT
  5. */
  6. (function(window, angular) {
  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. */
  16. angular.mock = {};
  17. /**
  18. * ! This is a private undocumented service !
  19. *
  20. * @name $browser
  21. *
  22. * @description
  23. * This service is a mock implementation of {@link ng.$browser}. It provides fake
  24. * implementation for commonly used browser apis that are hard to test, e.g. setTimeout, xhr,
  25. * cookies, etc.
  26. *
  27. * The api of this service is the same as that of the real {@link ng.$browser $browser}, except
  28. * that there are several helper methods available which can be used in tests.
  29. */
  30. angular.mock.$BrowserProvider = function() {
  31. this.$get = function() {
  32. return new angular.mock.$Browser();
  33. };
  34. };
  35. angular.mock.$Browser = function() {
  36. var self = this;
  37. this.isMock = true;
  38. self.$$url = "http://server/";
  39. self.$$lastUrl = self.$$url; // used by url polling fn
  40. self.pollFns = [];
  41. // TODO(vojta): remove this temporary api
  42. self.$$completeOutstandingRequest = angular.noop;
  43. self.$$incOutstandingRequestCount = angular.noop;
  44. // register url polling fn
  45. self.onUrlChange = function(listener) {
  46. self.pollFns.push(
  47. function() {
  48. if (self.$$lastUrl !== self.$$url || self.$$state !== self.$$lastState) {
  49. self.$$lastUrl = self.$$url;
  50. self.$$lastState = self.$$state;
  51. listener(self.$$url, self.$$state);
  52. }
  53. }
  54. );
  55. return listener;
  56. };
  57. self.$$applicationDestroyed = angular.noop;
  58. self.$$checkUrlChange = angular.noop;
  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 (angular.isDefined(fnIndex)) {
  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. var nextTime;
  95. if (angular.isDefined(delay)) {
  96. // A delay was passed so compute the next time
  97. nextTime = self.defer.now + delay;
  98. } else {
  99. if (self.deferredFns.length) {
  100. // No delay was passed so set the next time so that it clears the deferred queue
  101. nextTime = self.deferredFns[self.deferredFns.length - 1].time;
  102. } else {
  103. // No delay passed, but there are no deferred tasks so flush - indicates an error!
  104. throw new Error('No deferred tasks to be flushed');
  105. }
  106. }
  107. while (self.deferredFns.length && self.deferredFns[0].time <= nextTime) {
  108. // Increment the time and call the next deferred function
  109. self.defer.now = self.deferredFns[0].time;
  110. self.deferredFns.shift().fn();
  111. }
  112. // Ensure that the current time is correct
  113. self.defer.now = nextTime;
  114. };
  115. self.$$baseHref = '/';
  116. self.baseHref = function() {
  117. return this.$$baseHref;
  118. };
  119. };
  120. angular.mock.$Browser.prototype = {
  121. /**
  122. * @name $browser#poll
  123. *
  124. * @description
  125. * run all fns in pollFns
  126. */
  127. poll: function poll() {
  128. angular.forEach(this.pollFns, function(pollFn) {
  129. pollFn();
  130. });
  131. },
  132. url: function(url, replace, state) {
  133. if (angular.isUndefined(state)) {
  134. state = null;
  135. }
  136. if (url) {
  137. this.$$url = url;
  138. // Native pushState serializes & copies the object; simulate it.
  139. this.$$state = angular.copy(state);
  140. return this;
  141. }
  142. return this.$$url;
  143. },
  144. state: function() {
  145. return this.$$state;
  146. },
  147. notifyWhenNoOutstandingRequests: function(fn) {
  148. fn();
  149. }
  150. };
  151. /**
  152. * @ngdoc provider
  153. * @name $exceptionHandlerProvider
  154. *
  155. * @description
  156. * Configures the mock implementation of {@link ng.$exceptionHandler} to rethrow or to log errors
  157. * passed to the `$exceptionHandler`.
  158. */
  159. /**
  160. * @ngdoc service
  161. * @name $exceptionHandler
  162. *
  163. * @description
  164. * Mock implementation of {@link ng.$exceptionHandler} that rethrows or logs errors passed
  165. * to it. See {@link ngMock.$exceptionHandlerProvider $exceptionHandlerProvider} for configuration
  166. * information.
  167. *
  168. *
  169. * ```js
  170. * describe('$exceptionHandlerProvider', function() {
  171. *
  172. * it('should capture log messages and exceptions', function() {
  173. *
  174. * module(function($exceptionHandlerProvider) {
  175. * $exceptionHandlerProvider.mode('log');
  176. * });
  177. *
  178. * inject(function($log, $exceptionHandler, $timeout) {
  179. * $timeout(function() { $log.log(1); });
  180. * $timeout(function() { $log.log(2); throw 'banana peel'; });
  181. * $timeout(function() { $log.log(3); });
  182. * expect($exceptionHandler.errors).toEqual([]);
  183. * expect($log.assertEmpty());
  184. * $timeout.flush();
  185. * expect($exceptionHandler.errors).toEqual(['banana peel']);
  186. * expect($log.log.logs).toEqual([[1], [2], [3]]);
  187. * });
  188. * });
  189. * });
  190. * ```
  191. */
  192. angular.mock.$ExceptionHandlerProvider = function() {
  193. var handler;
  194. /**
  195. * @ngdoc method
  196. * @name $exceptionHandlerProvider#mode
  197. *
  198. * @description
  199. * Sets the logging mode.
  200. *
  201. * @param {string} mode Mode of operation, defaults to `rethrow`.
  202. *
  203. * - `log`: Sometimes it is desirable to test that an error is thrown, for this case the `log`
  204. * mode stores an array of errors in `$exceptionHandler.errors`, to allow later assertion of
  205. * them. See {@link ngMock.$log#assertEmpty assertEmpty()} and
  206. * {@link ngMock.$log#reset reset()}.
  207. * - `rethrow`: If any errors are passed to the handler in tests, it typically means that there
  208. * is a bug in the application or test, so this mock will make these tests fail. For any
  209. * implementations that expect exceptions to be thrown, the `rethrow` mode will also maintain
  210. * a log of thrown errors in `$exceptionHandler.errors`.
  211. */
  212. this.mode = function(mode) {
  213. switch (mode) {
  214. case 'log':
  215. case 'rethrow':
  216. var errors = [];
  217. handler = function(e) {
  218. if (arguments.length == 1) {
  219. errors.push(e);
  220. } else {
  221. errors.push([].slice.call(arguments, 0));
  222. }
  223. if (mode === "rethrow") {
  224. throw e;
  225. }
  226. };
  227. handler.errors = errors;
  228. break;
  229. default:
  230. throw new Error("Unknown mode '" + mode + "', only 'log'/'rethrow' modes are allowed!");
  231. }
  232. };
  233. this.$get = function() {
  234. return handler;
  235. };
  236. this.mode('rethrow');
  237. };
  238. /**
  239. * @ngdoc service
  240. * @name $log
  241. *
  242. * @description
  243. * Mock implementation of {@link ng.$log} that gathers all logged messages in arrays
  244. * (one array per logging level). These arrays are exposed as `logs` property of each of the
  245. * level-specific log function, e.g. for level `error` the array is exposed as `$log.error.logs`.
  246. *
  247. */
  248. angular.mock.$LogProvider = function() {
  249. var debug = true;
  250. function concat(array1, array2, index) {
  251. return array1.concat(Array.prototype.slice.call(array2, index));
  252. }
  253. this.debugEnabled = function(flag) {
  254. if (angular.isDefined(flag)) {
  255. debug = flag;
  256. return this;
  257. } else {
  258. return debug;
  259. }
  260. };
  261. this.$get = function() {
  262. var $log = {
  263. log: function() { $log.log.logs.push(concat([], arguments, 0)); },
  264. warn: function() { $log.warn.logs.push(concat([], arguments, 0)); },
  265. info: function() { $log.info.logs.push(concat([], arguments, 0)); },
  266. error: function() { $log.error.logs.push(concat([], arguments, 0)); },
  267. debug: function() {
  268. if (debug) {
  269. $log.debug.logs.push(concat([], arguments, 0));
  270. }
  271. }
  272. };
  273. /**
  274. * @ngdoc method
  275. * @name $log#reset
  276. *
  277. * @description
  278. * Reset all of the logging arrays to empty.
  279. */
  280. $log.reset = function() {
  281. /**
  282. * @ngdoc property
  283. * @name $log#log.logs
  284. *
  285. * @description
  286. * Array of messages logged using {@link ng.$log#log `log()`}.
  287. *
  288. * @example
  289. * ```js
  290. * $log.log('Some Log');
  291. * var first = $log.log.logs.unshift();
  292. * ```
  293. */
  294. $log.log.logs = [];
  295. /**
  296. * @ngdoc property
  297. * @name $log#info.logs
  298. *
  299. * @description
  300. * Array of messages logged using {@link ng.$log#info `info()`}.
  301. *
  302. * @example
  303. * ```js
  304. * $log.info('Some Info');
  305. * var first = $log.info.logs.unshift();
  306. * ```
  307. */
  308. $log.info.logs = [];
  309. /**
  310. * @ngdoc property
  311. * @name $log#warn.logs
  312. *
  313. * @description
  314. * Array of messages logged using {@link ng.$log#warn `warn()`}.
  315. *
  316. * @example
  317. * ```js
  318. * $log.warn('Some Warning');
  319. * var first = $log.warn.logs.unshift();
  320. * ```
  321. */
  322. $log.warn.logs = [];
  323. /**
  324. * @ngdoc property
  325. * @name $log#error.logs
  326. *
  327. * @description
  328. * Array of messages logged using {@link ng.$log#error `error()`}.
  329. *
  330. * @example
  331. * ```js
  332. * $log.error('Some Error');
  333. * var first = $log.error.logs.unshift();
  334. * ```
  335. */
  336. $log.error.logs = [];
  337. /**
  338. * @ngdoc property
  339. * @name $log#debug.logs
  340. *
  341. * @description
  342. * Array of messages logged using {@link ng.$log#debug `debug()`}.
  343. *
  344. * @example
  345. * ```js
  346. * $log.debug('Some Error');
  347. * var first = $log.debug.logs.unshift();
  348. * ```
  349. */
  350. $log.debug.logs = [];
  351. };
  352. /**
  353. * @ngdoc method
  354. * @name $log#assertEmpty
  355. *
  356. * @description
  357. * Assert that all of the logging methods have no logged messages. If any messages are present,
  358. * an exception is thrown.
  359. */
  360. $log.assertEmpty = function() {
  361. var errors = [];
  362. angular.forEach(['error', 'warn', 'info', 'log', 'debug'], function(logLevel) {
  363. angular.forEach($log[logLevel].logs, function(log) {
  364. angular.forEach(log, function(logItem) {
  365. errors.push('MOCK $log (' + logLevel + '): ' + String(logItem) + '\n' +
  366. (logItem.stack || ''));
  367. });
  368. });
  369. });
  370. if (errors.length) {
  371. errors.unshift("Expected $log to be empty! Either a message was logged unexpectedly, or " +
  372. "an expected log message was not checked and removed:");
  373. errors.push('');
  374. throw new Error(errors.join('\n---------\n'));
  375. }
  376. };
  377. $log.reset();
  378. return $log;
  379. };
  380. };
  381. /**
  382. * @ngdoc service
  383. * @name $interval
  384. *
  385. * @description
  386. * Mock implementation of the $interval service.
  387. *
  388. * Use {@link ngMock.$interval#flush `$interval.flush(millis)`} to
  389. * move forward by `millis` milliseconds and trigger any functions scheduled to run in that
  390. * time.
  391. *
  392. * @param {function()} fn A function that should be called repeatedly.
  393. * @param {number} delay Number of milliseconds between each function call.
  394. * @param {number=} [count=0] Number of times to repeat. If not set, or 0, will repeat
  395. * indefinitely.
  396. * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
  397. * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
  398. * @param {...*=} Pass additional parameters to the executed function.
  399. * @returns {promise} A promise which will be notified on each iteration.
  400. */
  401. angular.mock.$IntervalProvider = function() {
  402. this.$get = ['$browser', '$rootScope', '$q', '$$q',
  403. function($browser, $rootScope, $q, $$q) {
  404. var repeatFns = [],
  405. nextRepeatId = 0,
  406. now = 0;
  407. var $interval = function(fn, delay, count, invokeApply) {
  408. var hasParams = arguments.length > 4,
  409. args = hasParams ? Array.prototype.slice.call(arguments, 4) : [],
  410. iteration = 0,
  411. skipApply = (angular.isDefined(invokeApply) && !invokeApply),
  412. deferred = (skipApply ? $$q : $q).defer(),
  413. promise = deferred.promise;
  414. count = (angular.isDefined(count)) ? count : 0;
  415. promise.then(null, null, (!hasParams) ? fn : function() {
  416. fn.apply(null, args);
  417. });
  418. promise.$$intervalId = nextRepeatId;
  419. function tick() {
  420. deferred.notify(iteration++);
  421. if (count > 0 && iteration >= count) {
  422. var fnIndex;
  423. deferred.resolve(iteration);
  424. angular.forEach(repeatFns, function(fn, index) {
  425. if (fn.id === promise.$$intervalId) fnIndex = index;
  426. });
  427. if (angular.isDefined(fnIndex)) {
  428. repeatFns.splice(fnIndex, 1);
  429. }
  430. }
  431. if (skipApply) {
  432. $browser.defer.flush();
  433. } else {
  434. $rootScope.$apply();
  435. }
  436. }
  437. repeatFns.push({
  438. nextTime:(now + delay),
  439. delay: delay,
  440. fn: tick,
  441. id: nextRepeatId,
  442. deferred: deferred
  443. });
  444. repeatFns.sort(function(a, b) { return a.nextTime - b.nextTime;});
  445. nextRepeatId++;
  446. return promise;
  447. };
  448. /**
  449. * @ngdoc method
  450. * @name $interval#cancel
  451. *
  452. * @description
  453. * Cancels a task associated with the `promise`.
  454. *
  455. * @param {promise} promise A promise from calling the `$interval` function.
  456. * @returns {boolean} Returns `true` if the task was successfully cancelled.
  457. */
  458. $interval.cancel = function(promise) {
  459. if (!promise) return false;
  460. var fnIndex;
  461. angular.forEach(repeatFns, function(fn, index) {
  462. if (fn.id === promise.$$intervalId) fnIndex = index;
  463. });
  464. if (angular.isDefined(fnIndex)) {
  465. repeatFns[fnIndex].deferred.reject('canceled');
  466. repeatFns.splice(fnIndex, 1);
  467. return true;
  468. }
  469. return false;
  470. };
  471. /**
  472. * @ngdoc method
  473. * @name $interval#flush
  474. * @description
  475. *
  476. * Runs interval tasks scheduled to be run in the next `millis` milliseconds.
  477. *
  478. * @param {number=} millis maximum timeout amount to flush up until.
  479. *
  480. * @return {number} The amount of time moved forward.
  481. */
  482. $interval.flush = function(millis) {
  483. now += millis;
  484. while (repeatFns.length && repeatFns[0].nextTime <= now) {
  485. var task = repeatFns[0];
  486. task.fn();
  487. task.nextTime += task.delay;
  488. repeatFns.sort(function(a, b) { return a.nextTime - b.nextTime;});
  489. }
  490. return millis;
  491. };
  492. return $interval;
  493. }];
  494. };
  495. /* jshint -W101 */
  496. /* The R_ISO8061_STR regex is never going to fit into the 100 char limit!
  497. * This directive should go inside the anonymous function but a bug in JSHint means that it would
  498. * not be enacted early enough to prevent the warning.
  499. */
  500. var R_ISO8061_STR = /^(-?\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?:\:?(\d\d)(?:\:?(\d\d)(?:\.(\d{3}))?)?)?(Z|([+-])(\d\d):?(\d\d)))?$/;
  501. function jsonStringToDate(string) {
  502. var match;
  503. if (match = string.match(R_ISO8061_STR)) {
  504. var date = new Date(0),
  505. tzHour = 0,
  506. tzMin = 0;
  507. if (match[9]) {
  508. tzHour = toInt(match[9] + match[10]);
  509. tzMin = toInt(match[9] + match[11]);
  510. }
  511. date.setUTCFullYear(toInt(match[1]), toInt(match[2]) - 1, toInt(match[3]));
  512. date.setUTCHours(toInt(match[4] || 0) - tzHour,
  513. toInt(match[5] || 0) - tzMin,
  514. toInt(match[6] || 0),
  515. toInt(match[7] || 0));
  516. return date;
  517. }
  518. return string;
  519. }
  520. function toInt(str) {
  521. return parseInt(str, 10);
  522. }
  523. function padNumberInMock(num, digits, trim) {
  524. var neg = '';
  525. if (num < 0) {
  526. neg = '-';
  527. num = -num;
  528. }
  529. num = '' + num;
  530. while (num.length < digits) num = '0' + num;
  531. if (trim) {
  532. num = num.substr(num.length - digits);
  533. }
  534. return neg + num;
  535. }
  536. /**
  537. * @ngdoc type
  538. * @name angular.mock.TzDate
  539. * @description
  540. *
  541. * *NOTE*: this is not an injectable instance, just a globally available mock class of `Date`.
  542. *
  543. * Mock of the Date type which has its timezone specified via constructor arg.
  544. *
  545. * The main purpose is to create Date-like instances with timezone fixed to the specified timezone
  546. * offset, so that we can test code that depends on local timezone settings without dependency on
  547. * the time zone settings of the machine where the code is running.
  548. *
  549. * @param {number} offset Offset of the *desired* timezone in hours (fractions will be honored)
  550. * @param {(number|string)} timestamp Timestamp representing the desired time in *UTC*
  551. *
  552. * @example
  553. * !!!! WARNING !!!!!
  554. * This is not a complete Date object so only methods that were implemented can be called safely.
  555. * To make matters worse, TzDate instances inherit stuff from Date via a prototype.
  556. *
  557. * We do our best to intercept calls to "unimplemented" methods, but since the list of methods is
  558. * incomplete we might be missing some non-standard methods. This can result in errors like:
  559. * "Date.prototype.foo called on incompatible Object".
  560. *
  561. * ```js
  562. * var newYearInBratislava = new TzDate(-1, '2009-12-31T23:00:00Z');
  563. * newYearInBratislava.getTimezoneOffset() => -60;
  564. * newYearInBratislava.getFullYear() => 2010;
  565. * newYearInBratislava.getMonth() => 0;
  566. * newYearInBratislava.getDate() => 1;
  567. * newYearInBratislava.getHours() => 0;
  568. * newYearInBratislava.getMinutes() => 0;
  569. * newYearInBratislava.getSeconds() => 0;
  570. * ```
  571. *
  572. */
  573. angular.mock.TzDate = function(offset, timestamp) {
  574. var self = new Date(0);
  575. if (angular.isString(timestamp)) {
  576. var tsStr = timestamp;
  577. self.origDate = jsonStringToDate(timestamp);
  578. timestamp = self.origDate.getTime();
  579. if (isNaN(timestamp)) {
  580. throw {
  581. name: "Illegal Argument",
  582. message: "Arg '" + tsStr + "' passed into TzDate constructor is not a valid date string"
  583. };
  584. }
  585. } else {
  586. self.origDate = new Date(timestamp);
  587. }
  588. var localOffset = new Date(timestamp).getTimezoneOffset();
  589. self.offsetDiff = localOffset * 60 * 1000 - offset * 1000 * 60 * 60;
  590. self.date = new Date(timestamp + self.offsetDiff);
  591. self.getTime = function() {
  592. return self.date.getTime() - self.offsetDiff;
  593. };
  594. self.toLocaleDateString = function() {
  595. return self.date.toLocaleDateString();
  596. };
  597. self.getFullYear = function() {
  598. return self.date.getFullYear();
  599. };
  600. self.getMonth = function() {
  601. return self.date.getMonth();
  602. };
  603. self.getDate = function() {
  604. return self.date.getDate();
  605. };
  606. self.getHours = function() {
  607. return self.date.getHours();
  608. };
  609. self.getMinutes = function() {
  610. return self.date.getMinutes();
  611. };
  612. self.getSeconds = function() {
  613. return self.date.getSeconds();
  614. };
  615. self.getMilliseconds = function() {
  616. return self.date.getMilliseconds();
  617. };
  618. self.getTimezoneOffset = function() {
  619. return offset * 60;
  620. };
  621. self.getUTCFullYear = function() {
  622. return self.origDate.getUTCFullYear();
  623. };
  624. self.getUTCMonth = function() {
  625. return self.origDate.getUTCMonth();
  626. };
  627. self.getUTCDate = function() {
  628. return self.origDate.getUTCDate();
  629. };
  630. self.getUTCHours = function() {
  631. return self.origDate.getUTCHours();
  632. };
  633. self.getUTCMinutes = function() {
  634. return self.origDate.getUTCMinutes();
  635. };
  636. self.getUTCSeconds = function() {
  637. return self.origDate.getUTCSeconds();
  638. };
  639. self.getUTCMilliseconds = function() {
  640. return self.origDate.getUTCMilliseconds();
  641. };
  642. self.getDay = function() {
  643. return self.date.getDay();
  644. };
  645. // provide this method only on browsers that already have it
  646. if (self.toISOString) {
  647. self.toISOString = function() {
  648. return padNumberInMock(self.origDate.getUTCFullYear(), 4) + '-' +
  649. padNumberInMock(self.origDate.getUTCMonth() + 1, 2) + '-' +
  650. padNumberInMock(self.origDate.getUTCDate(), 2) + 'T' +
  651. padNumberInMock(self.origDate.getUTCHours(), 2) + ':' +
  652. padNumberInMock(self.origDate.getUTCMinutes(), 2) + ':' +
  653. padNumberInMock(self.origDate.getUTCSeconds(), 2) + '.' +
  654. padNumberInMock(self.origDate.getUTCMilliseconds(), 3) + 'Z';
  655. };
  656. }
  657. //hide all methods not implemented in this mock that the Date prototype exposes
  658. var unimplementedMethods = ['getUTCDay',
  659. 'getYear', 'setDate', 'setFullYear', 'setHours', 'setMilliseconds',
  660. 'setMinutes', 'setMonth', 'setSeconds', 'setTime', 'setUTCDate', 'setUTCFullYear',
  661. 'setUTCHours', 'setUTCMilliseconds', 'setUTCMinutes', 'setUTCMonth', 'setUTCSeconds',
  662. 'setYear', 'toDateString', 'toGMTString', 'toJSON', 'toLocaleFormat', 'toLocaleString',
  663. 'toLocaleTimeString', 'toSource', 'toString', 'toTimeString', 'toUTCString', 'valueOf'];
  664. angular.forEach(unimplementedMethods, function(methodName) {
  665. self[methodName] = function() {
  666. throw new Error("Method '" + methodName + "' is not implemented in the TzDate mock");
  667. };
  668. });
  669. return self;
  670. };
  671. //make "tzDateInstance instanceof Date" return true
  672. angular.mock.TzDate.prototype = Date.prototype;
  673. /* jshint +W101 */
  674. /**
  675. * @ngdoc service
  676. * @name $animate
  677. *
  678. * @description
  679. * Mock implementation of the {@link ng.$animate `$animate`} service. Exposes two additional methods
  680. * for testing animations.
  681. *
  682. * You need to require the `ngAnimateMock` module in your test suite for instance `beforeEach(module('ngAnimateMock'))`
  683. */
  684. angular.mock.animate = angular.module('ngAnimateMock', ['ng'])
  685. .config(['$provide', function($provide) {
  686. $provide.factory('$$forceReflow', function() {
  687. function reflowFn() {
  688. reflowFn.totalReflows++;
  689. }
  690. reflowFn.totalReflows = 0;
  691. return reflowFn;
  692. });
  693. $provide.factory('$$animateAsyncRun', function() {
  694. var queue = [];
  695. var queueFn = function() {
  696. return function(fn) {
  697. queue.push(fn);
  698. };
  699. };
  700. queueFn.flush = function() {
  701. if (queue.length === 0) return false;
  702. for (var i = 0; i < queue.length; i++) {
  703. queue[i]();
  704. }
  705. queue = [];
  706. return true;
  707. };
  708. return queueFn;
  709. });
  710. $provide.decorator('$$animateJs', ['$delegate', function($delegate) {
  711. var runners = [];
  712. var animateJsConstructor = function() {
  713. var animator = $delegate.apply($delegate, arguments);
  714. // If no javascript animation is found, animator is undefined
  715. if (animator) {
  716. runners.push(animator);
  717. }
  718. return animator;
  719. };
  720. animateJsConstructor.$closeAndFlush = function() {
  721. runners.forEach(function(runner) {
  722. runner.end();
  723. });
  724. runners = [];
  725. };
  726. return animateJsConstructor;
  727. }]);
  728. $provide.decorator('$animateCss', ['$delegate', function($delegate) {
  729. var runners = [];
  730. var animateCssConstructor = function(element, options) {
  731. var animator = $delegate(element, options);
  732. runners.push(animator);
  733. return animator;
  734. };
  735. animateCssConstructor.$closeAndFlush = function() {
  736. runners.forEach(function(runner) {
  737. runner.end();
  738. });
  739. runners = [];
  740. };
  741. return animateCssConstructor;
  742. }]);
  743. $provide.decorator('$animate', ['$delegate', '$timeout', '$browser', '$$rAF', '$animateCss', '$$animateJs',
  744. '$$forceReflow', '$$animateAsyncRun', '$rootScope',
  745. function($delegate, $timeout, $browser, $$rAF, $animateCss, $$animateJs,
  746. $$forceReflow, $$animateAsyncRun, $rootScope) {
  747. var animate = {
  748. queue: [],
  749. cancel: $delegate.cancel,
  750. on: $delegate.on,
  751. off: $delegate.off,
  752. pin: $delegate.pin,
  753. get reflows() {
  754. return $$forceReflow.totalReflows;
  755. },
  756. enabled: $delegate.enabled,
  757. /**
  758. * @ngdoc method
  759. * @name $animate#closeAndFlush
  760. * @description
  761. *
  762. * This method will close all pending animations (both {@link ngAnimate#javascript-based-animations Javascript}
  763. * and {@link ngAnimate.$animateCss CSS}) and it will also flush any remaining animation frames and/or callbacks.
  764. */
  765. closeAndFlush: function() {
  766. // we allow the flush command to swallow the errors
  767. // because depending on whether CSS or JS animations are
  768. // used, there may not be a RAF flush. The primary flush
  769. // at the end of this function must throw an exception
  770. // because it will track if there were pending animations
  771. this.flush(true);
  772. $animateCss.$closeAndFlush();
  773. $$animateJs.$closeAndFlush();
  774. this.flush();
  775. },
  776. /**
  777. * @ngdoc method
  778. * @name $animate#flush
  779. * @description
  780. *
  781. * This method is used to flush the pending callbacks and animation frames to either start
  782. * an animation or conclude an animation. Note that this will not actually close an
  783. * actively running animation (see {@link ngMock.$animate#closeAndFlush `closeAndFlush()`} for that).
  784. */
  785. flush: function(hideErrors) {
  786. $rootScope.$digest();
  787. var doNextRun, somethingFlushed = false;
  788. do {
  789. doNextRun = false;
  790. if ($$rAF.queue.length) {
  791. $$rAF.flush();
  792. doNextRun = somethingFlushed = true;
  793. }
  794. if ($$animateAsyncRun.flush()) {
  795. doNextRun = somethingFlushed = true;
  796. }
  797. } while (doNextRun);
  798. if (!somethingFlushed && !hideErrors) {
  799. throw new Error('No pending animations ready to be closed or flushed');
  800. }
  801. $rootScope.$digest();
  802. }
  803. };
  804. angular.forEach(
  805. ['animate','enter','leave','move','addClass','removeClass','setClass'], function(method) {
  806. animate[method] = function() {
  807. animate.queue.push({
  808. event: method,
  809. element: arguments[0],
  810. options: arguments[arguments.length - 1],
  811. args: arguments
  812. });
  813. return $delegate[method].apply($delegate, arguments);
  814. };
  815. });
  816. return animate;
  817. }]);
  818. }]);
  819. /**
  820. * @ngdoc function
  821. * @name angular.mock.dump
  822. * @description
  823. *
  824. * *NOTE*: This is not an injectable instance, just a globally available function.
  825. *
  826. * Method for serializing common angular objects (scope, elements, etc..) into strings.
  827. * It is useful for logging objects to the console when debugging.
  828. *
  829. * @param {*} object - any object to turn into string.
  830. * @return {string} a serialized string of the argument
  831. */
  832. angular.mock.dump = function(object) {
  833. return serialize(object);
  834. function serialize(object) {
  835. var out;
  836. if (angular.isElement(object)) {
  837. object = angular.element(object);
  838. out = angular.element('<div></div>');
  839. angular.forEach(object, function(element) {
  840. out.append(angular.element(element).clone());
  841. });
  842. out = out.html();
  843. } else if (angular.isArray(object)) {
  844. out = [];
  845. angular.forEach(object, function(o) {
  846. out.push(serialize(o));
  847. });
  848. out = '[ ' + out.join(', ') + ' ]';
  849. } else if (angular.isObject(object)) {
  850. if (angular.isFunction(object.$eval) && angular.isFunction(object.$apply)) {
  851. out = serializeScope(object);
  852. } else if (object instanceof Error) {
  853. out = object.stack || ('' + object.name + ': ' + object.message);
  854. } else {
  855. // TODO(i): this prevents methods being logged,
  856. // we should have a better way to serialize objects
  857. out = angular.toJson(object, true);
  858. }
  859. } else {
  860. out = String(object);
  861. }
  862. return out;
  863. }
  864. function serializeScope(scope, offset) {
  865. offset = offset || ' ';
  866. var log = [offset + 'Scope(' + scope.$id + '): {'];
  867. for (var key in scope) {
  868. if (Object.prototype.hasOwnProperty.call(scope, key) && !key.match(/^(\$|this)/)) {
  869. log.push(' ' + key + ': ' + angular.toJson(scope[key]));
  870. }
  871. }
  872. var child = scope.$$childHead;
  873. while (child) {
  874. log.push(serializeScope(child, offset + ' '));
  875. child = child.$$nextSibling;
  876. }
  877. log.push('}');
  878. return log.join('\n' + offset);
  879. }
  880. };
  881. /**
  882. * @ngdoc service
  883. * @name $httpBackend
  884. * @description
  885. * Fake HTTP backend implementation suitable for unit testing applications that use the
  886. * {@link ng.$http $http service}.
  887. *
  888. * <div class="alert alert-info">
  889. * **Note**: For fake HTTP backend implementation suitable for end-to-end testing or backend-less
  890. * development please see {@link ngMockE2E.$httpBackend e2e $httpBackend mock}.
  891. * </div>
  892. *
  893. * During unit testing, we want our unit tests to run quickly and have no external dependencies so
  894. * we don’t want to send [XHR](https://developer.mozilla.org/en/xmlhttprequest) or
  895. * [JSONP](http://en.wikipedia.org/wiki/JSONP) requests to a real server. All we really need is
  896. * to verify whether a certain request has been sent or not, or alternatively just let the
  897. * application make requests, respond with pre-trained responses and assert that the end result is
  898. * what we expect it to be.
  899. *
  900. * This mock implementation can be used to respond with static or dynamic responses via the
  901. * `expect` and `when` apis and their shortcuts (`expectGET`, `whenPOST`, etc).
  902. *
  903. * When an Angular application needs some data from a server, it calls the $http service, which
  904. * sends the request to a real server using $httpBackend service. With dependency injection, it is
  905. * easy to inject $httpBackend mock (which has the same API as $httpBackend) and use it to verify
  906. * the requests and respond with some testing data without sending a request to a real server.
  907. *
  908. * There are two ways to specify what test data should be returned as http responses by the mock
  909. * backend when the code under test makes http requests:
  910. *
  911. * - `$httpBackend.expect` - specifies a request expectation
  912. * - `$httpBackend.when` - specifies a backend definition
  913. *
  914. *
  915. * ## Request Expectations vs Backend Definitions
  916. *
  917. * Request expectations provide a way to make assertions about requests made by the application and
  918. * to define responses for those requests. The test will fail if the expected requests are not made
  919. * or they are made in the wrong order.
  920. *
  921. * Backend definitions allow you to define a fake backend for your application which doesn't assert
  922. * if a particular request was made or not, it just returns a trained response if a request is made.
  923. * The test will pass whether or not the request gets made during testing.
  924. *
  925. *
  926. * <table class="table">
  927. * <tr><th width="220px"></th><th>Request expectations</th><th>Backend definitions</th></tr>
  928. * <tr>
  929. * <th>Syntax</th>
  930. * <td>.expect(...).respond(...)</td>
  931. * <td>.when(...).respond(...)</td>
  932. * </tr>
  933. * <tr>
  934. * <th>Typical usage</th>
  935. * <td>strict unit tests</td>
  936. * <td>loose (black-box) unit testing</td>
  937. * </tr>
  938. * <tr>
  939. * <th>Fulfills multiple requests</th>
  940. * <td>NO</td>
  941. * <td>YES</td>
  942. * </tr>
  943. * <tr>
  944. * <th>Order of requests matters</th>
  945. * <td>YES</td>
  946. * <td>NO</td>
  947. * </tr>
  948. * <tr>
  949. * <th>Request required</th>
  950. * <td>YES</td>
  951. * <td>NO</td>
  952. * </tr>
  953. * <tr>
  954. * <th>Response required</th>
  955. * <td>optional (see below)</td>
  956. * <td>YES</td>
  957. * </tr>
  958. * </table>
  959. *
  960. * In cases where both backend definitions and request expectations are specified during unit
  961. * testing, the request expectations are evaluated first.
  962. *
  963. * If a request expectation has no response specified, the algorithm will search your backend
  964. * definitions for an appropriate response.
  965. *
  966. * If a request didn't match any expectation or if the expectation doesn't have the response
  967. * defined, the backend definitions are evaluated in sequential order to see if any of them match
  968. * the request. The response from the first matched definition is returned.
  969. *
  970. *
  971. * ## Flushing HTTP requests
  972. *
  973. * The $httpBackend used in production always responds to requests asynchronously. If we preserved
  974. * this behavior in unit testing, we'd have to create async unit tests, which are hard to write,
  975. * to follow and to maintain. But neither can the testing mock respond synchronously; that would
  976. * change the execution of the code under test. For this reason, the mock $httpBackend has a
  977. * `flush()` method, which allows the test to explicitly flush pending requests. This preserves
  978. * the async api of the backend, while allowing the test to execute synchronously.
  979. *
  980. *
  981. * ## Unit testing with mock $httpBackend
  982. * The following code shows how to setup and use the mock backend when unit testing a controller.
  983. * First we create the controller under test:
  984. *
  985. ```js
  986. // The module code
  987. angular
  988. .module('MyApp', [])
  989. .controller('MyController', MyController);
  990. // The controller code
  991. function MyController($scope, $http) {
  992. var authToken;
  993. $http.get('/auth.py').then(function(response) {
  994. authToken = response.headers('A-Token');
  995. $scope.user = response.data;
  996. });
  997. $scope.saveMessage = function(message) {
  998. var headers = { 'Authorization': authToken };
  999. $scope.status = 'Saving...';
  1000. $http.post('/add-msg.py', message, { headers: headers } ).then(function(response) {
  1001. $scope.status = '';
  1002. }).catch(function() {
  1003. $scope.status = 'Failed...';
  1004. });
  1005. };
  1006. }
  1007. ```
  1008. *
  1009. * Now we setup the mock backend and create the test specs:
  1010. *
  1011. ```js
  1012. // testing controller
  1013. describe('MyController', function() {
  1014. var $httpBackend, $rootScope, createController, authRequestHandler;
  1015. // Set up the module
  1016. beforeEach(module('MyApp'));
  1017. beforeEach(inject(function($injector) {
  1018. // Set up the mock http service responses
  1019. $httpBackend = $injector.get('$httpBackend');
  1020. // backend definition common for all tests
  1021. authRequestHandler = $httpBackend.when('GET', '/auth.py')
  1022. .respond({userId: 'userX'}, {'A-Token': 'xxx'});
  1023. // Get hold of a scope (i.e. the root scope)
  1024. $rootScope = $injector.get('$rootScope');
  1025. // The $controller service is used to create instances of controllers
  1026. var $controller = $injector.get('$controller');
  1027. createController = function() {
  1028. return $controller('MyController', {'$scope' : $rootScope });
  1029. };
  1030. }));
  1031. afterEach(function() {
  1032. $httpBackend.verifyNoOutstandingExpectation();
  1033. $httpBackend.verifyNoOutstandingRequest();
  1034. });
  1035. it('should fetch authentication token', function() {
  1036. $httpBackend.expectGET('/auth.py');
  1037. var controller = createController();
  1038. $httpBackend.flush();
  1039. });
  1040. it('should fail authentication', function() {
  1041. // Notice how you can change the response even after it was set
  1042. authRequestHandler.respond(401, '');
  1043. $httpBackend.expectGET('/auth.py');
  1044. var controller = createController();
  1045. $httpBackend.flush();
  1046. expect($rootScope.status).toBe('Failed...');
  1047. });
  1048. it('should send msg to server', function() {
  1049. var controller = createController();
  1050. $httpBackend.flush();
  1051. // now you don’t care about the authentication, but
  1052. // the controller will still send the request and
  1053. // $httpBackend will respond without you having to
  1054. // specify the expectation and response for this request
  1055. $httpBackend.expectPOST('/add-msg.py', 'message content').respond(201, '');
  1056. $rootScope.saveMessage('message content');
  1057. expect($rootScope.status).toBe('Saving...');
  1058. $httpBackend.flush();
  1059. expect($rootScope.status).toBe('');
  1060. });
  1061. it('should send auth header', function() {
  1062. var controller = createController();
  1063. $httpBackend.flush();
  1064. $httpBackend.expectPOST('/add-msg.py', undefined, function(headers) {
  1065. // check if the header was sent, if it wasn't the expectation won't
  1066. // match the request and the test will fail
  1067. return headers['Authorization'] == 'xxx';
  1068. }).respond(201, '');
  1069. $rootScope.saveMessage('whatever');
  1070. $httpBackend.flush();
  1071. });
  1072. });
  1073. ```
  1074. *
  1075. * ## Dynamic responses
  1076. *
  1077. * You define a response to a request by chaining a call to `respond()` onto a definition or expectation.
  1078. * If you provide a **callback** as the first parameter to `respond(callback)` then you can dynamically generate
  1079. * a response based on the properties of the request.
  1080. *
  1081. * The `callback` function should be of the form `function(method, url, data, headers, params)`.
  1082. *
  1083. * ### Query parameters
  1084. *
  1085. * By default, query parameters on request URLs are parsed into the `params` object. So a request URL
  1086. * of `/list?q=searchstr&orderby=-name` would set `params` to be `{q: 'searchstr', orderby: '-name'}`.
  1087. *
  1088. * ### Regex parameter matching
  1089. *
  1090. * If an expectation or definition uses a **regex** to match the URL, you can provide an array of **keys** via a
  1091. * `params` argument. The index of each **key** in the array will match the index of a **group** in the
  1092. * **regex**.
  1093. *
  1094. * The `params` object in the **callback** will now have properties with these keys, which hold the value of the
  1095. * corresponding **group** in the **regex**.
  1096. *
  1097. * This also applies to the `when` and `expect` shortcut methods.
  1098. *
  1099. *
  1100. * ```js
  1101. * $httpBackend.expect('GET', /\/user\/(.+)/, undefined, undefined, ['id'])
  1102. * .respond(function(method, url, data, headers, params) {
  1103. * // for requested url of '/user/1234' params is {id: '1234'}
  1104. * });
  1105. *
  1106. * $httpBackend.whenPATCH(/\/user\/(.+)\/article\/(.+)/, undefined, undefined, ['user', 'article'])
  1107. * .respond(function(method, url, data, headers, params) {
  1108. * // for url of '/user/1234/article/567' params is {user: '1234', article: '567'}
  1109. * });
  1110. * ```
  1111. *
  1112. * ## Matching route requests
  1113. *
  1114. * For extra convenience, `whenRoute` and `expectRoute` shortcuts are available. These methods offer colon
  1115. * delimited matching of the url path, ignoring the query string. This allows declarations
  1116. * similar to how application routes are configured with `$routeProvider`. Because these methods convert
  1117. * the definition url to regex, declaration order is important. Combined with query parameter parsing,
  1118. * the following is possible:
  1119. *
  1120. ```js
  1121. $httpBackend.whenRoute('GET', '/users/:id')
  1122. .respond(function(method, url, data, headers, params) {
  1123. return [200, MockUserList[Number(params.id)]];
  1124. });
  1125. $httpBackend.whenRoute('GET', '/users')
  1126. .respond(function(method, url, data, headers, params) {
  1127. var userList = angular.copy(MockUserList),
  1128. defaultSort = 'lastName',
  1129. count, pages, isPrevious, isNext;
  1130. // paged api response '/v1/users?page=2'
  1131. params.page = Number(params.page) || 1;
  1132. // query for last names '/v1/users?q=Archer'
  1133. if (params.q) {
  1134. userList = $filter('filter')({lastName: params.q});
  1135. }
  1136. pages = Math.ceil(userList.length / pagingLength);
  1137. isPrevious = params.page > 1;
  1138. isNext = params.page < pages;
  1139. return [200, {
  1140. count: userList.length,
  1141. previous: isPrevious,
  1142. next: isNext,
  1143. // sort field -> '/v1/users?sortBy=firstName'
  1144. results: $filter('orderBy')(userList, params.sortBy || defaultSort)
  1145. .splice((params.page - 1) * pagingLength, pagingLength)
  1146. }];
  1147. });
  1148. ```
  1149. */
  1150. angular.mock.$HttpBackendProvider = function() {
  1151. this.$get = ['$rootScope', '$timeout', createHttpBackendMock];
  1152. };
  1153. /**
  1154. * General factory function for $httpBackend mock.
  1155. * Returns instance for unit testing (when no arguments specified):
  1156. * - passing through is disabled
  1157. * - auto flushing is disabled
  1158. *
  1159. * Returns instance for e2e testing (when `$delegate` and `$browser` specified):
  1160. * - passing through (delegating request to real backend) is enabled
  1161. * - auto flushing is enabled
  1162. *
  1163. * @param {Object=} $delegate Real $httpBackend instance (allow passing through if specified)
  1164. * @param {Object=} $browser Auto-flushing enabled if specified
  1165. * @return {Object} Instance of $httpBackend mock
  1166. */
  1167. function createHttpBackendMock($rootScope, $timeout, $delegate, $browser) {
  1168. var definitions = [],
  1169. expectations = [],
  1170. responses = [],
  1171. responsesPush = angular.bind(responses, responses.push),
  1172. copy = angular.copy;
  1173. function createResponse(status, data, headers, statusText) {
  1174. if (angular.isFunction(status)) return status;
  1175. return function() {
  1176. return angular.isNumber(status)
  1177. ? [status, data, headers, statusText]
  1178. : [200, status, data, headers];
  1179. };
  1180. }
  1181. // TODO(vojta): change params to: method, url, data, headers, callback
  1182. function $httpBackend(method, url, data, callback, headers, timeout, withCredentials, responseType, eventHandlers, uploadEventHandlers) {
  1183. var xhr = new MockXhr(),
  1184. expectation = expectations[0],
  1185. wasExpected = false;
  1186. xhr.$$events = eventHandlers;
  1187. xhr.upload.$$events = uploadEventHandlers;
  1188. function prettyPrint(data) {
  1189. return (angular.isString(data) || angular.isFunction(data) || data instanceof RegExp)
  1190. ? data
  1191. : angular.toJson(data);
  1192. }
  1193. function wrapResponse(wrapped) {
  1194. if (!$browser && timeout) {
  1195. timeout.then ? timeout.then(handleTimeout) : $timeout(handleTimeout, timeout);
  1196. }
  1197. return handleResponse;
  1198. function handleResponse() {
  1199. var response = wrapped.response(method, url, data, headers, wrapped.params(url));
  1200. xhr.$$respHeaders = response[2];
  1201. callback(copy(response[0]), copy(response[1]), xhr.getAllResponseHeaders(),
  1202. copy(response[3] || ''));
  1203. }
  1204. function handleTimeout() {
  1205. for (var i = 0, ii = responses.length; i < ii; i++) {
  1206. if (responses[i] === handleResponse) {
  1207. responses.splice(i, 1);
  1208. callback(-1, undefined, '');
  1209. break;
  1210. }
  1211. }
  1212. }
  1213. }
  1214. if (expectation && expectation.match(method, url)) {
  1215. if (!expectation.matchData(data)) {
  1216. throw new Error('Expected ' + expectation + ' with different data\n' +
  1217. 'EXPECTED: ' + prettyPrint(expectation.data) + '\nGOT: ' + data);
  1218. }
  1219. if (!expectation.matchHeaders(headers)) {
  1220. throw new Error('Expected ' + expectation + ' with different headers\n' +
  1221. 'EXPECTED: ' + prettyPrint(expectation.headers) + '\nGOT: ' +
  1222. prettyPrint(headers));
  1223. }
  1224. expectations.shift();
  1225. if (expectation.response) {
  1226. responses.push(wrapResponse(expectation));
  1227. return;
  1228. }
  1229. wasExpected = true;
  1230. }
  1231. var i = -1, definition;
  1232. while ((definition = definitions[++i])) {
  1233. if (definition.match(method, url, data, headers || {})) {
  1234. if (definition.response) {
  1235. // if $browser specified, we do auto flush all requests
  1236. ($browser ? $browser.defer : responsesPush)(wrapResponse(definition));
  1237. } else if (definition.passThrough) {
  1238. $delegate(method, url, data, callback, headers, timeout, withCredentials, responseType, eventHandlers, uploadEventHandlers);
  1239. } else throw new Error('No response defined !');
  1240. return;
  1241. }
  1242. }
  1243. throw wasExpected ?
  1244. new Error('No response defined !') :
  1245. new Error('Unexpected request: ' + method + ' ' + url + '\n' +
  1246. (expectation ? 'Expected ' + expectation : 'No more request expected'));
  1247. }
  1248. /**
  1249. * @ngdoc method
  1250. * @name $httpBackend#when
  1251. * @description
  1252. * Creates a new backend definition.
  1253. *
  1254. * @param {string} method HTTP method.
  1255. * @param {string|RegExp|function(string)} url HTTP url or function that receives a url
  1256. * and returns true if the url matches the current definition.
  1257. * @param {(string|RegExp|function(string))=} data HTTP request body or function that receives
  1258. * data string and returns true if the data is as expected.
  1259. * @param {(Object|function(Object))=} headers HTTP headers or function that receives http header
  1260. * object and returns true if the headers match the current definition.
  1261. * @param {(Array)=} keys Array of keys to assign to regex matches in request url described above.
  1262. * @returns {requestHandler} Returns an object with `respond` method that controls 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. * - respond –
  1267. * ```js
  1268. * {function([status,] data[, headers, statusText])
  1269. * | function(function(method, url, data, headers, params)}
  1270. * ```
  1271. * – The respond method takes a set of static data to be returned or a function that can
  1272. * return an array containing response status (number), response data (Array|Object|string),
  1273. * response headers (Object), and the text for the status (string). The respond method returns
  1274. * the `requestHandler` object for possible overrides.
  1275. */
  1276. $httpBackend.when = function(method, url, data, headers, keys) {
  1277. var definition = new MockHttpExpectation(method, url, data, headers, keys),
  1278. chain = {
  1279. respond: function(status, data, headers, statusText) {
  1280. definition.passThrough = undefined;
  1281. definition.response = createResponse(status, data, headers, statusText);
  1282. return chain;
  1283. }
  1284. };
  1285. if ($browser) {
  1286. chain.passThrough = function() {
  1287. definition.response = undefined;
  1288. definition.passThrough = true;
  1289. return chain;
  1290. };
  1291. }
  1292. definitions.push(definition);
  1293. return chain;
  1294. };
  1295. /**
  1296. * @ngdoc method
  1297. * @name $httpBackend#whenGET
  1298. * @description
  1299. * Creates a new backend definition for GET requests. For more info see `when()`.
  1300. *
  1301. * @param {string|RegExp|function(string)} url HTTP url or function that receives a url
  1302. * and returns true if the url matches the current definition.
  1303. * @param {(Object|function(Object))=} headers HTTP headers.
  1304. * @param {(Array)=} keys Array of keys to assign to regex matches in request url described above.
  1305. * @returns {requestHandler} Returns an object with `respond` method that controls how a matched
  1306. * request is handled. You can save this object for later use and invoke `respond` again in
  1307. * order to change how a matched request is handled.
  1308. */
  1309. /**
  1310. * @ngdoc method
  1311. * @name $httpBackend#whenHEAD
  1312. * @description
  1313. * Creates a new backend definition for HEAD requests. For more info see `when()`.
  1314. *
  1315. * @param {string|RegExp|function(string)} url HTTP url or function that receives a url
  1316. * and returns true if the url matches the current definition.
  1317. * @param {(Object|function(Object))=} headers HTTP headers.
  1318. * @param {(Array)=} keys Array of keys to assign to regex matches in request url described above.
  1319. * @returns {requestHandler} Returns an object with `respond` method that controls how a matched
  1320. * request is handled. You can save this object for later use and invoke `respond` again in
  1321. * order to change how a matched request is handled.
  1322. */
  1323. /**
  1324. * @ngdoc method
  1325. * @name $httpBackend#whenDELETE
  1326. * @description
  1327. * Creates a new backend definition for DELETE requests. For more info see `when()`.
  1328. *
  1329. * @param {string|RegExp|function(string)} url HTTP url or function that receives a url
  1330. * and returns true if the url matches the current definition.
  1331. * @param {(Object|function(Object))=} headers HTTP headers.
  1332. * @param {(Array)=} keys Array of keys to assign to regex matches in request url described above.
  1333. * @returns {requestHandler} Returns an object with `respond` method that controls how a matched
  1334. * request is handled. You can save this object for later use and invoke `respond` again in
  1335. * order to change how a matched request is handled.
  1336. */
  1337. /**
  1338. * @ngdoc method
  1339. * @name $httpBackend#whenPOST
  1340. * @description
  1341. * Creates a new backend definition for POST requests. For more info see `when()`.
  1342. *
  1343. * @param {string|RegExp|function(string)} url HTTP url or function that receives a url
  1344. * and returns true if the url matches the current definition.
  1345. * @param {(string|RegExp|function(string))=} data HTTP request body or function that receives
  1346. * data string and returns true if the data is as expected.
  1347. * @param {(Object|function(Object))=} headers HTTP headers.
  1348. * @param {(Array)=} keys Array of keys to assign to regex matches in request url described above.
  1349. * @returns {requestHandler} Returns an object with `respond` method that controls how a matched
  1350. * request is handled. You can save this object for later use and invoke `respond` again in
  1351. * order to change how a matched request is handled.
  1352. */
  1353. /**
  1354. * @ngdoc method
  1355. * @name $httpBackend#whenPUT
  1356. * @description
  1357. * Creates a new backend definition for PUT requests. For more info see `when()`.
  1358. *
  1359. * @param {string|RegExp|function(string)} url HTTP url or function that receives a url
  1360. * and returns true if the url matches the current definition.
  1361. * @param {(string|RegExp|function(string))=} data HTTP request body or function that receives
  1362. * data string and returns true if the data is as expected.
  1363. * @param {(Object|function(Object))=} headers HTTP headers.
  1364. * @param {(Array)=} keys Array of keys to assign to regex matches in request url described above.
  1365. * @returns {requestHandler} Returns an object with `respond` method that controls how a matched
  1366. * request is handled. You can save this object for later use and invoke `respond` again in
  1367. * order to change how a matched request is handled.
  1368. */
  1369. /**
  1370. * @ngdoc method
  1371. * @name $httpBackend#whenJSONP
  1372. * @description
  1373. * Creates a new backend definition for JSONP requests. For more info see `when()`.
  1374. *
  1375. * @param {string|RegExp|function(string)} url HTTP url or function that receives a url
  1376. * and returns true if the url matches the current definition.
  1377. * @param {(Array)=} keys Array of keys to assign to regex matches in request url described above.
  1378. * @returns {requestHandler} Returns an object with `respond` method that controls how a matched
  1379. * request is handled. You can save this object for later use and invoke `respond` again in
  1380. * order to change how a matched request is handled.
  1381. */
  1382. createShortMethods('when');
  1383. /**
  1384. * @ngdoc method
  1385. * @name $httpBackend#whenRoute
  1386. * @description
  1387. * Creates a new backend definition that compares only with the requested route.
  1388. *
  1389. * @param {string} method HTTP method.
  1390. * @param {string} url HTTP url string that supports colon param matching.
  1391. * @returns {requestHandler} Returns an object with `respond` method that controls how a matched
  1392. * request is handled. You can save this object for later use and invoke `respond` again in
  1393. * order to change how a matched request is handled. See #when for more info.
  1394. */
  1395. $httpBackend.whenRoute = function(method, url) {
  1396. var pathObj = parseRoute(url);
  1397. return $httpBackend.when(method, pathObj.regexp, undefined, undefined, pathObj.keys);
  1398. };
  1399. function parseRoute(url) {
  1400. var ret = {
  1401. regexp: url
  1402. },
  1403. keys = ret.keys = [];
  1404. if (!url || !angular.isString(url)) return ret;
  1405. url = url
  1406. .replace(/([().])/g, '\\$1')
  1407. .replace(/(\/)?:(\w+)([\?\*])?/g, function(_, slash, key, option) {
  1408. var optional = option === '?' ? option : null;
  1409. var star = option === '*' ? option : null;
  1410. keys.push({ name: key, optional: !!optional });
  1411. slash = slash || '';
  1412. return ''
  1413. + (optional ? '' : slash)
  1414. + '(?:'
  1415. + (optional ? slash : '')
  1416. + (star && '(.+?)' || '([^/]+)')
  1417. + (optional || '')
  1418. + ')'
  1419. + (optional || '');
  1420. })
  1421. .replace(/([\/$\*])/g, '\\$1');
  1422. ret.regexp = new RegExp('^' + url, 'i');
  1423. return ret;
  1424. }
  1425. /**
  1426. * @ngdoc method
  1427. * @name $httpBackend#expect
  1428. * @description
  1429. * Creates a new request expectation.
  1430. *
  1431. * @param {string} method HTTP method.
  1432. * @param {string|RegExp|function(string)} url HTTP url or function that receives a url
  1433. * and returns true if the url matches the current definition.
  1434. * @param {(string|RegExp|function(string)|Object)=} data HTTP request body or function that
  1435. * receives data string and returns true if the data is as expected, or Object if request body
  1436. * is in JSON format.
  1437. * @param {(Object|function(Object))=} headers HTTP headers or function that receives http header
  1438. * object and returns true if the headers match the current expectation.
  1439. * @param {(Array)=} keys Array of keys to assign to regex matches in request url described above.
  1440. * @returns {requestHandler} Returns an object with `respond` method that controls how a matched
  1441. * request is handled. You can save this object for later use and invoke `respond` again in
  1442. * order to change how a matched request is handled.
  1443. *
  1444. * - respond –
  1445. * ```
  1446. * { function([status,] data[, headers, statusText])
  1447. * | function(function(method, url, data, headers, params)}
  1448. * ```
  1449. * – The respond method takes a set of static data to be returned or a function that can
  1450. * return an array containing response status (number), response data (Array|Object|string),
  1451. * response headers (Object), and the text for the status (string). The respond method returns
  1452. * the `requestHandler` object for possible overrides.
  1453. */
  1454. $httpBackend.expect = function(method, url, data, headers, keys) {
  1455. var expectation = new MockHttpExpectation(method, url, data, headers, keys),
  1456. chain = {
  1457. respond: function(status, data, headers, statusText) {
  1458. expectation.response = createResponse(status, data, headers, statusText);
  1459. return chain;
  1460. }
  1461. };
  1462. expectations.push(expectation);
  1463. return chain;
  1464. };
  1465. /**
  1466. * @ngdoc method
  1467. * @name $httpBackend#expectGET
  1468. * @description
  1469. * Creates a new request expectation for GET requests. For more info see `expect()`.
  1470. *
  1471. * @param {string|RegExp|function(string)} url HTTP url or function that receives a url
  1472. * and returns true if the url matches the current definition.
  1473. * @param {Object=} headers HTTP headers.
  1474. * @param {(Array)=} keys Array of keys to assign to regex matches in request url described above.
  1475. * @returns {requestHandler} Returns an object with `respond` method that controls how a matched
  1476. * request is handled. You can save this object for later use and invoke `respond` again in
  1477. * order to change how a matched request is handled. See #expect for more info.
  1478. */
  1479. /**
  1480. * @ngdoc method
  1481. * @name $httpBackend#expectHEAD
  1482. * @description
  1483. * Creates a new request expectation for HEAD requests. For more info see `expect()`.
  1484. *
  1485. * @param {string|RegExp|function(string)} url HTTP url or function that receives a url
  1486. * and returns true if the url matches the current definition.
  1487. * @param {Object=} headers HTTP headers.
  1488. * @param {(Array)=} keys Array of keys to assign to regex matches in request url described above.
  1489. * @returns {requestHandler} Returns an object with `respond` method that controls how a matched
  1490. * request is handled. You can save this object for later use and invoke `respond` again in
  1491. * order to change how a matched request is handled.
  1492. */
  1493. /**
  1494. * @ngdoc method
  1495. * @name $httpBackend#expectDELETE
  1496. * @description
  1497. * Creates a new request expectation for DELETE requests. For more info see `expect()`.
  1498. *
  1499. * @param {string|RegExp|function(string)} url HTTP url or function that receives a url
  1500. * and returns true if the url matches the current definition.
  1501. * @param {Object=} headers HTTP headers.
  1502. * @param {(Array)=} keys Array of keys to assign to regex matches in request url described above.
  1503. * @returns {requestHandler} Returns an object with `respond` method that controls how a matched
  1504. * request is handled. You can save this object for later use and invoke `respond` again in
  1505. * order to change how a matched request is handled.
  1506. */
  1507. /**
  1508. * @ngdoc method
  1509. * @name $httpBackend#expectPOST
  1510. * @description
  1511. * Creates a new request expectation for POST requests. For more info see `expect()`.
  1512. *
  1513. * @param {string|RegExp|function(string)} url HTTP url or function that receives a url
  1514. * and returns true if the url matches the current definition.
  1515. * @param {(string|RegExp|function(string)|Object)=} data HTTP request body or function that
  1516. * receives data string and returns true if the data is as expected, or Object if request body
  1517. * is in JSON format.
  1518. * @param {Object=} headers HTTP headers.
  1519. * @param {(Array)=} keys Array of keys to assign to regex matches in request url described above.
  1520. * @returns {requestHandler} Returns an object with `respond` method that controls how a matched
  1521. * request is handled. You can save this object for later use and invoke `respond` again in
  1522. * order to change how a matched request is handled.
  1523. */
  1524. /**
  1525. * @ngdoc method
  1526. * @name $httpBackend#expectPUT
  1527. * @description
  1528. * Creates a new request expectation for PUT requests. For more info see `expect()`.
  1529. *
  1530. * @param {string|RegExp|function(string)} url HTTP url or function that receives a url
  1531. * and returns true if the url matches the current definition.
  1532. * @param {(string|RegExp|function(string)|Object)=} data HTTP request body or function that
  1533. * receives data string and returns true if the data is as expected, or Object if request body
  1534. * is in JSON format.
  1535. * @param {Object=} headers HTTP headers.
  1536. * @param {(Array)=} keys Array of keys to assign to regex matches in request url described above.
  1537. * @returns {requestHandler} Returns an object with `respond` method that controls how a matched
  1538. * request is handled. You can save this object for later use and invoke `respond` again in
  1539. * order to change how a matched request is handled.
  1540. */
  1541. /**
  1542. * @ngdoc method
  1543. * @name $httpBackend#expectPATCH
  1544. * @description
  1545. * Creates a new request expectation for PATCH requests. For more info see `expect()`.
  1546. *
  1547. * @param {string|RegExp|function(string)} url HTTP url or function that receives a url
  1548. * and returns true if the url matches the current definition.
  1549. * @param {(string|RegExp|function(string)|Object)=} data HTTP request body or function that
  1550. * receives data string and returns true if the data is as expected, or Object if request body
  1551. * is in JSON format.
  1552. * @param {Object=} headers HTTP headers.
  1553. * @param {(Array)=} keys Array of keys to assign to regex matches in request url described above.
  1554. * @returns {requestHandler} Returns an object with `respond` method that controls how a matched
  1555. * request is handled. You can save this object for later use and invoke `respond` again in
  1556. * order to change how a matched request is handled.
  1557. */
  1558. /**
  1559. * @ngdoc method
  1560. * @name $httpBackend#expectJSONP
  1561. * @description
  1562. * Creates a new request expectation for JSONP requests. For more info see `expect()`.
  1563. *
  1564. * @param {string|RegExp|function(string)} url HTTP url or function that receives an url
  1565. * and returns true if the url matches the current definition.
  1566. * @param {(Array)=} keys Array of keys to assign to regex matches in request url described above.
  1567. * @returns {requestHandler} Returns an object with `respond` method that controls how a matched
  1568. * request is handled. You can save this object for later use and invoke `respond` again in
  1569. * order to change how a matched request is handled.
  1570. */
  1571. createShortMethods('expect');
  1572. /**
  1573. * @ngdoc method
  1574. * @name $httpBackend#expectRoute
  1575. * @description
  1576. * Creates a new request expectation that compares only with the requested route.
  1577. *
  1578. * @param {string} method HTTP method.
  1579. * @param {string} url HTTP url string that supports colon param matching.
  1580. * @returns {requestHandler} Returns an object with `respond` method that controls how a matched
  1581. * request is handled. You can save this object for later use and invoke `respond` again in
  1582. * order to change how a matched request is handled. See #expect for more info.
  1583. */
  1584. $httpBackend.expectRoute = function(method, url) {
  1585. var pathObj = parseRoute(url);
  1586. return $httpBackend.expect(method, pathObj.regexp, undefined, undefined, pathObj.keys);
  1587. };
  1588. /**
  1589. * @ngdoc method
  1590. * @name $httpBackend#flush
  1591. * @description
  1592. * Flushes all pending requests using the trained responses.
  1593. *
  1594. * @param {number=} count Number of responses to flush (in the order they arrived). If undefined,
  1595. * all pending requests will be flushed. If there are no pending requests when the flush method
  1596. * is called an exception is thrown (as this typically a sign of programming error).
  1597. */
  1598. $httpBackend.flush = function(count, digest) {
  1599. if (digest !== false) $rootScope.$digest();
  1600. if (!responses.length) throw new Error('No pending request to flush !');
  1601. if (angular.isDefined(count) && count !== null) {
  1602. while (count--) {
  1603. if (!responses.length) throw new Error('No more pending request to flush !');
  1604. responses.shift()();
  1605. }
  1606. } else {
  1607. while (responses.length) {
  1608. responses.shift()();
  1609. }
  1610. }
  1611. $httpBackend.verifyNoOutstandingExpectation(digest);
  1612. };
  1613. /**
  1614. * @ngdoc method
  1615. * @name $httpBackend#verifyNoOutstandingExpectation
  1616. * @description
  1617. * Verifies that all of the requests defined via the `expect` api were made. If any of the
  1618. * requests were not made, verifyNoOutstandingExpectation throws an exception.
  1619. *
  1620. * Typically, you would call this method following each test case that asserts requests using an
  1621. * "afterEach" clause.
  1622. *
  1623. * ```js
  1624. * afterEach($httpBackend.verifyNoOutstandingExpectation);
  1625. * ```
  1626. */
  1627. $httpBackend.verifyNoOutstandingExpectation = function(digest) {
  1628. if (digest !== false) $rootScope.$digest();
  1629. if (expectations.length) {
  1630. throw new Error('Unsatisfied requests: ' + expectations.join(', '));
  1631. }
  1632. };
  1633. /**
  1634. * @ngdoc method
  1635. * @name $httpBackend#verifyNoOutstandingRequest
  1636. * @description
  1637. * Verifies that there are no outstanding requests that need to be flushed.
  1638. *
  1639. * Typically, you would call this method following each test case that asserts requests using an
  1640. * "afterEach" clause.
  1641. *
  1642. * ```js
  1643. * afterEach($httpBackend.verifyNoOutstandingRequest);
  1644. * ```
  1645. */
  1646. $httpBackend.verifyNoOutstandingRequest = function() {
  1647. if (responses.length) {
  1648. throw new Error('Unflushed requests: ' + responses.length);
  1649. }
  1650. };
  1651. /**
  1652. * @ngdoc method
  1653. * @name $httpBackend#resetExpectations
  1654. * @description
  1655. * Resets all request expectations, but preserves all backend definitions. Typically, you would
  1656. * call resetExpectations during a multiple-phase test when you want to reuse the same instance of
  1657. * $httpBackend mock.
  1658. */
  1659. $httpBackend.resetExpectations = function() {
  1660. expectations.length = 0;
  1661. responses.length = 0;
  1662. };
  1663. return $httpBackend;
  1664. function createShortMethods(prefix) {
  1665. angular.forEach(['GET', 'DELETE', 'JSONP', 'HEAD'], function(method) {
  1666. $httpBackend[prefix + method] = function(url, headers, keys) {
  1667. return $httpBackend[prefix](method, url, undefined, headers, keys);
  1668. };
  1669. });
  1670. angular.forEach(['PUT', 'POST', 'PATCH'], function(method) {
  1671. $httpBackend[prefix + method] = function(url, data, headers, keys) {
  1672. return $httpBackend[prefix](method, url, data, headers, keys);
  1673. };
  1674. });
  1675. }
  1676. }
  1677. function MockHttpExpectation(method, url, data, headers, keys) {
  1678. function getUrlParams(u) {
  1679. var params = u.slice(u.indexOf('?') + 1).split('&');
  1680. return params.sort();
  1681. }
  1682. function compareUrl(u) {
  1683. return (url.slice(0, url.indexOf('?')) == u.slice(0, u.indexOf('?')) && getUrlParams(url).join() == getUrlParams(u).join());
  1684. }
  1685. this.data = data;
  1686. this.headers = headers;
  1687. this.match = function(m, u, d, h) {
  1688. if (method != m) return false;
  1689. if (!this.matchUrl(u)) return false;
  1690. if (angular.isDefined(d) && !this.matchData(d)) return false;
  1691. if (angular.isDefined(h) && !this.matchHeaders(h)) return false;
  1692. return true;
  1693. };
  1694. this.matchUrl = function(u) {
  1695. if (!url) return true;
  1696. if (angular.isFunction(url.test)) return url.test(u);
  1697. if (angular.isFunction(url)) return url(u);
  1698. return (url == u || compareUrl(u));
  1699. };
  1700. this.matchHeaders = function(h) {
  1701. if (angular.isUndefined(headers)) return true;
  1702. if (angular.isFunction(headers)) return headers(h);
  1703. return angular.equals(headers, h);
  1704. };
  1705. this.matchData = function(d) {
  1706. if (angular.isUndefined(data)) return true;
  1707. if (data && angular.isFunction(data.test)) return data.test(d);
  1708. if (data && angular.isFunction(data)) return data(d);
  1709. if (data && !angular.isString(data)) {
  1710. return angular.equals(angular.fromJson(angular.toJson(data)), angular.fromJson(d));
  1711. }
  1712. return data == d;
  1713. };
  1714. this.toString = function() {
  1715. return method + ' ' + url;
  1716. };
  1717. this.params = function(u) {
  1718. return angular.extend(parseQuery(), pathParams());
  1719. function pathParams() {
  1720. var keyObj = {};
  1721. if (!url || !angular.isFunction(url.test) || !keys || keys.length === 0) return keyObj;
  1722. var m = url.exec(u);
  1723. if (!m) return keyObj;
  1724. for (var i = 1, len = m.length; i < len; ++i) {
  1725. var key = keys[i - 1];
  1726. var val = m[i];
  1727. if (key && val) {
  1728. keyObj[key.name || key] = val;
  1729. }
  1730. }
  1731. return keyObj;
  1732. }
  1733. function parseQuery() {
  1734. var obj = {}, key_value, key,
  1735. queryStr = u.indexOf('?') > -1
  1736. ? u.substring(u.indexOf('?') + 1)
  1737. : "";
  1738. angular.forEach(queryStr.split('&'), function(keyValue) {
  1739. if (keyValue) {
  1740. key_value = keyValue.replace(/\+/g,'%20').split('=');
  1741. key = tryDecodeURIComponent(key_value[0]);
  1742. if (angular.isDefined(key)) {
  1743. var val = angular.isDefined(key_value[1]) ? tryDecodeURIComponent(key_value[1]) : true;
  1744. if (!hasOwnProperty.call(obj, key)) {
  1745. obj[key] = val;
  1746. } else if (angular.isArray(obj[key])) {
  1747. obj[key].push(val);
  1748. } else {
  1749. obj[key] = [obj[key],val];
  1750. }
  1751. }
  1752. }
  1753. });
  1754. return obj;
  1755. }
  1756. function tryDecodeURIComponent(value) {
  1757. try {
  1758. return decodeURIComponent(value);
  1759. } catch (e) {
  1760. // Ignore any invalid uri component
  1761. }
  1762. }
  1763. };
  1764. }
  1765. function createMockXhr() {
  1766. return new MockXhr();
  1767. }
  1768. function MockXhr() {
  1769. // hack for testing $http, $httpBackend
  1770. MockXhr.$$lastInstance = this;
  1771. this.open = function(method, url, async) {
  1772. this.$$method = method;
  1773. this.$$url = url;
  1774. this.$$async = async;
  1775. this.$$reqHeaders = {};
  1776. this.$$respHeaders = {};
  1777. };
  1778. this.send = function(data) {
  1779. this.$$data = data;
  1780. };
  1781. this.setRequestHeader = function(key, value) {
  1782. this.$$reqHeaders[key] = value;
  1783. };
  1784. this.getResponseHeader = function(name) {
  1785. // the lookup must be case insensitive,
  1786. // that's why we try two quick lookups first and full scan last
  1787. var header = this.$$respHeaders[name];
  1788. if (header) return header;
  1789. name = angular.lowercase(name);
  1790. header = this.$$respHeaders[name];
  1791. if (header) return header;
  1792. header = undefined;
  1793. angular.forEach(this.$$respHeaders, function(headerVal, headerName) {
  1794. if (!header && angular.lowercase(headerName) == name) header = headerVal;
  1795. });
  1796. return header;
  1797. };
  1798. this.getAllResponseHeaders = function() {
  1799. var lines = [];
  1800. angular.forEach(this.$$respHeaders, function(value, key) {
  1801. lines.push(key + ': ' + value);
  1802. });
  1803. return lines.join('\n');
  1804. };
  1805. this.abort = angular.noop;
  1806. // This section simulates the events on a real XHR object (and the upload object)
  1807. // When we are testing $httpBackend (inside the angular project) we make partial use of this
  1808. // but store the events directly ourselves on `$$events`, instead of going through the `addEventListener`
  1809. this.$$events = {};
  1810. this.addEventListener = function(name, listener) {
  1811. if (angular.isUndefined(this.$$events[name])) this.$$events[name] = [];
  1812. this.$$events[name].push(listener);
  1813. };
  1814. this.upload = {
  1815. $$events: {},
  1816. addEventListener: this.addEventListener
  1817. };
  1818. }
  1819. /**
  1820. * @ngdoc service
  1821. * @name $timeout
  1822. * @description
  1823. *
  1824. * This service is just a simple decorator for {@link ng.$timeout $timeout} service
  1825. * that adds a "flush" and "verifyNoPendingTasks" methods.
  1826. */
  1827. angular.mock.$TimeoutDecorator = ['$delegate', '$browser', function($delegate, $browser) {
  1828. /**
  1829. * @ngdoc method
  1830. * @name $timeout#flush
  1831. * @description
  1832. *
  1833. * Flushes the queue of pending tasks.
  1834. *
  1835. * @param {number=} delay maximum timeout amount to flush up until
  1836. */
  1837. $delegate.flush = function(delay) {
  1838. $browser.defer.flush(delay);
  1839. };
  1840. /**
  1841. * @ngdoc method
  1842. * @name $timeout#verifyNoPendingTasks
  1843. * @description
  1844. *
  1845. * Verifies that there are no pending tasks that need to be flushed.
  1846. */
  1847. $delegate.verifyNoPendingTasks = function() {
  1848. if ($browser.deferredFns.length) {
  1849. throw new Error('Deferred tasks to flush (' + $browser.deferredFns.length + '): ' +
  1850. formatPendingTasksAsString($browser.deferredFns));
  1851. }
  1852. };
  1853. function formatPendingTasksAsString(tasks) {
  1854. var result = [];
  1855. angular.forEach(tasks, function(task) {
  1856. result.push('{id: ' + task.id + ', ' + 'time: ' + task.time + '}');
  1857. });
  1858. return result.join(', ');
  1859. }
  1860. return $delegate;
  1861. }];
  1862. angular.mock.$RAFDecorator = ['$delegate', function($delegate) {
  1863. var rafFn = function(fn) {
  1864. var index = rafFn.queue.length;
  1865. rafFn.queue.push(fn);
  1866. return function() {
  1867. rafFn.queue.splice(index, 1);
  1868. };
  1869. };
  1870. rafFn.queue = [];
  1871. rafFn.supported = $delegate.supported;
  1872. rafFn.flush = function() {
  1873. if (rafFn.queue.length === 0) {
  1874. throw new Error('No rAF callbacks present');
  1875. }
  1876. var length = rafFn.queue.length;
  1877. for (var i = 0; i < length; i++) {
  1878. rafFn.queue[i]();
  1879. }
  1880. rafFn.queue = rafFn.queue.slice(i);
  1881. };
  1882. return rafFn;
  1883. }];
  1884. /**
  1885. *
  1886. */
  1887. var originalRootElement;
  1888. angular.mock.$RootElementProvider = function() {
  1889. this.$get = ['$injector', function($injector) {
  1890. originalRootElement = angular.element('<div ng-app></div>').data('$injector', $injector);
  1891. return originalRootElement;
  1892. }];
  1893. };
  1894. /**
  1895. * @ngdoc service
  1896. * @name $controller
  1897. * @description
  1898. * A decorator for {@link ng.$controller} with additional `bindings` parameter, useful when testing
  1899. * controllers of directives that use {@link $compile#-bindtocontroller- `bindToController`}.
  1900. *
  1901. *
  1902. * ## Example
  1903. *
  1904. * ```js
  1905. *
  1906. * // Directive definition ...
  1907. *
  1908. * myMod.directive('myDirective', {
  1909. * controller: 'MyDirectiveController',
  1910. * bindToController: {
  1911. * name: '@'
  1912. * }
  1913. * });
  1914. *
  1915. *
  1916. * // Controller definition ...
  1917. *
  1918. * myMod.controller('MyDirectiveController', ['$log', function($log) {
  1919. * $log.info(this.name);
  1920. * }]);
  1921. *
  1922. *
  1923. * // In a test ...
  1924. *
  1925. * describe('myDirectiveController', function() {
  1926. * it('should write the bound name to the log', inject(function($controller, $log) {
  1927. * var ctrl = $controller('MyDirectiveController', { /* no locals &#42;/ }, { name: 'Clark Kent' });
  1928. * expect(ctrl.name).toEqual('Clark Kent');
  1929. * expect($log.info.logs).toEqual(['Clark Kent']);
  1930. * }));
  1931. * });
  1932. *
  1933. * ```
  1934. *
  1935. * @param {Function|string} constructor If called with a function then it's considered to be the
  1936. * controller constructor function. Otherwise it's considered to be a string which is used
  1937. * to retrieve the controller constructor using the following steps:
  1938. *
  1939. * * check if a controller with given name is registered via `$controllerProvider`
  1940. * * check if evaluating the string on the current scope returns a constructor
  1941. * * if $controllerProvider#allowGlobals, check `window[constructor]` on the global
  1942. * `window` object (not recommended)
  1943. *
  1944. * The string can use the `controller as property` syntax, where the controller instance is published
  1945. * as the specified property on the `scope`; the `scope` must be injected into `locals` param for this
  1946. * to work correctly.
  1947. *
  1948. * @param {Object} locals Injection locals for Controller.
  1949. * @param {Object=} bindings Properties to add to the controller before invoking the constructor. This is used
  1950. * to simulate the `bindToController` feature and simplify certain kinds of tests.
  1951. * @return {Object} Instance of given controller.
  1952. */
  1953. angular.mock.$ControllerDecorator = ['$delegate', function($delegate) {
  1954. return function(expression, locals, later, ident) {
  1955. if (later && typeof later === 'object') {
  1956. var instantiate = $delegate(expression, locals, true, ident);
  1957. angular.extend(instantiate.instance, later);
  1958. var instance = instantiate();
  1959. if (instance !== instantiate.instance) {
  1960. angular.extend(instance, later);
  1961. }
  1962. return instance;
  1963. }
  1964. return $delegate(expression, locals, later, ident);
  1965. };
  1966. }];
  1967. /**
  1968. * @ngdoc service
  1969. * @name $componentController
  1970. * @description
  1971. * A service that can be used to create instances of component controllers.
  1972. * <div class="alert alert-info">
  1973. * Be aware that the controller will be instantiated and attached to the scope as specified in
  1974. * the component definition object. If you do not provide a `$scope` object in the `locals` param
  1975. * then the helper will create a new isolated scope as a child of `$rootScope`.
  1976. * </div>
  1977. * @param {string} componentName the name of the component whose controller we want to instantiate
  1978. * @param {Object} locals Injection locals for Controller.
  1979. * @param {Object=} bindings Properties to add to the controller before invoking the constructor. This is used
  1980. * to simulate the `bindToController` feature and simplify certain kinds of tests.
  1981. * @param {string=} ident Override the property name to use when attaching the controller to the scope.
  1982. * @return {Object} Instance of requested controller.
  1983. */
  1984. angular.mock.$ComponentControllerProvider = ['$compileProvider', function($compileProvider) {
  1985. this.$get = ['$controller','$injector', '$rootScope', function($controller, $injector, $rootScope) {
  1986. return function $componentController(componentName, locals, bindings, ident) {
  1987. // get all directives associated to the component name
  1988. var directives = $injector.get(componentName + 'Directive');
  1989. // look for those directives that are components
  1990. var candidateDirectives = directives.filter(function(directiveInfo) {
  1991. // components have controller, controllerAs and restrict:'E'
  1992. return directiveInfo.controller && directiveInfo.controllerAs && directiveInfo.restrict === 'E';
  1993. });
  1994. // check if valid directives found
  1995. if (candidateDirectives.length === 0) {
  1996. throw new Error('No component found');
  1997. }
  1998. if (candidateDirectives.length > 1) {
  1999. throw new Error('Too many components found');
  2000. }
  2001. // get the info of the component
  2002. var directiveInfo = candidateDirectives[0];
  2003. // create a scope if needed
  2004. locals = locals || {};
  2005. locals.$scope = locals.$scope || $rootScope.$new(true);
  2006. return $controller(directiveInfo.controller, locals, bindings, ident || directiveInfo.controllerAs);
  2007. };
  2008. }];
  2009. }];
  2010. /**
  2011. * @ngdoc module
  2012. * @name ngMock
  2013. * @packageName angular-mocks
  2014. * @description
  2015. *
  2016. * # ngMock
  2017. *
  2018. * The `ngMock` module provides support to inject and mock Angular services into unit tests.
  2019. * In addition, ngMock also extends various core ng services such that they can be
  2020. * inspected and controlled in a synchronous manner within test code.
  2021. *
  2022. *
  2023. * <div doc-module-components="ngMock"></div>
  2024. *
  2025. * @installation
  2026. *
  2027. * First, download the file:
  2028. * * [Google CDN](https://developers.google.com/speed/libraries/devguide#angularjs) e.g.
  2029. * `"//ajax.googleapis.com/ajax/libs/angularjs/X.Y.Z/angular-mocks.js"`
  2030. * * [NPM](https://www.npmjs.com/) e.g. `npm install angular-mocks@X.Y.Z`
  2031. * * [Bower](http://bower.io) e.g. `bower install angular-mocks#X.Y.Z`
  2032. * * [code.angularjs.org](https://code.angularjs.org/) (discouraged for production use) e.g.
  2033. * `"//code.angularjs.org/X.Y.Z/angular-mocks.js"`
  2034. *
  2035. * where X.Y.Z is the AngularJS version you are running.
  2036. *
  2037. * Then, configure your test runner to load `angular-mocks.js` after `angular.js`.
  2038. * This example uses <a href="http://karma-runner.github.io/">Karma</a>:
  2039. *
  2040. * ```
  2041. * config.set({
  2042. * files: [
  2043. * 'build/angular.js', // and other module files you need
  2044. * 'build/angular-mocks.js',
  2045. * '<path/to/application/files>',
  2046. * '<path/to/spec/files>'
  2047. * ]
  2048. * });
  2049. * ```
  2050. *
  2051. * Including the `angular-mocks.js` file automatically adds the `ngMock` module, so your tests
  2052. * are ready to go!
  2053. */
  2054. angular.module('ngMock', ['ng']).provider({
  2055. $browser: angular.mock.$BrowserProvider,
  2056. $exceptionHandler: angular.mock.$ExceptionHandlerProvider,
  2057. $log: angular.mock.$LogProvider,
  2058. $interval: angular.mock.$IntervalProvider,
  2059. $httpBackend: angular.mock.$HttpBackendProvider,
  2060. $rootElement: angular.mock.$RootElementProvider,
  2061. $componentController: angular.mock.$ComponentControllerProvider
  2062. }).config(['$provide', function($provide) {
  2063. $provide.decorator('$timeout', angular.mock.$TimeoutDecorator);
  2064. $provide.decorator('$$rAF', angular.mock.$RAFDecorator);
  2065. $provide.decorator('$rootScope', angular.mock.$RootScopeDecorator);
  2066. $provide.decorator('$controller', angular.mock.$ControllerDecorator);
  2067. }]);
  2068. /**
  2069. * @ngdoc module
  2070. * @name ngMockE2E
  2071. * @module ngMockE2E
  2072. * @packageName angular-mocks
  2073. * @description
  2074. *
  2075. * The `ngMockE2E` is an angular module which contains mocks suitable for end-to-end testing.
  2076. * Currently there is only one mock present in this module -
  2077. * the {@link ngMockE2E.$httpBackend e2e $httpBackend} mock.
  2078. */
  2079. angular.module('ngMockE2E', ['ng']).config(['$provide', function($provide) {
  2080. $provide.value('$httpBackend', angular.injector(['ng']).get('$httpBackend'));
  2081. $provide.decorator('$httpBackend', angular.mock.e2e.$httpBackendDecorator);
  2082. }]);
  2083. /**
  2084. * @ngdoc service
  2085. * @name $httpBackend
  2086. * @module ngMockE2E
  2087. * @description
  2088. * Fake HTTP backend implementation suitable for end-to-end testing or backend-less development of
  2089. * applications that use the {@link ng.$http $http service}.
  2090. *
  2091. * <div class="alert alert-info">
  2092. * **Note**: For fake http backend implementation suitable for unit testing please see
  2093. * {@link ngMock.$httpBackend unit-testing $httpBackend mock}.
  2094. * </div>
  2095. *
  2096. * This implementation can be used to respond with static or dynamic responses via the `when` api
  2097. * and its shortcuts (`whenGET`, `whenPOST`, etc) and optionally pass through requests to the
  2098. * real $httpBackend for specific requests (e.g. to interact with certain remote apis or to fetch
  2099. * templates from a webserver).
  2100. *
  2101. * As opposed to unit-testing, in an end-to-end testing scenario or in scenario when an application
  2102. * is being developed with the real backend api replaced with a mock, it is often desirable for
  2103. * certain category of requests to bypass the mock and issue a real http request (e.g. to fetch
  2104. * templates or static files from the webserver). To configure the backend with this behavior
  2105. * use the `passThrough` request handler of `when` instead of `respond`.
  2106. *
  2107. * Additionally, we don't want to manually have to flush mocked out requests like we do during unit
  2108. * testing. For this reason the e2e $httpBackend flushes mocked out requests
  2109. * automatically, closely simulating the behavior of the XMLHttpRequest object.
  2110. *
  2111. * To setup the application to run with this http backend, you have to create a module that depends
  2112. * on the `ngMockE2E` and your application modules and defines the fake backend:
  2113. *
  2114. * ```js
  2115. * var myAppDev = angular.module('myAppDev', ['myApp', 'ngMockE2E']);
  2116. * myAppDev.run(function($httpBackend) {
  2117. * var phones = [{name: 'phone1'}, {name: 'phone2'}];
  2118. *
  2119. * // returns the current list of phones
  2120. * $httpBackend.whenGET('/phones').respond(phones);
  2121. *
  2122. * // adds a new phone to the phones array
  2123. * $httpBackend.whenPOST('/phones').respond(function(method, url, data) {
  2124. * var phone = angular.fromJson(data);
  2125. * phones.push(phone);
  2126. * return [200, phone, {}];
  2127. * });
  2128. * $httpBackend.whenGET(/^\/templates\//).passThrough(); // Requests for templare are handled by the real server
  2129. * //...
  2130. * });
  2131. * ```
  2132. *
  2133. * Afterwards, bootstrap your app with this new module.
  2134. *
  2135. * ## Example
  2136. * <example name="httpbackend-e2e-testing" module="myAppE2E" deps="angular-mocks.js">
  2137. * <file name="app.js">
  2138. * var myApp = angular.module('myApp', []);
  2139. *
  2140. * myApp.controller('main', function($http) {
  2141. * var ctrl = this;
  2142. *
  2143. * ctrl.phones = [];
  2144. * ctrl.newPhone = {
  2145. * name: ''
  2146. * };
  2147. *
  2148. * ctrl.getPhones = function() {
  2149. * $http.get('/phones').then(function(response) {
  2150. * ctrl.phones = response.data;
  2151. * });
  2152. * };
  2153. *
  2154. * ctrl.addPhone = function(phone) {
  2155. * $http.post('/phones', phone).then(function() {
  2156. * ctrl.newPhone = {name: ''};
  2157. * return ctrl.getPhones();
  2158. * });
  2159. * };
  2160. *
  2161. * ctrl.getPhones();
  2162. * });
  2163. * </file>
  2164. * <file name="e2e.js">
  2165. * var myAppDev = angular.module('myAppE2E', ['myApp', 'ngMockE2E']);
  2166. *
  2167. * myAppDev.run(function($httpBackend) {
  2168. * var phones = [{name: 'phone1'}, {name: 'phone2'}];
  2169. *
  2170. * // returns the current list of phones
  2171. * $httpBackend.whenGET('/phones').respond(phones);
  2172. *
  2173. * // adds a new phone to the phones array
  2174. * $httpBackend.whenPOST('/phones').respond(function(method, url, data) {
  2175. * var phone = angular.fromJson(data);
  2176. * phones.push(phone);
  2177. * return [200, phone, {}];
  2178. * });
  2179. * });
  2180. * </file>
  2181. * <file name="index.html">
  2182. * <div ng-controller="main as $ctrl">
  2183. * <form name="newPhoneForm" ng-submit="$ctrl.addPhone($ctrl.newPhone)">
  2184. * <input type="text" ng-model="$ctrl.newPhone.name">
  2185. * <input type="submit" value="Add Phone">
  2186. * </form>
  2187. * <h1>Phones</h1>
  2188. * <ul>
  2189. * <li ng-repeat="phone in $ctrl.phones">{{phone.name}}</li>
  2190. * </ul>
  2191. * </div>
  2192. * </file>
  2193. * </example>
  2194. *
  2195. *
  2196. */
  2197. /**
  2198. * @ngdoc method
  2199. * @name $httpBackend#when
  2200. * @module ngMockE2E
  2201. * @description
  2202. * Creates a new backend definition.
  2203. *
  2204. * @param {string} method HTTP method.
  2205. * @param {string|RegExp|function(string)} url HTTP url or function that receives a url
  2206. * and returns true if the url matches the current definition.
  2207. * @param {(string|RegExp)=} data HTTP request body.
  2208. * @param {(Object|function(Object))=} headers HTTP headers or function that receives http header
  2209. * object and returns true if the headers match the current definition.
  2210. * @param {(Array)=} keys Array of keys to assign to regex matches in request url described on
  2211. * {@link ngMock.$httpBackend $httpBackend mock}.
  2212. * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
  2213. * control how a matched request is handled. You can save this object for later use and invoke
  2214. * `respond` or `passThrough` again in order to change how a matched request is handled.
  2215. *
  2216. * - respond –
  2217. * ```
  2218. * { function([status,] data[, headers, statusText])
  2219. * | function(function(method, url, data, headers, params)}
  2220. * ```
  2221. * – The respond method takes a set of static data to be returned or a function that can return
  2222. * an array containing response status (number), response data (Array|Object|string), response
  2223. * headers (Object), and the text for the status (string).
  2224. * - passThrough – `{function()}` – Any request matching a backend definition with
  2225. * `passThrough` handler will be passed through to the real backend (an XHR request will be made
  2226. * to the server.)
  2227. * - Both methods return the `requestHandler` object for possible overrides.
  2228. */
  2229. /**
  2230. * @ngdoc method
  2231. * @name $httpBackend#whenGET
  2232. * @module ngMockE2E
  2233. * @description
  2234. * Creates a new backend definition for GET requests. For more info see `when()`.
  2235. *
  2236. * @param {string|RegExp|function(string)} url HTTP url or function that receives a url
  2237. * and returns true if the url matches the current definition.
  2238. * @param {(Object|function(Object))=} headers HTTP headers.
  2239. * @param {(Array)=} keys Array of keys to assign to regex matches in request url described on
  2240. * {@link ngMock.$httpBackend $httpBackend mock}.
  2241. * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
  2242. * control how a matched request is handled. You can save this object for later use and invoke
  2243. * `respond` or `passThrough` again in order to change how a matched request is handled.
  2244. */
  2245. /**
  2246. * @ngdoc method
  2247. * @name $httpBackend#whenHEAD
  2248. * @module ngMockE2E
  2249. * @description
  2250. * Creates a new backend definition for HEAD requests. For more info see `when()`.
  2251. *
  2252. * @param {string|RegExp|function(string)} url HTTP url or function that receives a url
  2253. * and returns true if the url matches the current definition.
  2254. * @param {(Object|function(Object))=} headers HTTP headers.
  2255. * @param {(Array)=} keys Array of keys to assign to regex matches in request url described on
  2256. * {@link ngMock.$httpBackend $httpBackend mock}.
  2257. * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
  2258. * control how a matched request is handled. You can save this object for later use and invoke
  2259. * `respond` or `passThrough` again in order to change how a matched request is handled.
  2260. */
  2261. /**
  2262. * @ngdoc method
  2263. * @name $httpBackend#whenDELETE
  2264. * @module ngMockE2E
  2265. * @description
  2266. * Creates a new backend definition for DELETE requests. For more info see `when()`.
  2267. *
  2268. * @param {string|RegExp|function(string)} url HTTP url or function that receives a url
  2269. * and returns true if the url matches the current definition.
  2270. * @param {(Object|function(Object))=} headers HTTP headers.
  2271. * @param {(Array)=} keys Array of keys to assign to regex matches in request url described on
  2272. * {@link ngMock.$httpBackend $httpBackend mock}.
  2273. * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
  2274. * control how a matched request is handled. You can save this object for later use and invoke
  2275. * `respond` or `passThrough` again in order to change how a matched request is handled.
  2276. */
  2277. /**
  2278. * @ngdoc method
  2279. * @name $httpBackend#whenPOST
  2280. * @module ngMockE2E
  2281. * @description
  2282. * Creates a new backend definition for POST requests. For more info see `when()`.
  2283. *
  2284. * @param {string|RegExp|function(string)} url HTTP url or function that receives a url
  2285. * and returns true if the url matches the current definition.
  2286. * @param {(string|RegExp)=} data HTTP request body.
  2287. * @param {(Object|function(Object))=} headers HTTP headers.
  2288. * @param {(Array)=} keys Array of keys to assign to regex matches in request url described on
  2289. * {@link ngMock.$httpBackend $httpBackend mock}.
  2290. * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
  2291. * control how a matched request is handled. You can save this object for later use and invoke
  2292. * `respond` or `passThrough` again in order to change how a matched request is handled.
  2293. */
  2294. /**
  2295. * @ngdoc method
  2296. * @name $httpBackend#whenPUT
  2297. * @module ngMockE2E
  2298. * @description
  2299. * Creates a new backend definition for PUT requests. For more info see `when()`.
  2300. *
  2301. * @param {string|RegExp|function(string)} url HTTP url or function that receives a url
  2302. * and returns true if the url matches the current definition.
  2303. * @param {(string|RegExp)=} data HTTP request body.
  2304. * @param {(Object|function(Object))=} headers HTTP headers.
  2305. * @param {(Array)=} keys Array of keys to assign to regex matches in request url described on
  2306. * {@link ngMock.$httpBackend $httpBackend mock}.
  2307. * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
  2308. * control how a matched request is handled. You can save this object for later use and invoke
  2309. * `respond` or `passThrough` again in order to change how a matched request is handled.
  2310. */
  2311. /**
  2312. * @ngdoc method
  2313. * @name $httpBackend#whenPATCH
  2314. * @module ngMockE2E
  2315. * @description
  2316. * Creates a new backend definition for PATCH requests. For more info see `when()`.
  2317. *
  2318. * @param {string|RegExp|function(string)} url HTTP url or function that receives a url
  2319. * and returns true if the url matches the current definition.
  2320. * @param {(string|RegExp)=} data HTTP request body.
  2321. * @param {(Object|function(Object))=} headers HTTP headers.
  2322. * @param {(Array)=} keys Array of keys to assign to regex matches in request url described on
  2323. * {@link ngMock.$httpBackend $httpBackend mock}.
  2324. * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
  2325. * control how a matched request is handled. You can save this object for later use and invoke
  2326. * `respond` or `passThrough` again in order to change how a matched request is handled.
  2327. */
  2328. /**
  2329. * @ngdoc method
  2330. * @name $httpBackend#whenJSONP
  2331. * @module ngMockE2E
  2332. * @description
  2333. * Creates a new backend definition for JSONP requests. For more info see `when()`.
  2334. *
  2335. * @param {string|RegExp|function(string)} url HTTP url or function that receives a url
  2336. * and returns true if the url matches the current definition.
  2337. * @param {(Array)=} keys Array of keys to assign to regex matches in request url described on
  2338. * {@link ngMock.$httpBackend $httpBackend mock}.
  2339. * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
  2340. * control how a matched request is handled. You can save this object for later use and invoke
  2341. * `respond` or `passThrough` again in order to change how a matched request is handled.
  2342. */
  2343. /**
  2344. * @ngdoc method
  2345. * @name $httpBackend#whenRoute
  2346. * @module ngMockE2E
  2347. * @description
  2348. * Creates a new backend definition that compares only with the requested route.
  2349. *
  2350. * @param {string} method HTTP method.
  2351. * @param {string} url HTTP url string that supports colon param matching.
  2352. * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
  2353. * control how a matched request is handled. You can save this object for later use and invoke
  2354. * `respond` or `passThrough` again in order to change how a matched request is handled.
  2355. */
  2356. angular.mock.e2e = {};
  2357. angular.mock.e2e.$httpBackendDecorator =
  2358. ['$rootScope', '$timeout', '$delegate', '$browser', createHttpBackendMock];
  2359. /**
  2360. * @ngdoc type
  2361. * @name $rootScope.Scope
  2362. * @module ngMock
  2363. * @description
  2364. * {@link ng.$rootScope.Scope Scope} type decorated with helper methods useful for testing. These
  2365. * methods are automatically available on any {@link ng.$rootScope.Scope Scope} instance when
  2366. * `ngMock` module is loaded.
  2367. *
  2368. * In addition to all the regular `Scope` methods, the following helper methods are available:
  2369. */
  2370. angular.mock.$RootScopeDecorator = ['$delegate', function($delegate) {
  2371. var $rootScopePrototype = Object.getPrototypeOf($delegate);
  2372. $rootScopePrototype.$countChildScopes = countChildScopes;
  2373. $rootScopePrototype.$countWatchers = countWatchers;
  2374. return $delegate;
  2375. // ------------------------------------------------------------------------------------------ //
  2376. /**
  2377. * @ngdoc method
  2378. * @name $rootScope.Scope#$countChildScopes
  2379. * @module ngMock
  2380. * @description
  2381. * Counts all the direct and indirect child scopes of the current scope.
  2382. *
  2383. * The current scope is excluded from the count. The count includes all isolate child scopes.
  2384. *
  2385. * @returns {number} Total number of child scopes.
  2386. */
  2387. function countChildScopes() {
  2388. // jshint validthis: true
  2389. var count = 0; // exclude the current scope
  2390. var pendingChildHeads = [this.$$childHead];
  2391. var currentScope;
  2392. while (pendingChildHeads.length) {
  2393. currentScope = pendingChildHeads.shift();
  2394. while (currentScope) {
  2395. count += 1;
  2396. pendingChildHeads.push(currentScope.$$childHead);
  2397. currentScope = currentScope.$$nextSibling;
  2398. }
  2399. }
  2400. return count;
  2401. }
  2402. /**
  2403. * @ngdoc method
  2404. * @name $rootScope.Scope#$countWatchers
  2405. * @module ngMock
  2406. * @description
  2407. * Counts all the watchers of direct and indirect child scopes of the current scope.
  2408. *
  2409. * The watchers of the current scope are included in the count and so are all the watchers of
  2410. * isolate child scopes.
  2411. *
  2412. * @returns {number} Total number of watchers.
  2413. */
  2414. function countWatchers() {
  2415. // jshint validthis: true
  2416. var count = this.$$watchers ? this.$$watchers.length : 0; // include the current scope
  2417. var pendingChildHeads = [this.$$childHead];
  2418. var currentScope;
  2419. while (pendingChildHeads.length) {
  2420. currentScope = pendingChildHeads.shift();
  2421. while (currentScope) {
  2422. count += currentScope.$$watchers ? currentScope.$$watchers.length : 0;
  2423. pendingChildHeads.push(currentScope.$$childHead);
  2424. currentScope = currentScope.$$nextSibling;
  2425. }
  2426. }
  2427. return count;
  2428. }
  2429. }];
  2430. !(function(jasmineOrMocha) {
  2431. if (!jasmineOrMocha) {
  2432. return;
  2433. }
  2434. var currentSpec = null,
  2435. injectorState = new InjectorState(),
  2436. annotatedFunctions = [],
  2437. wasInjectorCreated = function() {
  2438. return !!currentSpec;
  2439. };
  2440. angular.mock.$$annotate = angular.injector.$$annotate;
  2441. angular.injector.$$annotate = function(fn) {
  2442. if (typeof fn === 'function' && !fn.$inject) {
  2443. annotatedFunctions.push(fn);
  2444. }
  2445. return angular.mock.$$annotate.apply(this, arguments);
  2446. };
  2447. /**
  2448. * @ngdoc function
  2449. * @name angular.mock.module
  2450. * @description
  2451. *
  2452. * *NOTE*: This function is also published on window for easy access.<br>
  2453. * *NOTE*: This function is declared ONLY WHEN running tests with jasmine or mocha
  2454. *
  2455. * This function registers a module configuration code. It collects the configuration information
  2456. * which will be used when the injector is created by {@link angular.mock.inject inject}.
  2457. *
  2458. * See {@link angular.mock.inject inject} for usage example
  2459. *
  2460. * @param {...(string|Function|Object)} fns any number of modules which are represented as string
  2461. * aliases or as anonymous module initialization functions. The modules are used to
  2462. * configure the injector. The 'ng' and 'ngMock' modules are automatically loaded. If an
  2463. * object literal is passed each key-value pair will be registered on the module via
  2464. * {@link auto.$provide $provide}.value, the key being the string name (or token) to associate
  2465. * with the value on the injector.
  2466. */
  2467. var module = window.module = angular.mock.module = function() {
  2468. var moduleFns = Array.prototype.slice.call(arguments, 0);
  2469. return wasInjectorCreated() ? workFn() : workFn;
  2470. /////////////////////
  2471. function workFn() {
  2472. if (currentSpec.$injector) {
  2473. throw new Error('Injector already created, can not register a module!');
  2474. } else {
  2475. var fn, modules = currentSpec.$modules || (currentSpec.$modules = []);
  2476. angular.forEach(moduleFns, function(module) {
  2477. if (angular.isObject(module) && !angular.isArray(module)) {
  2478. fn = ['$provide', function($provide) {
  2479. angular.forEach(module, function(value, key) {
  2480. $provide.value(key, value);
  2481. });
  2482. }];
  2483. } else {
  2484. fn = module;
  2485. }
  2486. if (currentSpec.$providerInjector) {
  2487. currentSpec.$providerInjector.invoke(fn);
  2488. } else {
  2489. modules.push(fn);
  2490. }
  2491. });
  2492. }
  2493. }
  2494. };
  2495. module.$$beforeAllHook = (window.before || window.beforeAll);
  2496. module.$$afterAllHook = (window.after || window.afterAll);
  2497. // purely for testing ngMock itself
  2498. module.$$currentSpec = function(to) {
  2499. if (arguments.length === 0) return to;
  2500. currentSpec = to;
  2501. };
  2502. /**
  2503. * @ngdoc function
  2504. * @name angular.mock.module.sharedInjector
  2505. * @description
  2506. *
  2507. * *NOTE*: This function is declared ONLY WHEN running tests with jasmine or mocha
  2508. *
  2509. * This function ensures a single injector will be used for all tests in a given describe context.
  2510. * This contrasts with the default behaviour where a new injector is created per test case.
  2511. *
  2512. * Use sharedInjector when you want to take advantage of Jasmine's `beforeAll()`, or mocha's
  2513. * `before()` methods. Call `module.sharedInjector()` before you setup any other hooks that
  2514. * will create (i.e call `module()`) or use (i.e call `inject()`) the injector.
  2515. *
  2516. * You cannot call `sharedInjector()` from within a context already using `sharedInjector()`.
  2517. *
  2518. * ## Example
  2519. *
  2520. * Typically beforeAll is used to make many assertions about a single operation. This can
  2521. * cut down test run-time as the test setup doesn't need to be re-run, and enabling focussed
  2522. * tests each with a single assertion.
  2523. *
  2524. * ```js
  2525. * describe("Deep Thought", function() {
  2526. *
  2527. * module.sharedInjector();
  2528. *
  2529. * beforeAll(module("UltimateQuestion"));
  2530. *
  2531. * beforeAll(inject(function(DeepThought) {
  2532. * expect(DeepThought.answer).toBeUndefined();
  2533. * DeepThought.generateAnswer();
  2534. * }));
  2535. *
  2536. * it("has calculated the answer correctly", inject(function(DeepThought) {
  2537. * // Because of sharedInjector, we have access to the instance of the DeepThought service
  2538. * // that was provided to the beforeAll() hook. Therefore we can test the generated answer
  2539. * expect(DeepThought.answer).toBe(42);
  2540. * }));
  2541. *
  2542. * it("has calculated the answer within the expected time", inject(function(DeepThought) {
  2543. * expect(DeepThought.runTimeMillennia).toBeLessThan(8000);
  2544. * }));
  2545. *
  2546. * it("has double checked the answer", inject(function(DeepThought) {
  2547. * expect(DeepThought.absolutelySureItIsTheRightAnswer).toBe(true);
  2548. * }));
  2549. *
  2550. * });
  2551. *
  2552. * ```
  2553. */
  2554. module.sharedInjector = function() {
  2555. if (!(module.$$beforeAllHook && module.$$afterAllHook)) {
  2556. throw Error("sharedInjector() cannot be used unless your test runner defines beforeAll/afterAll");
  2557. }
  2558. var initialized = false;
  2559. module.$$beforeAllHook(function() {
  2560. if (injectorState.shared) {
  2561. injectorState.sharedError = Error("sharedInjector() cannot be called inside a context that has already called sharedInjector()");
  2562. throw injectorState.sharedError;
  2563. }
  2564. initialized = true;
  2565. currentSpec = this;
  2566. injectorState.shared = true;
  2567. });
  2568. module.$$afterAllHook(function() {
  2569. if (initialized) {
  2570. injectorState = new InjectorState();
  2571. module.$$cleanup();
  2572. } else {
  2573. injectorState.sharedError = null;
  2574. }
  2575. });
  2576. };
  2577. module.$$beforeEach = function() {
  2578. if (injectorState.shared && currentSpec && currentSpec != this) {
  2579. var state = currentSpec;
  2580. currentSpec = this;
  2581. angular.forEach(["$injector","$modules","$providerInjector", "$injectorStrict"], function(k) {
  2582. currentSpec[k] = state[k];
  2583. state[k] = null;
  2584. });
  2585. } else {
  2586. currentSpec = this;
  2587. originalRootElement = null;
  2588. annotatedFunctions = [];
  2589. }
  2590. };
  2591. module.$$afterEach = function() {
  2592. if (injectorState.cleanupAfterEach()) {
  2593. module.$$cleanup();
  2594. }
  2595. };
  2596. module.$$cleanup = function() {
  2597. var injector = currentSpec.$injector;
  2598. annotatedFunctions.forEach(function(fn) {
  2599. delete fn.$inject;
  2600. });
  2601. angular.forEach(currentSpec.$modules, function(module) {
  2602. if (module && module.$$hashKey) {
  2603. module.$$hashKey = undefined;
  2604. }
  2605. });
  2606. currentSpec.$injector = null;
  2607. currentSpec.$modules = null;
  2608. currentSpec.$providerInjector = null;
  2609. currentSpec = null;
  2610. if (injector) {
  2611. // Ensure `$rootElement` is instantiated, before checking `originalRootElement`
  2612. var $rootElement = injector.get('$rootElement');
  2613. var rootNode = $rootElement && $rootElement[0];
  2614. var cleanUpNodes = !originalRootElement ? [] : [originalRootElement[0]];
  2615. if (rootNode && (!originalRootElement || rootNode !== originalRootElement[0])) {
  2616. cleanUpNodes.push(rootNode);
  2617. }
  2618. angular.element.cleanData(cleanUpNodes);
  2619. // Ensure `$destroy()` is available, before calling it
  2620. // (a mocked `$rootScope` might not implement it (or not even be an object at all))
  2621. var $rootScope = injector.get('$rootScope');
  2622. if ($rootScope && $rootScope.$destroy) $rootScope.$destroy();
  2623. }
  2624. // clean up jquery's fragment cache
  2625. angular.forEach(angular.element.fragments, function(val, key) {
  2626. delete angular.element.fragments[key];
  2627. });
  2628. MockXhr.$$lastInstance = null;
  2629. angular.forEach(angular.callbacks, function(val, key) {
  2630. delete angular.callbacks[key];
  2631. });
  2632. angular.callbacks.$$counter = 0;
  2633. };
  2634. (window.beforeEach || window.setup)(module.$$beforeEach);
  2635. (window.afterEach || window.teardown)(module.$$afterEach);
  2636. /**
  2637. * @ngdoc function
  2638. * @name angular.mock.inject
  2639. * @description
  2640. *
  2641. * *NOTE*: This function is also published on window for easy access.<br>
  2642. * *NOTE*: This function is declared ONLY WHEN running tests with jasmine or mocha
  2643. *
  2644. * The inject function wraps a function into an injectable function. The inject() creates new
  2645. * instance of {@link auto.$injector $injector} per test, which is then used for
  2646. * resolving references.
  2647. *
  2648. *
  2649. * ## Resolving References (Underscore Wrapping)
  2650. * Often, we would like to inject a reference once, in a `beforeEach()` block and reuse this
  2651. * in multiple `it()` clauses. To be able to do this we must assign the reference to a variable
  2652. * that is declared in the scope of the `describe()` block. Since we would, most likely, want
  2653. * the variable to have the same name of the reference we have a problem, since the parameter
  2654. * to the `inject()` function would hide the outer variable.
  2655. *
  2656. * To help with this, the injected parameters can, optionally, be enclosed with underscores.
  2657. * These are ignored by the injector when the reference name is resolved.
  2658. *
  2659. * For example, the parameter `_myService_` would be resolved as the reference `myService`.
  2660. * Since it is available in the function body as _myService_, we can then assign it to a variable
  2661. * defined in an outer scope.
  2662. *
  2663. * ```
  2664. * // Defined out reference variable outside
  2665. * var myService;
  2666. *
  2667. * // Wrap the parameter in underscores
  2668. * beforeEach( inject( function(_myService_){
  2669. * myService = _myService_;
  2670. * }));
  2671. *
  2672. * // Use myService in a series of tests.
  2673. * it('makes use of myService', function() {
  2674. * myService.doStuff();
  2675. * });
  2676. *
  2677. * ```
  2678. *
  2679. * See also {@link angular.mock.module angular.mock.module}
  2680. *
  2681. * ## Example
  2682. * Example of what a typical jasmine tests looks like with the inject method.
  2683. * ```js
  2684. *
  2685. * angular.module('myApplicationModule', [])
  2686. * .value('mode', 'app')
  2687. * .value('version', 'v1.0.1');
  2688. *
  2689. *
  2690. * describe('MyApp', function() {
  2691. *
  2692. * // You need to load modules that you want to test,
  2693. * // it loads only the "ng" module by default.
  2694. * beforeEach(module('myApplicationModule'));
  2695. *
  2696. *
  2697. * // inject() is used to inject arguments of all given functions
  2698. * it('should provide a version', inject(function(mode, version) {
  2699. * expect(version).toEqual('v1.0.1');
  2700. * expect(mode).toEqual('app');
  2701. * }));
  2702. *
  2703. *
  2704. * // The inject and module method can also be used inside of the it or beforeEach
  2705. * it('should override a version and test the new version is injected', function() {
  2706. * // module() takes functions or strings (module aliases)
  2707. * module(function($provide) {
  2708. * $provide.value('version', 'overridden'); // override version here
  2709. * });
  2710. *
  2711. * inject(function(version) {
  2712. * expect(version).toEqual('overridden');
  2713. * });
  2714. * });
  2715. * });
  2716. *
  2717. * ```
  2718. *
  2719. * @param {...Function} fns any number of functions which will be injected using the injector.
  2720. */
  2721. var ErrorAddingDeclarationLocationStack = function(e, errorForStack) {
  2722. this.message = e.message;
  2723. this.name = e.name;
  2724. if (e.line) this.line = e.line;
  2725. if (e.sourceId) this.sourceId = e.sourceId;
  2726. if (e.stack && errorForStack)
  2727. this.stack = e.stack + '\n' + errorForStack.stack;
  2728. if (e.stackArray) this.stackArray = e.stackArray;
  2729. };
  2730. ErrorAddingDeclarationLocationStack.prototype = Error.prototype;
  2731. window.inject = angular.mock.inject = function() {
  2732. var blockFns = Array.prototype.slice.call(arguments, 0);
  2733. var errorForStack = new Error('Declaration Location');
  2734. // IE10+ and PhanthomJS do not set stack trace information, until the error is thrown
  2735. if (!errorForStack.stack) {
  2736. try {
  2737. throw errorForStack;
  2738. } catch (e) {}
  2739. }
  2740. return wasInjectorCreated() ? workFn.call(currentSpec) : workFn;
  2741. /////////////////////
  2742. function workFn() {
  2743. var modules = currentSpec.$modules || [];
  2744. var strictDi = !!currentSpec.$injectorStrict;
  2745. modules.unshift(['$injector', function($injector) {
  2746. currentSpec.$providerInjector = $injector;
  2747. }]);
  2748. modules.unshift('ngMock');
  2749. modules.unshift('ng');
  2750. var injector = currentSpec.$injector;
  2751. if (!injector) {
  2752. if (strictDi) {
  2753. // If strictDi is enabled, annotate the providerInjector blocks
  2754. angular.forEach(modules, function(moduleFn) {
  2755. if (typeof moduleFn === "function") {
  2756. angular.injector.$$annotate(moduleFn);
  2757. }
  2758. });
  2759. }
  2760. injector = currentSpec.$injector = angular.injector(modules, strictDi);
  2761. currentSpec.$injectorStrict = strictDi;
  2762. }
  2763. for (var i = 0, ii = blockFns.length; i < ii; i++) {
  2764. if (currentSpec.$injectorStrict) {
  2765. // If the injector is strict / strictDi, and the spec wants to inject using automatic
  2766. // annotation, then annotate the function here.
  2767. injector.annotate(blockFns[i]);
  2768. }
  2769. try {
  2770. /* jshint -W040 *//* Jasmine explicitly provides a `this` object when calling functions */
  2771. injector.invoke(blockFns[i] || angular.noop, this);
  2772. /* jshint +W040 */
  2773. } catch (e) {
  2774. if (e.stack && errorForStack) {
  2775. throw new ErrorAddingDeclarationLocationStack(e, errorForStack);
  2776. }
  2777. throw e;
  2778. } finally {
  2779. errorForStack = null;
  2780. }
  2781. }
  2782. }
  2783. };
  2784. angular.mock.inject.strictDi = function(value) {
  2785. value = arguments.length ? !!value : true;
  2786. return wasInjectorCreated() ? workFn() : workFn;
  2787. function workFn() {
  2788. if (value !== currentSpec.$injectorStrict) {
  2789. if (currentSpec.$injector) {
  2790. throw new Error('Injector already created, can not modify strict annotations');
  2791. } else {
  2792. currentSpec.$injectorStrict = value;
  2793. }
  2794. }
  2795. }
  2796. };
  2797. function InjectorState() {
  2798. this.shared = false;
  2799. this.sharedError = null;
  2800. this.cleanupAfterEach = function() {
  2801. return !this.shared || this.sharedError;
  2802. };
  2803. }
  2804. })(window.jasmine || window.mocha);
  2805. })(window, window.angular);