angular-mocks.js 116 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408
  1. /**
  2. * @license AngularJS v1.6.1
  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. * Depending on the value of
  1929. * {@link ng.$compileProvider#preAssignBindingsEnabled `preAssignBindingsEnabled()`}, the properties
  1930. * will be bound before or after invoking the constructor.
  1931. *
  1932. *
  1933. * ## Example
  1934. *
  1935. * ```js
  1936. *
  1937. * // Directive definition ...
  1938. *
  1939. * myMod.directive('myDirective', {
  1940. * controller: 'MyDirectiveController',
  1941. * bindToController: {
  1942. * name: '@'
  1943. * }
  1944. * });
  1945. *
  1946. *
  1947. * // Controller definition ...
  1948. *
  1949. * myMod.controller('MyDirectiveController', ['$log', function($log) {
  1950. * this.log = function() {
  1951. * $log.info(this.name);
  1952. * };
  1953. * }]);
  1954. *
  1955. *
  1956. * // In a test ...
  1957. *
  1958. * describe('myDirectiveController', function() {
  1959. * describe('log()', function() {
  1960. * it('should write the bound name to the log', inject(function($controller, $log) {
  1961. * var ctrl = $controller('MyDirectiveController', { /* no locals &#42;/ }, { name: 'Clark Kent' });
  1962. * ctrl.log();
  1963. *
  1964. * expect(ctrl.name).toEqual('Clark Kent');
  1965. * expect($log.info.logs).toEqual(['Clark Kent']);
  1966. * }));
  1967. * });
  1968. * });
  1969. *
  1970. * ```
  1971. *
  1972. * @param {Function|string} constructor If called with a function then it's considered to be the
  1973. * controller constructor function. Otherwise it's considered to be a string which is used
  1974. * to retrieve the controller constructor using the following steps:
  1975. *
  1976. * * check if a controller with given name is registered via `$controllerProvider`
  1977. * * check if evaluating the string on the current scope returns a constructor
  1978. * * if $controllerProvider#allowGlobals, check `window[constructor]` on the global
  1979. * `window` object (deprecated, not recommended)
  1980. *
  1981. * The string can use the `controller as property` syntax, where the controller instance is published
  1982. * as the specified property on the `scope`; the `scope` must be injected into `locals` param for this
  1983. * to work correctly.
  1984. *
  1985. * @param {Object} locals Injection locals for Controller.
  1986. * @param {Object=} bindings Properties to add to the controller instance. This is used to simulate
  1987. * the `bindToController` feature and simplify certain kinds of tests.
  1988. * @return {Object} Instance of given controller.
  1989. */
  1990. function createControllerDecorator(compileProvider) {
  1991. angular.mock.$ControllerDecorator = ['$delegate', function($delegate) {
  1992. return function(expression, locals, later, ident) {
  1993. if (later && typeof later === 'object') {
  1994. var preAssignBindingsEnabled = compileProvider.preAssignBindingsEnabled();
  1995. var instantiate = $delegate(expression, locals, true, ident);
  1996. if (preAssignBindingsEnabled) {
  1997. angular.extend(instantiate.instance, later);
  1998. }
  1999. var instance = instantiate();
  2000. if (!preAssignBindingsEnabled || instance !== instantiate.instance) {
  2001. angular.extend(instance, later);
  2002. }
  2003. return instance;
  2004. }
  2005. return $delegate(expression, locals, later, ident);
  2006. };
  2007. }];
  2008. return angular.mock.$ControllerDecorator;
  2009. }
  2010. /**
  2011. * @ngdoc service
  2012. * @name $componentController
  2013. * @description
  2014. * A service that can be used to create instances of component controllers. Useful for unit-testing.
  2015. *
  2016. * Be aware that the controller will be instantiated and attached to the scope as specified in
  2017. * the component definition object. If you do not provide a `$scope` object in the `locals` param
  2018. * then the helper will create a new isolated scope as a child of `$rootScope`.
  2019. *
  2020. * If you are using `$element` or `$attrs` in the controller, make sure to provide them as `locals`.
  2021. * The `$element` must be a jqLite-wrapped DOM element, and `$attrs` should be an object that
  2022. * has all properties / functions that you are using in the controller. If this is getting too complex,
  2023. * you should compile the component instead and access the component's controller via the
  2024. * {@link angular.element#methods `controller`} function.
  2025. *
  2026. * See also the section on {@link guide/component#unit-testing-component-controllers unit-testing component controllers}
  2027. * in the guide.
  2028. *
  2029. * @param {string} componentName the name of the component whose controller we want to instantiate
  2030. * @param {Object} locals Injection locals for Controller.
  2031. * @param {Object=} bindings Properties to add to the controller before invoking the constructor. This is used
  2032. * to simulate the `bindToController` feature and simplify certain kinds of tests.
  2033. * @param {string=} ident Override the property name to use when attaching the controller to the scope.
  2034. * @return {Object} Instance of requested controller.
  2035. */
  2036. angular.mock.$ComponentControllerProvider = ['$compileProvider',
  2037. function ComponentControllerProvider($compileProvider) {
  2038. this.$get = ['$controller','$injector', '$rootScope', function($controller, $injector, $rootScope) {
  2039. return function $componentController(componentName, locals, bindings, ident) {
  2040. // get all directives associated to the component name
  2041. var directives = $injector.get(componentName + 'Directive');
  2042. // look for those directives that are components
  2043. var candidateDirectives = directives.filter(function(directiveInfo) {
  2044. // components have controller, controllerAs and restrict:'E'
  2045. return directiveInfo.controller && directiveInfo.controllerAs && directiveInfo.restrict === 'E';
  2046. });
  2047. // check if valid directives found
  2048. if (candidateDirectives.length === 0) {
  2049. throw new Error('No component found');
  2050. }
  2051. if (candidateDirectives.length > 1) {
  2052. throw new Error('Too many components found');
  2053. }
  2054. // get the info of the component
  2055. var directiveInfo = candidateDirectives[0];
  2056. // create a scope if needed
  2057. locals = locals || {};
  2058. locals.$scope = locals.$scope || $rootScope.$new(true);
  2059. return $controller(directiveInfo.controller, locals, bindings, ident || directiveInfo.controllerAs);
  2060. };
  2061. }];
  2062. }];
  2063. /**
  2064. * @ngdoc module
  2065. * @name ngMock
  2066. * @packageName angular-mocks
  2067. * @description
  2068. *
  2069. * # ngMock
  2070. *
  2071. * The `ngMock` module provides support to inject and mock Angular services into unit tests.
  2072. * In addition, ngMock also extends various core ng services such that they can be
  2073. * inspected and controlled in a synchronous manner within test code.
  2074. *
  2075. *
  2076. * <div doc-module-components="ngMock"></div>
  2077. *
  2078. * @installation
  2079. *
  2080. * First, download the file:
  2081. * * [Google CDN](https://developers.google.com/speed/libraries/devguide#angularjs) e.g.
  2082. * `"//ajax.googleapis.com/ajax/libs/angularjs/X.Y.Z/angular-mocks.js"`
  2083. * * [NPM](https://www.npmjs.com/) e.g. `npm install angular-mocks@X.Y.Z`
  2084. * * [Yarn](https://yarnpkg.com) e.g. `yarn add angular-mocks@X.Y.Z`
  2085. * * [Bower](http://bower.io) e.g. `bower install angular-mocks#X.Y.Z`
  2086. * * [code.angularjs.org](https://code.angularjs.org/) (discouraged for production use) e.g.
  2087. * `"//code.angularjs.org/X.Y.Z/angular-mocks.js"`
  2088. *
  2089. * where X.Y.Z is the AngularJS version you are running.
  2090. *
  2091. * Then, configure your test runner to load `angular-mocks.js` after `angular.js`.
  2092. * This example uses <a href="http://karma-runner.github.io/">Karma</a>:
  2093. *
  2094. * ```
  2095. * config.set({
  2096. * files: [
  2097. * 'build/angular.js', // and other module files you need
  2098. * 'build/angular-mocks.js',
  2099. * '<path/to/application/files>',
  2100. * '<path/to/spec/files>'
  2101. * ]
  2102. * });
  2103. * ```
  2104. *
  2105. * Including the `angular-mocks.js` file automatically adds the `ngMock` module, so your tests
  2106. * are ready to go!
  2107. */
  2108. angular.module('ngMock', ['ng']).provider({
  2109. $browser: angular.mock.$BrowserProvider,
  2110. $exceptionHandler: angular.mock.$ExceptionHandlerProvider,
  2111. $log: angular.mock.$LogProvider,
  2112. $interval: angular.mock.$IntervalProvider,
  2113. $httpBackend: angular.mock.$HttpBackendProvider,
  2114. $rootElement: angular.mock.$RootElementProvider,
  2115. $componentController: angular.mock.$ComponentControllerProvider
  2116. }).config(['$provide', '$compileProvider', function($provide, $compileProvider) {
  2117. $provide.decorator('$timeout', angular.mock.$TimeoutDecorator);
  2118. $provide.decorator('$$rAF', angular.mock.$RAFDecorator);
  2119. $provide.decorator('$rootScope', angular.mock.$RootScopeDecorator);
  2120. $provide.decorator('$controller', createControllerDecorator($compileProvider));
  2121. }]);
  2122. /**
  2123. * @ngdoc module
  2124. * @name ngMockE2E
  2125. * @module ngMockE2E
  2126. * @packageName angular-mocks
  2127. * @description
  2128. *
  2129. * The `ngMockE2E` is an angular module which contains mocks suitable for end-to-end testing.
  2130. * Currently there is only one mock present in this module -
  2131. * the {@link ngMockE2E.$httpBackend e2e $httpBackend} mock.
  2132. */
  2133. angular.module('ngMockE2E', ['ng']).config(['$provide', function($provide) {
  2134. $provide.value('$httpBackend', angular.injector(['ng']).get('$httpBackend'));
  2135. $provide.decorator('$httpBackend', angular.mock.e2e.$httpBackendDecorator);
  2136. }]);
  2137. /**
  2138. * @ngdoc service
  2139. * @name $httpBackend
  2140. * @module ngMockE2E
  2141. * @description
  2142. * Fake HTTP backend implementation suitable for end-to-end testing or backend-less development of
  2143. * applications that use the {@link ng.$http $http service}.
  2144. *
  2145. * <div class="alert alert-info">
  2146. * **Note**: For fake http backend implementation suitable for unit testing please see
  2147. * {@link ngMock.$httpBackend unit-testing $httpBackend mock}.
  2148. * </div>
  2149. *
  2150. * This implementation can be used to respond with static or dynamic responses via the `when` api
  2151. * and its shortcuts (`whenGET`, `whenPOST`, etc) and optionally pass through requests to the
  2152. * real $httpBackend for specific requests (e.g. to interact with certain remote apis or to fetch
  2153. * templates from a webserver).
  2154. *
  2155. * As opposed to unit-testing, in an end-to-end testing scenario or in scenario when an application
  2156. * is being developed with the real backend api replaced with a mock, it is often desirable for
  2157. * certain category of requests to bypass the mock and issue a real http request (e.g. to fetch
  2158. * templates or static files from the webserver). To configure the backend with this behavior
  2159. * use the `passThrough` request handler of `when` instead of `respond`.
  2160. *
  2161. * Additionally, we don't want to manually have to flush mocked out requests like we do during unit
  2162. * testing. For this reason the e2e $httpBackend flushes mocked out requests
  2163. * automatically, closely simulating the behavior of the XMLHttpRequest object.
  2164. *
  2165. * To setup the application to run with this http backend, you have to create a module that depends
  2166. * on the `ngMockE2E` and your application modules and defines the fake backend:
  2167. *
  2168. * ```js
  2169. * var myAppDev = angular.module('myAppDev', ['myApp', 'ngMockE2E']);
  2170. * myAppDev.run(function($httpBackend) {
  2171. * var phones = [{name: 'phone1'}, {name: 'phone2'}];
  2172. *
  2173. * // returns the current list of phones
  2174. * $httpBackend.whenGET('/phones').respond(phones);
  2175. *
  2176. * // adds a new phone to the phones array
  2177. * $httpBackend.whenPOST('/phones').respond(function(method, url, data) {
  2178. * var phone = angular.fromJson(data);
  2179. * phones.push(phone);
  2180. * return [200, phone, {}];
  2181. * });
  2182. * $httpBackend.whenGET(/^\/templates\//).passThrough(); // Requests for templates are handled by the real server
  2183. * //...
  2184. * });
  2185. * ```
  2186. *
  2187. * Afterwards, bootstrap your app with this new module.
  2188. *
  2189. * ## Example
  2190. * <example name="httpbackend-e2e-testing" module="myAppE2E" deps="angular-mocks.js">
  2191. * <file name="app.js">
  2192. * var myApp = angular.module('myApp', []);
  2193. *
  2194. * myApp.controller('MainCtrl', function MainCtrl($http) {
  2195. * var ctrl = this;
  2196. *
  2197. * ctrl.phones = [];
  2198. * ctrl.newPhone = {
  2199. * name: ''
  2200. * };
  2201. *
  2202. * ctrl.getPhones = function() {
  2203. * $http.get('/phones').then(function(response) {
  2204. * ctrl.phones = response.data;
  2205. * });
  2206. * };
  2207. *
  2208. * ctrl.addPhone = function(phone) {
  2209. * $http.post('/phones', phone).then(function() {
  2210. * ctrl.newPhone = {name: ''};
  2211. * return ctrl.getPhones();
  2212. * });
  2213. * };
  2214. *
  2215. * ctrl.getPhones();
  2216. * });
  2217. * </file>
  2218. * <file name="e2e.js">
  2219. * var myAppDev = angular.module('myAppE2E', ['myApp', 'ngMockE2E']);
  2220. *
  2221. * myAppDev.run(function($httpBackend) {
  2222. * var phones = [{name: 'phone1'}, {name: 'phone2'}];
  2223. *
  2224. * // returns the current list of phones
  2225. * $httpBackend.whenGET('/phones').respond(phones);
  2226. *
  2227. * // adds a new phone to the phones array
  2228. * $httpBackend.whenPOST('/phones').respond(function(method, url, data) {
  2229. * var phone = angular.fromJson(data);
  2230. * phones.push(phone);
  2231. * return [200, phone, {}];
  2232. * });
  2233. * });
  2234. * </file>
  2235. * <file name="index.html">
  2236. * <div ng-controller="MainCtrl as $ctrl">
  2237. * <form name="newPhoneForm" ng-submit="$ctrl.addPhone($ctrl.newPhone)">
  2238. * <input type="text" ng-model="$ctrl.newPhone.name">
  2239. * <input type="submit" value="Add Phone">
  2240. * </form>
  2241. * <h1>Phones</h1>
  2242. * <ul>
  2243. * <li ng-repeat="phone in $ctrl.phones">{{phone.name}}</li>
  2244. * </ul>
  2245. * </div>
  2246. * </file>
  2247. * </example>
  2248. *
  2249. *
  2250. */
  2251. /**
  2252. * @ngdoc method
  2253. * @name $httpBackend#when
  2254. * @module ngMockE2E
  2255. * @description
  2256. * Creates a new backend definition.
  2257. *
  2258. * @param {string} method HTTP method.
  2259. * @param {string|RegExp|function(string)=} url HTTP url or function that receives a url
  2260. * and returns true if the url matches the current definition.
  2261. * @param {(string|RegExp|function(string))=} data HTTP request body or function that receives
  2262. * data string and returns true if the data is as expected.
  2263. * @param {(Object|function(Object))=} headers HTTP headers or function that receives http header
  2264. * object and returns true if the headers match the current definition.
  2265. * @param {(Array)=} keys Array of keys to assign to regex matches in request url described on
  2266. * {@link ngMock.$httpBackend $httpBackend mock}.
  2267. * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
  2268. * control how a matched request is handled. You can save this object for later use and invoke
  2269. * `respond` or `passThrough` again in order to change how a matched request is handled.
  2270. *
  2271. * - respond –
  2272. * ```
  2273. * { function([status,] data[, headers, statusText])
  2274. * | function(function(method, url, data, headers, params)}
  2275. * ```
  2276. * – The respond method takes a set of static data to be returned or a function that can return
  2277. * an array containing response status (number), response data (Array|Object|string), response
  2278. * headers (Object), and the text for the status (string).
  2279. * - passThrough – `{function()}` – Any request matching a backend definition with
  2280. * `passThrough` handler will be passed through to the real backend (an XHR request will be made
  2281. * to the server.)
  2282. * - Both methods return the `requestHandler` object for possible overrides.
  2283. */
  2284. /**
  2285. * @ngdoc method
  2286. * @name $httpBackend#whenGET
  2287. * @module ngMockE2E
  2288. * @description
  2289. * Creates a new backend definition for GET requests. For more info see `when()`.
  2290. *
  2291. * @param {string|RegExp|function(string)=} url HTTP url or function that receives a url
  2292. * and returns true if the url matches the current definition.
  2293. * @param {(Object|function(Object))=} headers HTTP headers.
  2294. * @param {(Array)=} keys Array of keys to assign to regex matches in request url described on
  2295. * {@link ngMock.$httpBackend $httpBackend mock}.
  2296. * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
  2297. * control how a matched request is handled. You can save this object for later use and invoke
  2298. * `respond` or `passThrough` again in order to change how a matched request is handled.
  2299. */
  2300. /**
  2301. * @ngdoc method
  2302. * @name $httpBackend#whenHEAD
  2303. * @module ngMockE2E
  2304. * @description
  2305. * Creates a new backend definition for HEAD requests. For more info see `when()`.
  2306. *
  2307. * @param {string|RegExp|function(string)=} url HTTP url or function that receives a url
  2308. * and returns true if the url matches the current definition.
  2309. * @param {(Object|function(Object))=} headers HTTP headers.
  2310. * @param {(Array)=} keys Array of keys to assign to regex matches in request url described on
  2311. * {@link ngMock.$httpBackend $httpBackend mock}.
  2312. * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
  2313. * control how a matched request is handled. You can save this object for later use and invoke
  2314. * `respond` or `passThrough` again in order to change how a matched request is handled.
  2315. */
  2316. /**
  2317. * @ngdoc method
  2318. * @name $httpBackend#whenDELETE
  2319. * @module ngMockE2E
  2320. * @description
  2321. * Creates a new backend definition for DELETE requests. For more info see `when()`.
  2322. *
  2323. * @param {string|RegExp|function(string)=} url HTTP url or function that receives a url
  2324. * and returns true if the url matches the current definition.
  2325. * @param {(Object|function(Object))=} headers HTTP headers.
  2326. * @param {(Array)=} keys Array of keys to assign to regex matches in request url described on
  2327. * {@link ngMock.$httpBackend $httpBackend mock}.
  2328. * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
  2329. * control how a matched request is handled. You can save this object for later use and invoke
  2330. * `respond` or `passThrough` again in order to change how a matched request is handled.
  2331. */
  2332. /**
  2333. * @ngdoc method
  2334. * @name $httpBackend#whenPOST
  2335. * @module ngMockE2E
  2336. * @description
  2337. * Creates a new backend definition for POST requests. For more info see `when()`.
  2338. *
  2339. * @param {string|RegExp|function(string)=} url HTTP url or function that receives a url
  2340. * and returns true if the url matches the current definition.
  2341. * @param {(string|RegExp|function(string))=} data HTTP request body or function that receives
  2342. * data string and returns true if the data is as expected.
  2343. * @param {(Object|function(Object))=} headers HTTP headers.
  2344. * @param {(Array)=} keys Array of keys to assign to regex matches in request url described on
  2345. * {@link ngMock.$httpBackend $httpBackend mock}.
  2346. * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
  2347. * control how a matched request is handled. You can save this object for later use and invoke
  2348. * `respond` or `passThrough` again in order to change how a matched request is handled.
  2349. */
  2350. /**
  2351. * @ngdoc method
  2352. * @name $httpBackend#whenPUT
  2353. * @module ngMockE2E
  2354. * @description
  2355. * Creates a new backend definition for PUT requests. For more info see `when()`.
  2356. *
  2357. * @param {string|RegExp|function(string)=} url HTTP url or function that receives a url
  2358. * and returns true if the url matches the current definition.
  2359. * @param {(string|RegExp|function(string))=} data HTTP request body or function that receives
  2360. * data string and returns true if the data is as expected.
  2361. * @param {(Object|function(Object))=} headers HTTP headers.
  2362. * @param {(Array)=} keys Array of keys to assign to regex matches in request url described on
  2363. * {@link ngMock.$httpBackend $httpBackend mock}.
  2364. * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
  2365. * control how a matched request is handled. You can save this object for later use and invoke
  2366. * `respond` or `passThrough` again in order to change how a matched request is handled.
  2367. */
  2368. /**
  2369. * @ngdoc method
  2370. * @name $httpBackend#whenPATCH
  2371. * @module ngMockE2E
  2372. * @description
  2373. * Creates a new backend definition for PATCH requests. For more info see `when()`.
  2374. *
  2375. * @param {string|RegExp|function(string)=} url HTTP url or function that receives a url
  2376. * and returns true if the url matches the current definition.
  2377. * @param {(string|RegExp|function(string))=} data HTTP request body or function that receives
  2378. * data string and returns true if the data is as expected.
  2379. * @param {(Object|function(Object))=} headers HTTP headers.
  2380. * @param {(Array)=} keys Array of keys to assign to regex matches in request url described on
  2381. * {@link ngMock.$httpBackend $httpBackend mock}.
  2382. * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
  2383. * control how a matched request is handled. You can save this object for later use and invoke
  2384. * `respond` or `passThrough` again in order to change how a matched request is handled.
  2385. */
  2386. /**
  2387. * @ngdoc method
  2388. * @name $httpBackend#whenJSONP
  2389. * @module ngMockE2E
  2390. * @description
  2391. * Creates a new backend definition for JSONP requests. For more info see `when()`.
  2392. *
  2393. * @param {string|RegExp|function(string)=} url HTTP url or function that receives a url
  2394. * and returns true if the url matches the current definition.
  2395. * @param {(Array)=} keys Array of keys to assign to regex matches in request url described on
  2396. * {@link ngMock.$httpBackend $httpBackend mock}.
  2397. * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
  2398. * control how a matched request is handled. You can save this object for later use and invoke
  2399. * `respond` or `passThrough` again in order to change how a matched request is handled.
  2400. */
  2401. /**
  2402. * @ngdoc method
  2403. * @name $httpBackend#whenRoute
  2404. * @module ngMockE2E
  2405. * @description
  2406. * Creates a new backend definition that compares only with the requested route.
  2407. *
  2408. * @param {string} method HTTP method.
  2409. * @param {string} url HTTP url string that supports colon param matching.
  2410. * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
  2411. * control how a matched request is handled. You can save this object for later use and invoke
  2412. * `respond` or `passThrough` again in order to change how a matched request is handled.
  2413. */
  2414. angular.mock.e2e = {};
  2415. angular.mock.e2e.$httpBackendDecorator =
  2416. ['$rootScope', '$timeout', '$delegate', '$browser', createHttpBackendMock];
  2417. /**
  2418. * @ngdoc type
  2419. * @name $rootScope.Scope
  2420. * @module ngMock
  2421. * @description
  2422. * {@link ng.$rootScope.Scope Scope} type decorated with helper methods useful for testing. These
  2423. * methods are automatically available on any {@link ng.$rootScope.Scope Scope} instance when
  2424. * `ngMock` module is loaded.
  2425. *
  2426. * In addition to all the regular `Scope` methods, the following helper methods are available:
  2427. */
  2428. angular.mock.$RootScopeDecorator = ['$delegate', function($delegate) {
  2429. var $rootScopePrototype = Object.getPrototypeOf($delegate);
  2430. $rootScopePrototype.$countChildScopes = countChildScopes;
  2431. $rootScopePrototype.$countWatchers = countWatchers;
  2432. return $delegate;
  2433. // ------------------------------------------------------------------------------------------ //
  2434. /**
  2435. * @ngdoc method
  2436. * @name $rootScope.Scope#$countChildScopes
  2437. * @module ngMock
  2438. * @this $rootScope.Scope
  2439. * @description
  2440. * Counts all the direct and indirect child scopes of the current scope.
  2441. *
  2442. * The current scope is excluded from the count. The count includes all isolate child scopes.
  2443. *
  2444. * @returns {number} Total number of child scopes.
  2445. */
  2446. function countChildScopes() {
  2447. var count = 0; // exclude the current scope
  2448. var pendingChildHeads = [this.$$childHead];
  2449. var currentScope;
  2450. while (pendingChildHeads.length) {
  2451. currentScope = pendingChildHeads.shift();
  2452. while (currentScope) {
  2453. count += 1;
  2454. pendingChildHeads.push(currentScope.$$childHead);
  2455. currentScope = currentScope.$$nextSibling;
  2456. }
  2457. }
  2458. return count;
  2459. }
  2460. /**
  2461. * @ngdoc method
  2462. * @name $rootScope.Scope#$countWatchers
  2463. * @this $rootScope.Scope
  2464. * @module ngMock
  2465. * @description
  2466. * Counts all the watchers of direct and indirect child scopes of the current scope.
  2467. *
  2468. * The watchers of the current scope are included in the count and so are all the watchers of
  2469. * isolate child scopes.
  2470. *
  2471. * @returns {number} Total number of watchers.
  2472. */
  2473. function countWatchers() {
  2474. var count = this.$$watchers ? this.$$watchers.length : 0; // include the current scope
  2475. var pendingChildHeads = [this.$$childHead];
  2476. var currentScope;
  2477. while (pendingChildHeads.length) {
  2478. currentScope = pendingChildHeads.shift();
  2479. while (currentScope) {
  2480. count += currentScope.$$watchers ? currentScope.$$watchers.length : 0;
  2481. pendingChildHeads.push(currentScope.$$childHead);
  2482. currentScope = currentScope.$$nextSibling;
  2483. }
  2484. }
  2485. return count;
  2486. }
  2487. }];
  2488. (function(jasmineOrMocha) {
  2489. if (!jasmineOrMocha) {
  2490. return;
  2491. }
  2492. var currentSpec = null,
  2493. injectorState = new InjectorState(),
  2494. annotatedFunctions = [],
  2495. wasInjectorCreated = function() {
  2496. return !!currentSpec;
  2497. };
  2498. angular.mock.$$annotate = angular.injector.$$annotate;
  2499. angular.injector.$$annotate = function(fn) {
  2500. if (typeof fn === 'function' && !fn.$inject) {
  2501. annotatedFunctions.push(fn);
  2502. }
  2503. return angular.mock.$$annotate.apply(this, arguments);
  2504. };
  2505. /**
  2506. * @ngdoc function
  2507. * @name angular.mock.module
  2508. * @description
  2509. *
  2510. * *NOTE*: This function is also published on window for easy access.<br>
  2511. * *NOTE*: This function is declared ONLY WHEN running tests with jasmine or mocha
  2512. *
  2513. * This function registers a module configuration code. It collects the configuration information
  2514. * which will be used when the injector is created by {@link angular.mock.inject inject}.
  2515. *
  2516. * See {@link angular.mock.inject inject} for usage example
  2517. *
  2518. * @param {...(string|Function|Object)} fns any number of modules which are represented as string
  2519. * aliases or as anonymous module initialization functions. The modules are used to
  2520. * configure the injector. The 'ng' and 'ngMock' modules are automatically loaded. If an
  2521. * object literal is passed each key-value pair will be registered on the module via
  2522. * {@link auto.$provide $provide}.value, the key being the string name (or token) to associate
  2523. * with the value on the injector.
  2524. */
  2525. var module = window.module = angular.mock.module = function() {
  2526. var moduleFns = Array.prototype.slice.call(arguments, 0);
  2527. return wasInjectorCreated() ? workFn() : workFn;
  2528. /////////////////////
  2529. function workFn() {
  2530. if (currentSpec.$injector) {
  2531. throw new Error('Injector already created, can not register a module!');
  2532. } else {
  2533. var fn, modules = currentSpec.$modules || (currentSpec.$modules = []);
  2534. angular.forEach(moduleFns, function(module) {
  2535. if (angular.isObject(module) && !angular.isArray(module)) {
  2536. fn = ['$provide', function($provide) {
  2537. angular.forEach(module, function(value, key) {
  2538. $provide.value(key, value);
  2539. });
  2540. }];
  2541. } else {
  2542. fn = module;
  2543. }
  2544. if (currentSpec.$providerInjector) {
  2545. currentSpec.$providerInjector.invoke(fn);
  2546. } else {
  2547. modules.push(fn);
  2548. }
  2549. });
  2550. }
  2551. }
  2552. };
  2553. module.$$beforeAllHook = (window.before || window.beforeAll);
  2554. module.$$afterAllHook = (window.after || window.afterAll);
  2555. // purely for testing ngMock itself
  2556. module.$$currentSpec = function(to) {
  2557. if (arguments.length === 0) return to;
  2558. currentSpec = to;
  2559. };
  2560. /**
  2561. * @ngdoc function
  2562. * @name angular.mock.module.sharedInjector
  2563. * @description
  2564. *
  2565. * *NOTE*: This function is declared ONLY WHEN running tests with jasmine or mocha
  2566. *
  2567. * This function ensures a single injector will be used for all tests in a given describe context.
  2568. * This contrasts with the default behaviour where a new injector is created per test case.
  2569. *
  2570. * Use sharedInjector when you want to take advantage of Jasmine's `beforeAll()`, or mocha's
  2571. * `before()` methods. Call `module.sharedInjector()` before you setup any other hooks that
  2572. * will create (i.e call `module()`) or use (i.e call `inject()`) the injector.
  2573. *
  2574. * You cannot call `sharedInjector()` from within a context already using `sharedInjector()`.
  2575. *
  2576. * ## Example
  2577. *
  2578. * Typically beforeAll is used to make many assertions about a single operation. This can
  2579. * cut down test run-time as the test setup doesn't need to be re-run, and enabling focussed
  2580. * tests each with a single assertion.
  2581. *
  2582. * ```js
  2583. * describe("Deep Thought", function() {
  2584. *
  2585. * module.sharedInjector();
  2586. *
  2587. * beforeAll(module("UltimateQuestion"));
  2588. *
  2589. * beforeAll(inject(function(DeepThought) {
  2590. * expect(DeepThought.answer).toBeUndefined();
  2591. * DeepThought.generateAnswer();
  2592. * }));
  2593. *
  2594. * it("has calculated the answer correctly", inject(function(DeepThought) {
  2595. * // Because of sharedInjector, we have access to the instance of the DeepThought service
  2596. * // that was provided to the beforeAll() hook. Therefore we can test the generated answer
  2597. * expect(DeepThought.answer).toBe(42);
  2598. * }));
  2599. *
  2600. * it("has calculated the answer within the expected time", inject(function(DeepThought) {
  2601. * expect(DeepThought.runTimeMillennia).toBeLessThan(8000);
  2602. * }));
  2603. *
  2604. * it("has double checked the answer", inject(function(DeepThought) {
  2605. * expect(DeepThought.absolutelySureItIsTheRightAnswer).toBe(true);
  2606. * }));
  2607. *
  2608. * });
  2609. *
  2610. * ```
  2611. */
  2612. module.sharedInjector = function() {
  2613. if (!(module.$$beforeAllHook && module.$$afterAllHook)) {
  2614. throw Error('sharedInjector() cannot be used unless your test runner defines beforeAll/afterAll');
  2615. }
  2616. var initialized = false;
  2617. module.$$beforeAllHook(/** @this */ function() {
  2618. if (injectorState.shared) {
  2619. injectorState.sharedError = Error('sharedInjector() cannot be called inside a context that has already called sharedInjector()');
  2620. throw injectorState.sharedError;
  2621. }
  2622. initialized = true;
  2623. currentSpec = this;
  2624. injectorState.shared = true;
  2625. });
  2626. module.$$afterAllHook(function() {
  2627. if (initialized) {
  2628. injectorState = new InjectorState();
  2629. module.$$cleanup();
  2630. } else {
  2631. injectorState.sharedError = null;
  2632. }
  2633. });
  2634. };
  2635. module.$$beforeEach = function() {
  2636. if (injectorState.shared && currentSpec && currentSpec !== this) {
  2637. var state = currentSpec;
  2638. currentSpec = this;
  2639. angular.forEach(['$injector','$modules','$providerInjector', '$injectorStrict'], function(k) {
  2640. currentSpec[k] = state[k];
  2641. state[k] = null;
  2642. });
  2643. } else {
  2644. currentSpec = this;
  2645. originalRootElement = null;
  2646. annotatedFunctions = [];
  2647. }
  2648. };
  2649. module.$$afterEach = function() {
  2650. if (injectorState.cleanupAfterEach()) {
  2651. module.$$cleanup();
  2652. }
  2653. };
  2654. module.$$cleanup = function() {
  2655. var injector = currentSpec.$injector;
  2656. annotatedFunctions.forEach(function(fn) {
  2657. delete fn.$inject;
  2658. });
  2659. angular.forEach(currentSpec.$modules, function(module) {
  2660. if (module && module.$$hashKey) {
  2661. module.$$hashKey = undefined;
  2662. }
  2663. });
  2664. currentSpec.$injector = null;
  2665. currentSpec.$modules = null;
  2666. currentSpec.$providerInjector = null;
  2667. currentSpec = null;
  2668. if (injector) {
  2669. // Ensure `$rootElement` is instantiated, before checking `originalRootElement`
  2670. var $rootElement = injector.get('$rootElement');
  2671. var rootNode = $rootElement && $rootElement[0];
  2672. var cleanUpNodes = !originalRootElement ? [] : [originalRootElement[0]];
  2673. if (rootNode && (!originalRootElement || rootNode !== originalRootElement[0])) {
  2674. cleanUpNodes.push(rootNode);
  2675. }
  2676. angular.element.cleanData(cleanUpNodes);
  2677. // Ensure `$destroy()` is available, before calling it
  2678. // (a mocked `$rootScope` might not implement it (or not even be an object at all))
  2679. var $rootScope = injector.get('$rootScope');
  2680. if ($rootScope && $rootScope.$destroy) $rootScope.$destroy();
  2681. }
  2682. // clean up jquery's fragment cache
  2683. angular.forEach(angular.element.fragments, function(val, key) {
  2684. delete angular.element.fragments[key];
  2685. });
  2686. MockXhr.$$lastInstance = null;
  2687. angular.forEach(angular.callbacks, function(val, key) {
  2688. delete angular.callbacks[key];
  2689. });
  2690. angular.callbacks.$$counter = 0;
  2691. };
  2692. (window.beforeEach || window.setup)(module.$$beforeEach);
  2693. (window.afterEach || window.teardown)(module.$$afterEach);
  2694. /**
  2695. * @ngdoc function
  2696. * @name angular.mock.inject
  2697. * @description
  2698. *
  2699. * *NOTE*: This function is also published on window for easy access.<br>
  2700. * *NOTE*: This function is declared ONLY WHEN running tests with jasmine or mocha
  2701. *
  2702. * The inject function wraps a function into an injectable function. The inject() creates new
  2703. * instance of {@link auto.$injector $injector} per test, which is then used for
  2704. * resolving references.
  2705. *
  2706. *
  2707. * ## Resolving References (Underscore Wrapping)
  2708. * Often, we would like to inject a reference once, in a `beforeEach()` block and reuse this
  2709. * in multiple `it()` clauses. To be able to do this we must assign the reference to a variable
  2710. * that is declared in the scope of the `describe()` block. Since we would, most likely, want
  2711. * the variable to have the same name of the reference we have a problem, since the parameter
  2712. * to the `inject()` function would hide the outer variable.
  2713. *
  2714. * To help with this, the injected parameters can, optionally, be enclosed with underscores.
  2715. * These are ignored by the injector when the reference name is resolved.
  2716. *
  2717. * For example, the parameter `_myService_` would be resolved as the reference `myService`.
  2718. * Since it is available in the function body as `_myService_`, we can then assign it to a variable
  2719. * defined in an outer scope.
  2720. *
  2721. * ```
  2722. * // Defined out reference variable outside
  2723. * var myService;
  2724. *
  2725. * // Wrap the parameter in underscores
  2726. * beforeEach( inject( function(_myService_){
  2727. * myService = _myService_;
  2728. * }));
  2729. *
  2730. * // Use myService in a series of tests.
  2731. * it('makes use of myService', function() {
  2732. * myService.doStuff();
  2733. * });
  2734. *
  2735. * ```
  2736. *
  2737. * See also {@link angular.mock.module angular.mock.module}
  2738. *
  2739. * ## Example
  2740. * Example of what a typical jasmine tests looks like with the inject method.
  2741. * ```js
  2742. *
  2743. * angular.module('myApplicationModule', [])
  2744. * .value('mode', 'app')
  2745. * .value('version', 'v1.0.1');
  2746. *
  2747. *
  2748. * describe('MyApp', function() {
  2749. *
  2750. * // You need to load modules that you want to test,
  2751. * // it loads only the "ng" module by default.
  2752. * beforeEach(module('myApplicationModule'));
  2753. *
  2754. *
  2755. * // inject() is used to inject arguments of all given functions
  2756. * it('should provide a version', inject(function(mode, version) {
  2757. * expect(version).toEqual('v1.0.1');
  2758. * expect(mode).toEqual('app');
  2759. * }));
  2760. *
  2761. *
  2762. * // The inject and module method can also be used inside of the it or beforeEach
  2763. * it('should override a version and test the new version is injected', function() {
  2764. * // module() takes functions or strings (module aliases)
  2765. * module(function($provide) {
  2766. * $provide.value('version', 'overridden'); // override version here
  2767. * });
  2768. *
  2769. * inject(function(version) {
  2770. * expect(version).toEqual('overridden');
  2771. * });
  2772. * });
  2773. * });
  2774. *
  2775. * ```
  2776. *
  2777. * @param {...Function} fns any number of functions which will be injected using the injector.
  2778. */
  2779. var ErrorAddingDeclarationLocationStack = function ErrorAddingDeclarationLocationStack(e, errorForStack) {
  2780. this.message = e.message;
  2781. this.name = e.name;
  2782. if (e.line) this.line = e.line;
  2783. if (e.sourceId) this.sourceId = e.sourceId;
  2784. if (e.stack && errorForStack)
  2785. this.stack = e.stack + '\n' + errorForStack.stack;
  2786. if (e.stackArray) this.stackArray = e.stackArray;
  2787. };
  2788. ErrorAddingDeclarationLocationStack.prototype = Error.prototype;
  2789. window.inject = angular.mock.inject = function() {
  2790. var blockFns = Array.prototype.slice.call(arguments, 0);
  2791. var errorForStack = new Error('Declaration Location');
  2792. // IE10+ and PhanthomJS do not set stack trace information, until the error is thrown
  2793. if (!errorForStack.stack) {
  2794. try {
  2795. throw errorForStack;
  2796. } catch (e) { /* empty */ }
  2797. }
  2798. return wasInjectorCreated() ? WorkFn.call(currentSpec) : WorkFn;
  2799. /////////////////////
  2800. function WorkFn() {
  2801. var modules = currentSpec.$modules || [];
  2802. var strictDi = !!currentSpec.$injectorStrict;
  2803. modules.unshift(['$injector', function($injector) {
  2804. currentSpec.$providerInjector = $injector;
  2805. }]);
  2806. modules.unshift('ngMock');
  2807. modules.unshift('ng');
  2808. var injector = currentSpec.$injector;
  2809. if (!injector) {
  2810. if (strictDi) {
  2811. // If strictDi is enabled, annotate the providerInjector blocks
  2812. angular.forEach(modules, function(moduleFn) {
  2813. if (typeof moduleFn === 'function') {
  2814. angular.injector.$$annotate(moduleFn);
  2815. }
  2816. });
  2817. }
  2818. injector = currentSpec.$injector = angular.injector(modules, strictDi);
  2819. currentSpec.$injectorStrict = strictDi;
  2820. }
  2821. for (var i = 0, ii = blockFns.length; i < ii; i++) {
  2822. if (currentSpec.$injectorStrict) {
  2823. // If the injector is strict / strictDi, and the spec wants to inject using automatic
  2824. // annotation, then annotate the function here.
  2825. injector.annotate(blockFns[i]);
  2826. }
  2827. try {
  2828. injector.invoke(blockFns[i] || angular.noop, this);
  2829. } catch (e) {
  2830. if (e.stack && errorForStack) {
  2831. throw new ErrorAddingDeclarationLocationStack(e, errorForStack);
  2832. }
  2833. throw e;
  2834. } finally {
  2835. errorForStack = null;
  2836. }
  2837. }
  2838. }
  2839. };
  2840. angular.mock.inject.strictDi = function(value) {
  2841. value = arguments.length ? !!value : true;
  2842. return wasInjectorCreated() ? workFn() : workFn;
  2843. function workFn() {
  2844. if (value !== currentSpec.$injectorStrict) {
  2845. if (currentSpec.$injector) {
  2846. throw new Error('Injector already created, can not modify strict annotations');
  2847. } else {
  2848. currentSpec.$injectorStrict = value;
  2849. }
  2850. }
  2851. }
  2852. };
  2853. function InjectorState() {
  2854. this.shared = false;
  2855. this.sharedError = null;
  2856. this.cleanupAfterEach = function() {
  2857. return !this.shared || this.sharedError;
  2858. };
  2859. }
  2860. })(window.jasmine || window.mocha);
  2861. 'use strict';
  2862. (function() {
  2863. /**
  2864. * Triggers a browser event. Attempts to choose the right event if one is
  2865. * not specified.
  2866. *
  2867. * @param {Object} element Either a wrapped jQuery/jqLite node or a DOMElement
  2868. * @param {string} eventType Optional event type
  2869. * @param {Object=} eventData An optional object which contains additional event data (such as x,y
  2870. * coordinates, keys, etc...) that are passed into the event when triggered
  2871. */
  2872. window.browserTrigger = function browserTrigger(element, eventType, eventData) {
  2873. if (element && !element.nodeName) element = element[0];
  2874. if (!element) return;
  2875. eventData = eventData || {};
  2876. var relatedTarget = eventData.relatedTarget || element;
  2877. var keys = eventData.keys;
  2878. var x = eventData.x;
  2879. var y = eventData.y;
  2880. var inputType = (element.type) ? element.type.toLowerCase() : null,
  2881. nodeName = element.nodeName.toLowerCase();
  2882. if (!eventType) {
  2883. eventType = {
  2884. 'text': 'change',
  2885. 'textarea': 'change',
  2886. 'hidden': 'change',
  2887. 'password': 'change',
  2888. 'button': 'click',
  2889. 'submit': 'click',
  2890. 'reset': 'click',
  2891. 'image': 'click',
  2892. 'checkbox': 'click',
  2893. 'radio': 'click',
  2894. 'select-one': 'change',
  2895. 'select-multiple': 'change',
  2896. '_default_': 'click'
  2897. }[inputType || '_default_'];
  2898. }
  2899. if (nodeName === 'option') {
  2900. element.parentNode.value = element.value;
  2901. element = element.parentNode;
  2902. eventType = 'change';
  2903. }
  2904. keys = keys || [];
  2905. function pressed(key) {
  2906. return keys.indexOf(key) !== -1;
  2907. }
  2908. var evnt;
  2909. if (/transitionend/.test(eventType)) {
  2910. if (window.WebKitTransitionEvent) {
  2911. evnt = new window.WebKitTransitionEvent(eventType, eventData);
  2912. evnt.initEvent(eventType, false, true);
  2913. } else {
  2914. try {
  2915. evnt = new window.TransitionEvent(eventType, eventData);
  2916. } catch (e) {
  2917. evnt = window.document.createEvent('TransitionEvent');
  2918. evnt.initTransitionEvent(eventType, null, null, null, eventData.elapsedTime || 0);
  2919. }
  2920. }
  2921. } else if (/animationend/.test(eventType)) {
  2922. if (window.WebKitAnimationEvent) {
  2923. evnt = new window.WebKitAnimationEvent(eventType, eventData);
  2924. evnt.initEvent(eventType, false, true);
  2925. } else {
  2926. try {
  2927. evnt = new window.AnimationEvent(eventType, eventData);
  2928. } catch (e) {
  2929. evnt = window.document.createEvent('AnimationEvent');
  2930. evnt.initAnimationEvent(eventType, null, null, null, eventData.elapsedTime || 0);
  2931. }
  2932. }
  2933. } else if (/touch/.test(eventType) && supportsTouchEvents()) {
  2934. evnt = createTouchEvent(element, eventType, x, y);
  2935. } else if (/key/.test(eventType)) {
  2936. evnt = window.document.createEvent('Events');
  2937. evnt.initEvent(eventType, eventData.bubbles, eventData.cancelable);
  2938. evnt.view = window;
  2939. evnt.ctrlKey = pressed('ctrl');
  2940. evnt.altKey = pressed('alt');
  2941. evnt.shiftKey = pressed('shift');
  2942. evnt.metaKey = pressed('meta');
  2943. evnt.keyCode = eventData.keyCode;
  2944. evnt.charCode = eventData.charCode;
  2945. evnt.which = eventData.which;
  2946. } else {
  2947. evnt = window.document.createEvent('MouseEvents');
  2948. x = x || 0;
  2949. y = y || 0;
  2950. evnt.initMouseEvent(eventType, true, true, window, 0, x, y, x, y, pressed('ctrl'),
  2951. pressed('alt'), pressed('shift'), pressed('meta'), 0, relatedTarget);
  2952. }
  2953. /* we're unable to change the timeStamp value directly so this
  2954. * is only here to allow for testing where the timeStamp value is
  2955. * read */
  2956. evnt.$manualTimeStamp = eventData.timeStamp;
  2957. if (!evnt) return;
  2958. var originalPreventDefault = evnt.preventDefault,
  2959. appWindow = element.ownerDocument.defaultView,
  2960. fakeProcessDefault = true,
  2961. finalProcessDefault,
  2962. angular = appWindow.angular || {};
  2963. // igor: temporary fix for https://bugzilla.mozilla.org/show_bug.cgi?id=684208
  2964. angular['ff-684208-preventDefault'] = false;
  2965. evnt.preventDefault = function() {
  2966. fakeProcessDefault = false;
  2967. return originalPreventDefault.apply(evnt, arguments);
  2968. };
  2969. if (!eventData.bubbles || supportsEventBubblingInDetachedTree() || isAttachedToDocument(element)) {
  2970. element.dispatchEvent(evnt);
  2971. } else {
  2972. triggerForPath(element, evnt);
  2973. }
  2974. finalProcessDefault = !(angular['ff-684208-preventDefault'] || !fakeProcessDefault);
  2975. delete angular['ff-684208-preventDefault'];
  2976. return finalProcessDefault;
  2977. };
  2978. function supportsTouchEvents() {
  2979. if ('_cached' in supportsTouchEvents) {
  2980. return supportsTouchEvents._cached;
  2981. }
  2982. if (!window.document.createTouch || !window.document.createTouchList) {
  2983. supportsTouchEvents._cached = false;
  2984. return false;
  2985. }
  2986. try {
  2987. window.document.createEvent('TouchEvent');
  2988. } catch (e) {
  2989. supportsTouchEvents._cached = false;
  2990. return false;
  2991. }
  2992. supportsTouchEvents._cached = true;
  2993. return true;
  2994. }
  2995. function createTouchEvent(element, eventType, x, y) {
  2996. var evnt = new window.Event(eventType);
  2997. x = x || 0;
  2998. y = y || 0;
  2999. var touch = window.document.createTouch(window, element, Date.now(), x, y, x, y);
  3000. var touches = window.document.createTouchList(touch);
  3001. evnt.touches = touches;
  3002. return evnt;
  3003. }
  3004. function supportsEventBubblingInDetachedTree() {
  3005. if ('_cached' in supportsEventBubblingInDetachedTree) {
  3006. return supportsEventBubblingInDetachedTree._cached;
  3007. }
  3008. supportsEventBubblingInDetachedTree._cached = false;
  3009. var doc = window.document;
  3010. if (doc) {
  3011. var parent = doc.createElement('div'),
  3012. child = parent.cloneNode();
  3013. parent.appendChild(child);
  3014. parent.addEventListener('e', function() {
  3015. supportsEventBubblingInDetachedTree._cached = true;
  3016. });
  3017. var evnt = window.document.createEvent('Events');
  3018. evnt.initEvent('e', true, true);
  3019. child.dispatchEvent(evnt);
  3020. }
  3021. return supportsEventBubblingInDetachedTree._cached;
  3022. }
  3023. function triggerForPath(element, evnt) {
  3024. var stop = false;
  3025. var _stopPropagation = evnt.stopPropagation;
  3026. evnt.stopPropagation = function() {
  3027. stop = true;
  3028. _stopPropagation.apply(evnt, arguments);
  3029. };
  3030. patchEventTargetForBubbling(evnt, element);
  3031. do {
  3032. element.dispatchEvent(evnt);
  3033. // eslint-disable-next-line no-unmodified-loop-condition
  3034. } while (!stop && (element = element.parentNode));
  3035. }
  3036. function patchEventTargetForBubbling(event, target) {
  3037. event._target = target;
  3038. Object.defineProperty(event, 'target', {get: function() { return this._target;}});
  3039. }
  3040. function isAttachedToDocument(element) {
  3041. while ((element = element.parentNode)) {
  3042. if (element === window) {
  3043. return true;
  3044. }
  3045. }
  3046. return false;
  3047. }
  3048. })();
  3049. })(window, window.angular);