angular-mocks.js 139 KB

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