angular-mocks.js 115 KB

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