angular-mocks.js 110 KB

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