angular-mocks.js 96 KB

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