angular-mocks.js 101 KB

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