angular-mocks.js 67 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166
  1. /**
  2. * @license AngularJS v1.2.9
  3. * (c) 2010-2014 Google, Inc. http://angularjs.org
  4. * License: MIT
  5. */
  6. (function(window, angular, undefined) {
  7. 'use strict';
  8. /**
  9. * @ngdoc overview
  10. * @name angular.mock
  11. * @description
  12. *
  13. * Namespace from 'angular-mocks.js' which contains testing related code.
  14. */
  15. angular.mock = {};
  16. /**
  17. * ! This is a private undocumented service !
  18. *
  19. * @name ngMock.$browser
  20. *
  21. * @description
  22. * This service is a mock implementation of {@link ng.$browser}. It provides fake
  23. * implementation for commonly used browser apis that are hard to test, e.g. setTimeout, xhr,
  24. * cookies, etc...
  25. *
  26. * The api of this service is the same as that of the real {@link ng.$browser $browser}, except
  27. * that there are several helper methods available which can be used in tests.
  28. */
  29. angular.mock.$BrowserProvider = function() {
  30. this.$get = function() {
  31. return new angular.mock.$Browser();
  32. };
  33. };
  34. angular.mock.$Browser = function() {
  35. var self = this;
  36. this.isMock = true;
  37. self.$$url = "http://server/";
  38. self.$$lastUrl = self.$$url; // used by url polling fn
  39. self.pollFns = [];
  40. // TODO(vojta): remove this temporary api
  41. self.$$completeOutstandingRequest = angular.noop;
  42. self.$$incOutstandingRequestCount = angular.noop;
  43. // register url polling fn
  44. self.onUrlChange = function(listener) {
  45. self.pollFns.push(
  46. function() {
  47. if (self.$$lastUrl != self.$$url) {
  48. self.$$lastUrl = self.$$url;
  49. listener(self.$$url);
  50. }
  51. }
  52. );
  53. return listener;
  54. };
  55. self.cookieHash = {};
  56. self.lastCookieHash = {};
  57. self.deferredFns = [];
  58. self.deferredNextId = 0;
  59. self.defer = function(fn, delay) {
  60. delay = delay || 0;
  61. self.deferredFns.push({time:(self.defer.now + delay), fn:fn, id: self.deferredNextId});
  62. self.deferredFns.sort(function(a,b){ return a.time - b.time;});
  63. return self.deferredNextId++;
  64. };
  65. /**
  66. * @name ngMock.$browser#defer.now
  67. * @propertyOf ngMock.$browser
  68. *
  69. * @description
  70. * Current milliseconds mock time.
  71. */
  72. self.defer.now = 0;
  73. self.defer.cancel = function(deferId) {
  74. var fnIndex;
  75. angular.forEach(self.deferredFns, function(fn, index) {
  76. if (fn.id === deferId) fnIndex = index;
  77. });
  78. if (fnIndex !== undefined) {
  79. self.deferredFns.splice(fnIndex, 1);
  80. return true;
  81. }
  82. return false;
  83. };
  84. /**
  85. * @name ngMock.$browser#defer.flush
  86. * @methodOf ngMock.$browser
  87. *
  88. * @description
  89. * Flushes all pending requests and executes the defer callbacks.
  90. *
  91. * @param {number=} number of milliseconds to flush. See {@link #defer.now}
  92. */
  93. self.defer.flush = function(delay) {
  94. if (angular.isDefined(delay)) {
  95. self.defer.now += delay;
  96. } else {
  97. if (self.deferredFns.length) {
  98. self.defer.now = self.deferredFns[self.deferredFns.length-1].time;
  99. } else {
  100. throw new Error('No deferred tasks to be flushed');
  101. }
  102. }
  103. while (self.deferredFns.length && self.deferredFns[0].time <= self.defer.now) {
  104. self.deferredFns.shift().fn();
  105. }
  106. };
  107. self.$$baseHref = '';
  108. self.baseHref = function() {
  109. return this.$$baseHref;
  110. };
  111. };
  112. angular.mock.$Browser.prototype = {
  113. /**
  114. * @name ngMock.$browser#poll
  115. * @methodOf ngMock.$browser
  116. *
  117. * @description
  118. * run all fns in pollFns
  119. */
  120. poll: function poll() {
  121. angular.forEach(this.pollFns, function(pollFn){
  122. pollFn();
  123. });
  124. },
  125. addPollFn: function(pollFn) {
  126. this.pollFns.push(pollFn);
  127. return pollFn;
  128. },
  129. url: function(url, replace) {
  130. if (url) {
  131. this.$$url = url;
  132. return this;
  133. }
  134. return this.$$url;
  135. },
  136. cookies: function(name, value) {
  137. if (name) {
  138. if (angular.isUndefined(value)) {
  139. delete this.cookieHash[name];
  140. } else {
  141. if (angular.isString(value) && //strings only
  142. value.length <= 4096) { //strict cookie storage limits
  143. this.cookieHash[name] = value;
  144. }
  145. }
  146. } else {
  147. if (!angular.equals(this.cookieHash, this.lastCookieHash)) {
  148. this.lastCookieHash = angular.copy(this.cookieHash);
  149. this.cookieHash = angular.copy(this.cookieHash);
  150. }
  151. return this.cookieHash;
  152. }
  153. },
  154. notifyWhenNoOutstandingRequests: function(fn) {
  155. fn();
  156. }
  157. };
  158. /**
  159. * @ngdoc object
  160. * @name ngMock.$exceptionHandlerProvider
  161. *
  162. * @description
  163. * Configures the mock implementation of {@link ng.$exceptionHandler} to rethrow or to log errors
  164. * passed into the `$exceptionHandler`.
  165. */
  166. /**
  167. * @ngdoc object
  168. * @name ngMock.$exceptionHandler
  169. *
  170. * @description
  171. * Mock implementation of {@link ng.$exceptionHandler} that rethrows or logs errors passed
  172. * into it. See {@link ngMock.$exceptionHandlerProvider $exceptionHandlerProvider} for configuration
  173. * information.
  174. *
  175. *
  176. * <pre>
  177. * describe('$exceptionHandlerProvider', function() {
  178. *
  179. * it('should capture log messages and exceptions', function() {
  180. *
  181. * module(function($exceptionHandlerProvider) {
  182. * $exceptionHandlerProvider.mode('log');
  183. * });
  184. *
  185. * inject(function($log, $exceptionHandler, $timeout) {
  186. * $timeout(function() { $log.log(1); });
  187. * $timeout(function() { $log.log(2); throw 'banana peel'; });
  188. * $timeout(function() { $log.log(3); });
  189. * expect($exceptionHandler.errors).toEqual([]);
  190. * expect($log.assertEmpty());
  191. * $timeout.flush();
  192. * expect($exceptionHandler.errors).toEqual(['banana peel']);
  193. * expect($log.log.logs).toEqual([[1], [2], [3]]);
  194. * });
  195. * });
  196. * });
  197. * </pre>
  198. */
  199. angular.mock.$ExceptionHandlerProvider = function() {
  200. var handler;
  201. /**
  202. * @ngdoc method
  203. * @name ngMock.$exceptionHandlerProvider#mode
  204. * @methodOf ngMock.$exceptionHandlerProvider
  205. *
  206. * @description
  207. * Sets the logging mode.
  208. *
  209. * @param {string} mode Mode of operation, defaults to `rethrow`.
  210. *
  211. * - `rethrow`: If any errors are passed into the handler in tests, it typically
  212. * means that there is a bug in the application or test, so this mock will
  213. * make these tests fail.
  214. * - `log`: Sometimes it is desirable to test that an error is thrown, for this case the `log`
  215. * mode stores an array of errors in `$exceptionHandler.errors`, to allow later
  216. * assertion of them. See {@link ngMock.$log#assertEmpty assertEmpty()} and
  217. * {@link ngMock.$log#reset reset()}
  218. */
  219. this.mode = function(mode) {
  220. switch(mode) {
  221. case 'rethrow':
  222. handler = function(e) {
  223. throw e;
  224. };
  225. break;
  226. case 'log':
  227. var errors = [];
  228. handler = function(e) {
  229. if (arguments.length == 1) {
  230. errors.push(e);
  231. } else {
  232. errors.push([].slice.call(arguments, 0));
  233. }
  234. };
  235. handler.errors = errors;
  236. break;
  237. default:
  238. throw new Error("Unknown mode '" + mode + "', only 'log'/'rethrow' modes are allowed!");
  239. }
  240. };
  241. this.$get = function() {
  242. return handler;
  243. };
  244. this.mode('rethrow');
  245. };
  246. /**
  247. * @ngdoc service
  248. * @name ngMock.$log
  249. *
  250. * @description
  251. * Mock implementation of {@link ng.$log} that gathers all logged messages in arrays
  252. * (one array per logging level). These arrays are exposed as `logs` property of each of the
  253. * level-specific log function, e.g. for level `error` the array is exposed as `$log.error.logs`.
  254. *
  255. */
  256. angular.mock.$LogProvider = function() {
  257. var debug = true;
  258. function concat(array1, array2, index) {
  259. return array1.concat(Array.prototype.slice.call(array2, index));
  260. }
  261. this.debugEnabled = function(flag) {
  262. if (angular.isDefined(flag)) {
  263. debug = flag;
  264. return this;
  265. } else {
  266. return debug;
  267. }
  268. };
  269. this.$get = function () {
  270. var $log = {
  271. log: function() { $log.log.logs.push(concat([], arguments, 0)); },
  272. warn: function() { $log.warn.logs.push(concat([], arguments, 0)); },
  273. info: function() { $log.info.logs.push(concat([], arguments, 0)); },
  274. error: function() { $log.error.logs.push(concat([], arguments, 0)); },
  275. debug: function() {
  276. if (debug) {
  277. $log.debug.logs.push(concat([], arguments, 0));
  278. }
  279. }
  280. };
  281. /**
  282. * @ngdoc method
  283. * @name ngMock.$log#reset
  284. * @methodOf ngMock.$log
  285. *
  286. * @description
  287. * Reset all of the logging arrays to empty.
  288. */
  289. $log.reset = function () {
  290. /**
  291. * @ngdoc property
  292. * @name ngMock.$log#log.logs
  293. * @propertyOf ngMock.$log
  294. *
  295. * @description
  296. * Array of messages logged using {@link ngMock.$log#log}.
  297. *
  298. * @example
  299. * <pre>
  300. * $log.log('Some Log');
  301. * var first = $log.log.logs.unshift();
  302. * </pre>
  303. */
  304. $log.log.logs = [];
  305. /**
  306. * @ngdoc property
  307. * @name ngMock.$log#info.logs
  308. * @propertyOf ngMock.$log
  309. *
  310. * @description
  311. * Array of messages logged using {@link ngMock.$log#info}.
  312. *
  313. * @example
  314. * <pre>
  315. * $log.info('Some Info');
  316. * var first = $log.info.logs.unshift();
  317. * </pre>
  318. */
  319. $log.info.logs = [];
  320. /**
  321. * @ngdoc property
  322. * @name ngMock.$log#warn.logs
  323. * @propertyOf ngMock.$log
  324. *
  325. * @description
  326. * Array of messages logged using {@link ngMock.$log#warn}.
  327. *
  328. * @example
  329. * <pre>
  330. * $log.warn('Some Warning');
  331. * var first = $log.warn.logs.unshift();
  332. * </pre>
  333. */
  334. $log.warn.logs = [];
  335. /**
  336. * @ngdoc property
  337. * @name ngMock.$log#error.logs
  338. * @propertyOf ngMock.$log
  339. *
  340. * @description
  341. * Array of messages logged using {@link ngMock.$log#error}.
  342. *
  343. * @example
  344. * <pre>
  345. * $log.log('Some Error');
  346. * var first = $log.error.logs.unshift();
  347. * </pre>
  348. */
  349. $log.error.logs = [];
  350. /**
  351. * @ngdoc property
  352. * @name ngMock.$log#debug.logs
  353. * @propertyOf ngMock.$log
  354. *
  355. * @description
  356. * Array of messages logged using {@link ngMock.$log#debug}.
  357. *
  358. * @example
  359. * <pre>
  360. * $log.debug('Some Error');
  361. * var first = $log.debug.logs.unshift();
  362. * </pre>
  363. */
  364. $log.debug.logs = [];
  365. };
  366. /**
  367. * @ngdoc method
  368. * @name ngMock.$log#assertEmpty
  369. * @methodOf ngMock.$log
  370. *
  371. * @description
  372. * Assert that the all of the logging methods have no logged messages. If messages present, an
  373. * exception is thrown.
  374. */
  375. $log.assertEmpty = function() {
  376. var errors = [];
  377. angular.forEach(['error', 'warn', 'info', 'log', 'debug'], function(logLevel) {
  378. angular.forEach($log[logLevel].logs, function(log) {
  379. angular.forEach(log, function (logItem) {
  380. errors.push('MOCK $log (' + logLevel + '): ' + String(logItem) + '\n' +
  381. (logItem.stack || ''));
  382. });
  383. });
  384. });
  385. if (errors.length) {
  386. errors.unshift("Expected $log to be empty! Either a message was logged unexpectedly, or "+
  387. "an expected log message was not checked and removed:");
  388. errors.push('');
  389. throw new Error(errors.join('\n---------\n'));
  390. }
  391. };
  392. $log.reset();
  393. return $log;
  394. };
  395. };
  396. /**
  397. * @ngdoc service
  398. * @name ngMock.$interval
  399. *
  400. * @description
  401. * Mock implementation of the $interval service.
  402. *
  403. * Use {@link ngMock.$interval#methods_flush `$interval.flush(millis)`} to
  404. * move forward by `millis` milliseconds and trigger any functions scheduled to run in that
  405. * time.
  406. *
  407. * @param {function()} fn A function that should be called repeatedly.
  408. * @param {number} delay Number of milliseconds between each function call.
  409. * @param {number=} [count=0] Number of times to repeat. If not set, or 0, will repeat
  410. * indefinitely.
  411. * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
  412. * will invoke `fn` within the {@link ng.$rootScope.Scope#methods_$apply $apply} block.
  413. * @returns {promise} A promise which will be notified on each iteration.
  414. */
  415. angular.mock.$IntervalProvider = function() {
  416. this.$get = ['$rootScope', '$q',
  417. function($rootScope, $q) {
  418. var repeatFns = [],
  419. nextRepeatId = 0,
  420. now = 0;
  421. var $interval = function(fn, delay, count, invokeApply) {
  422. var deferred = $q.defer(),
  423. promise = deferred.promise,
  424. iteration = 0,
  425. skipApply = (angular.isDefined(invokeApply) && !invokeApply);
  426. count = (angular.isDefined(count)) ? count : 0,
  427. promise.then(null, null, fn);
  428. promise.$$intervalId = nextRepeatId;
  429. function tick() {
  430. deferred.notify(iteration++);
  431. if (count > 0 && iteration >= count) {
  432. var fnIndex;
  433. deferred.resolve(iteration);
  434. angular.forEach(repeatFns, function(fn, index) {
  435. if (fn.id === promise.$$intervalId) fnIndex = index;
  436. });
  437. if (fnIndex !== undefined) {
  438. repeatFns.splice(fnIndex, 1);
  439. }
  440. }
  441. if (!skipApply) $rootScope.$apply();
  442. }
  443. repeatFns.push({
  444. nextTime:(now + delay),
  445. delay: delay,
  446. fn: tick,
  447. id: nextRepeatId,
  448. deferred: deferred
  449. });
  450. repeatFns.sort(function(a,b){ return a.nextTime - b.nextTime;});
  451. nextRepeatId++;
  452. return promise;
  453. };
  454. $interval.cancel = function(promise) {
  455. var fnIndex;
  456. angular.forEach(repeatFns, function(fn, index) {
  457. if (fn.id === promise.$$intervalId) fnIndex = index;
  458. });
  459. if (fnIndex !== undefined) {
  460. repeatFns[fnIndex].deferred.reject('canceled');
  461. repeatFns.splice(fnIndex, 1);
  462. return true;
  463. }
  464. return false;
  465. };
  466. /**
  467. * @ngdoc method
  468. * @name ngMock.$interval#flush
  469. * @methodOf ngMock.$interval
  470. * @description
  471. *
  472. * Runs interval tasks scheduled to be run in the next `millis` milliseconds.
  473. *
  474. * @param {number=} millis maximum timeout amount to flush up until.
  475. *
  476. * @return {number} The amount of time moved forward.
  477. */
  478. $interval.flush = function(millis) {
  479. now += millis;
  480. while (repeatFns.length && repeatFns[0].nextTime <= now) {
  481. var task = repeatFns[0];
  482. task.fn();
  483. task.nextTime += task.delay;
  484. repeatFns.sort(function(a,b){ return a.nextTime - b.nextTime;});
  485. }
  486. return millis;
  487. };
  488. return $interval;
  489. }];
  490. };
  491. /* jshint -W101 */
  492. /* The R_ISO8061_STR regex is never going to fit into the 100 char limit!
  493. * This directive should go inside the anonymous function but a bug in JSHint means that it would
  494. * not be enacted early enough to prevent the warning.
  495. */
  496. var R_ISO8061_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?:\:?(\d\d)(?:\:?(\d\d)(?:\.(\d{3}))?)?)?(Z|([+-])(\d\d):?(\d\d)))?$/;
  497. function jsonStringToDate(string) {
  498. var match;
  499. if (match = string.match(R_ISO8061_STR)) {
  500. var date = new Date(0),
  501. tzHour = 0,
  502. tzMin = 0;
  503. if (match[9]) {
  504. tzHour = int(match[9] + match[10]);
  505. tzMin = int(match[9] + match[11]);
  506. }
  507. date.setUTCFullYear(int(match[1]), int(match[2]) - 1, int(match[3]));
  508. date.setUTCHours(int(match[4]||0) - tzHour,
  509. int(match[5]||0) - tzMin,
  510. int(match[6]||0),
  511. int(match[7]||0));
  512. return date;
  513. }
  514. return string;
  515. }
  516. function int(str) {
  517. return parseInt(str, 10);
  518. }
  519. function padNumber(num, digits, trim) {
  520. var neg = '';
  521. if (num < 0) {
  522. neg = '-';
  523. num = -num;
  524. }
  525. num = '' + num;
  526. while(num.length < digits) num = '0' + num;
  527. if (trim)
  528. num = num.substr(num.length - digits);
  529. return neg + num;
  530. }
  531. /**
  532. * @ngdoc object
  533. * @name angular.mock.TzDate
  534. * @description
  535. *
  536. * *NOTE*: this is not an injectable instance, just a globally available mock class of `Date`.
  537. *
  538. * Mock of the Date type which has its timezone specified via constructor arg.
  539. *
  540. * The main purpose is to create Date-like instances with timezone fixed to the specified timezone
  541. * offset, so that we can test code that depends on local timezone settings without dependency on
  542. * the time zone settings of the machine where the code is running.
  543. *
  544. * @param {number} offset Offset of the *desired* timezone in hours (fractions will be honored)
  545. * @param {(number|string)} timestamp Timestamp representing the desired time in *UTC*
  546. *
  547. * @example
  548. * !!!! WARNING !!!!!
  549. * This is not a complete Date object so only methods that were implemented can be called safely.
  550. * To make matters worse, TzDate instances inherit stuff from Date via a prototype.
  551. *
  552. * We do our best to intercept calls to "unimplemented" methods, but since the list of methods is
  553. * incomplete we might be missing some non-standard methods. This can result in errors like:
  554. * "Date.prototype.foo called on incompatible Object".
  555. *
  556. * <pre>
  557. * var newYearInBratislava = new TzDate(-1, '2009-12-31T23:00:00Z');
  558. * newYearInBratislava.getTimezoneOffset() => -60;
  559. * newYearInBratislava.getFullYear() => 2010;
  560. * newYearInBratislava.getMonth() => 0;
  561. * newYearInBratislava.getDate() => 1;
  562. * newYearInBratislava.getHours() => 0;
  563. * newYearInBratislava.getMinutes() => 0;
  564. * newYearInBratislava.getSeconds() => 0;
  565. * </pre>
  566. *
  567. */
  568. angular.mock.TzDate = function (offset, timestamp) {
  569. var self = new Date(0);
  570. if (angular.isString(timestamp)) {
  571. var tsStr = timestamp;
  572. self.origDate = jsonStringToDate(timestamp);
  573. timestamp = self.origDate.getTime();
  574. if (isNaN(timestamp))
  575. throw {
  576. name: "Illegal Argument",
  577. message: "Arg '" + tsStr + "' passed into TzDate constructor is not a valid date string"
  578. };
  579. } else {
  580. self.origDate = new Date(timestamp);
  581. }
  582. var localOffset = new Date(timestamp).getTimezoneOffset();
  583. self.offsetDiff = localOffset*60*1000 - offset*1000*60*60;
  584. self.date = new Date(timestamp + self.offsetDiff);
  585. self.getTime = function() {
  586. return self.date.getTime() - self.offsetDiff;
  587. };
  588. self.toLocaleDateString = function() {
  589. return self.date.toLocaleDateString();
  590. };
  591. self.getFullYear = function() {
  592. return self.date.getFullYear();
  593. };
  594. self.getMonth = function() {
  595. return self.date.getMonth();
  596. };
  597. self.getDate = function() {
  598. return self.date.getDate();
  599. };
  600. self.getHours = function() {
  601. return self.date.getHours();
  602. };
  603. self.getMinutes = function() {
  604. return self.date.getMinutes();
  605. };
  606. self.getSeconds = function() {
  607. return self.date.getSeconds();
  608. };
  609. self.getMilliseconds = function() {
  610. return self.date.getMilliseconds();
  611. };
  612. self.getTimezoneOffset = function() {
  613. return offset * 60;
  614. };
  615. self.getUTCFullYear = function() {
  616. return self.origDate.getUTCFullYear();
  617. };
  618. self.getUTCMonth = function() {
  619. return self.origDate.getUTCMonth();
  620. };
  621. self.getUTCDate = function() {
  622. return self.origDate.getUTCDate();
  623. };
  624. self.getUTCHours = function() {
  625. return self.origDate.getUTCHours();
  626. };
  627. self.getUTCMinutes = function() {
  628. return self.origDate.getUTCMinutes();
  629. };
  630. self.getUTCSeconds = function() {
  631. return self.origDate.getUTCSeconds();
  632. };
  633. self.getUTCMilliseconds = function() {
  634. return self.origDate.getUTCMilliseconds();
  635. };
  636. self.getDay = function() {
  637. return self.date.getDay();
  638. };
  639. // provide this method only on browsers that already have it
  640. if (self.toISOString) {
  641. self.toISOString = function() {
  642. return padNumber(self.origDate.getUTCFullYear(), 4) + '-' +
  643. padNumber(self.origDate.getUTCMonth() + 1, 2) + '-' +
  644. padNumber(self.origDate.getUTCDate(), 2) + 'T' +
  645. padNumber(self.origDate.getUTCHours(), 2) + ':' +
  646. padNumber(self.origDate.getUTCMinutes(), 2) + ':' +
  647. padNumber(self.origDate.getUTCSeconds(), 2) + '.' +
  648. padNumber(self.origDate.getUTCMilliseconds(), 3) + 'Z';
  649. };
  650. }
  651. //hide all methods not implemented in this mock that the Date prototype exposes
  652. var unimplementedMethods = ['getUTCDay',
  653. 'getYear', 'setDate', 'setFullYear', 'setHours', 'setMilliseconds',
  654. 'setMinutes', 'setMonth', 'setSeconds', 'setTime', 'setUTCDate', 'setUTCFullYear',
  655. 'setUTCHours', 'setUTCMilliseconds', 'setUTCMinutes', 'setUTCMonth', 'setUTCSeconds',
  656. 'setYear', 'toDateString', 'toGMTString', 'toJSON', 'toLocaleFormat', 'toLocaleString',
  657. 'toLocaleTimeString', 'toSource', 'toString', 'toTimeString', 'toUTCString', 'valueOf'];
  658. angular.forEach(unimplementedMethods, function(methodName) {
  659. self[methodName] = function() {
  660. throw new Error("Method '" + methodName + "' is not implemented in the TzDate mock");
  661. };
  662. });
  663. return self;
  664. };
  665. //make "tzDateInstance instanceof Date" return true
  666. angular.mock.TzDate.prototype = Date.prototype;
  667. /* jshint +W101 */
  668. // TODO(matias): remove this IMMEDIATELY once we can properly detect the
  669. // presence of a registered module
  670. var animateLoaded;
  671. try {
  672. angular.module('ngAnimate');
  673. animateLoaded = true;
  674. } catch(e) {}
  675. if(animateLoaded) {
  676. angular.module('ngAnimate').config(['$provide', function($provide) {
  677. var reflowQueue = [];
  678. $provide.value('$$animateReflow', function(fn) {
  679. reflowQueue.push(fn);
  680. return angular.noop;
  681. });
  682. $provide.decorator('$animate', function($delegate) {
  683. $delegate.triggerReflow = function() {
  684. if(reflowQueue.length === 0) {
  685. throw new Error('No animation reflows present');
  686. }
  687. angular.forEach(reflowQueue, function(fn) {
  688. fn();
  689. });
  690. reflowQueue = [];
  691. };
  692. return $delegate;
  693. });
  694. }]);
  695. }
  696. angular.mock.animate = angular.module('mock.animate', ['ng'])
  697. .config(['$provide', function($provide) {
  698. $provide.decorator('$animate', function($delegate) {
  699. var animate = {
  700. queue : [],
  701. enabled : $delegate.enabled,
  702. flushNext : function(name) {
  703. var tick = animate.queue.shift();
  704. if (!tick) throw new Error('No animation to be flushed');
  705. if(tick.method !== name) {
  706. throw new Error('The next animation is not "' + name +
  707. '", but is "' + tick.method + '"');
  708. }
  709. tick.fn();
  710. return tick;
  711. }
  712. };
  713. angular.forEach(['enter','leave','move','addClass','removeClass'], function(method) {
  714. animate[method] = function() {
  715. var params = arguments;
  716. animate.queue.push({
  717. method : method,
  718. params : params,
  719. element : angular.isElement(params[0]) && params[0],
  720. parent : angular.isElement(params[1]) && params[1],
  721. after : angular.isElement(params[2]) && params[2],
  722. fn : function() {
  723. $delegate[method].apply($delegate, params);
  724. }
  725. });
  726. };
  727. });
  728. return animate;
  729. });
  730. }]);
  731. /**
  732. * @ngdoc function
  733. * @name angular.mock.dump
  734. * @description
  735. *
  736. * *NOTE*: this is not an injectable instance, just a globally available function.
  737. *
  738. * Method for serializing common angular objects (scope, elements, etc..) into strings, useful for
  739. * debugging.
  740. *
  741. * This method is also available on window, where it can be used to display objects on debug
  742. * console.
  743. *
  744. * @param {*} object - any object to turn into string.
  745. * @return {string} a serialized string of the argument
  746. */
  747. angular.mock.dump = function(object) {
  748. return serialize(object);
  749. function serialize(object) {
  750. var out;
  751. if (angular.isElement(object)) {
  752. object = angular.element(object);
  753. out = angular.element('<div></div>');
  754. angular.forEach(object, function(element) {
  755. out.append(angular.element(element).clone());
  756. });
  757. out = out.html();
  758. } else if (angular.isArray(object)) {
  759. out = [];
  760. angular.forEach(object, function(o) {
  761. out.push(serialize(o));
  762. });
  763. out = '[ ' + out.join(', ') + ' ]';
  764. } else if (angular.isObject(object)) {
  765. if (angular.isFunction(object.$eval) && angular.isFunction(object.$apply)) {
  766. out = serializeScope(object);
  767. } else if (object instanceof Error) {
  768. out = object.stack || ('' + object.name + ': ' + object.message);
  769. } else {
  770. // TODO(i): this prevents methods being logged,
  771. // we should have a better way to serialize objects
  772. out = angular.toJson(object, true);
  773. }
  774. } else {
  775. out = String(object);
  776. }
  777. return out;
  778. }
  779. function serializeScope(scope, offset) {
  780. offset = offset || ' ';
  781. var log = [offset + 'Scope(' + scope.$id + '): {'];
  782. for ( var key in scope ) {
  783. if (Object.prototype.hasOwnProperty.call(scope, key) && !key.match(/^(\$|this)/)) {
  784. log.push(' ' + key + ': ' + angular.toJson(scope[key]));
  785. }
  786. }
  787. var child = scope.$$childHead;
  788. while(child) {
  789. log.push(serializeScope(child, offset + ' '));
  790. child = child.$$nextSibling;
  791. }
  792. log.push('}');
  793. return log.join('\n' + offset);
  794. }
  795. };
  796. /**
  797. * @ngdoc object
  798. * @name ngMock.$httpBackend
  799. * @description
  800. * Fake HTTP backend implementation suitable for unit testing applications that use the
  801. * {@link ng.$http $http service}.
  802. *
  803. * *Note*: For fake HTTP backend implementation suitable for end-to-end testing or backend-less
  804. * development please see {@link ngMockE2E.$httpBackend e2e $httpBackend mock}.
  805. *
  806. * During unit testing, we want our unit tests to run quickly and have no external dependencies so
  807. * we don’t want to send {@link https://developer.mozilla.org/en/xmlhttprequest XHR} or
  808. * {@link http://en.wikipedia.org/wiki/JSONP JSONP} requests to a real server. All we really need is
  809. * to verify whether a certain request has been sent or not, or alternatively just let the
  810. * application make requests, respond with pre-trained responses and assert that the end result is
  811. * what we expect it to be.
  812. *
  813. * This mock implementation can be used to respond with static or dynamic responses via the
  814. * `expect` and `when` apis and their shortcuts (`expectGET`, `whenPOST`, etc).
  815. *
  816. * When an Angular application needs some data from a server, it calls the $http service, which
  817. * sends the request to a real server using $httpBackend service. With dependency injection, it is
  818. * easy to inject $httpBackend mock (which has the same API as $httpBackend) and use it to verify
  819. * the requests and respond with some testing data without sending a request to real server.
  820. *
  821. * There are two ways to specify what test data should be returned as http responses by the mock
  822. * backend when the code under test makes http requests:
  823. *
  824. * - `$httpBackend.expect` - specifies a request expectation
  825. * - `$httpBackend.when` - specifies a backend definition
  826. *
  827. *
  828. * # Request Expectations vs Backend Definitions
  829. *
  830. * Request expectations provide a way to make assertions about requests made by the application and
  831. * to define responses for those requests. The test will fail if the expected requests are not made
  832. * or they are made in the wrong order.
  833. *
  834. * Backend definitions allow you to define a fake backend for your application which doesn't assert
  835. * if a particular request was made or not, it just returns a trained response if a request is made.
  836. * The test will pass whether or not the request gets made during testing.
  837. *
  838. *
  839. * <table class="table">
  840. * <tr><th width="220px"></th><th>Request expectations</th><th>Backend definitions</th></tr>
  841. * <tr>
  842. * <th>Syntax</th>
  843. * <td>.expect(...).respond(...)</td>
  844. * <td>.when(...).respond(...)</td>
  845. * </tr>
  846. * <tr>
  847. * <th>Typical usage</th>
  848. * <td>strict unit tests</td>
  849. * <td>loose (black-box) unit testing</td>
  850. * </tr>
  851. * <tr>
  852. * <th>Fulfills multiple requests</th>
  853. * <td>NO</td>
  854. * <td>YES</td>
  855. * </tr>
  856. * <tr>
  857. * <th>Order of requests matters</th>
  858. * <td>YES</td>
  859. * <td>NO</td>
  860. * </tr>
  861. * <tr>
  862. * <th>Request required</th>
  863. * <td>YES</td>
  864. * <td>NO</td>
  865. * </tr>
  866. * <tr>
  867. * <th>Response required</th>
  868. * <td>optional (see below)</td>
  869. * <td>YES</td>
  870. * </tr>
  871. * </table>
  872. *
  873. * In cases where both backend definitions and request expectations are specified during unit
  874. * testing, the request expectations are evaluated first.
  875. *
  876. * If a request expectation has no response specified, the algorithm will search your backend
  877. * definitions for an appropriate response.
  878. *
  879. * If a request didn't match any expectation or if the expectation doesn't have the response
  880. * defined, the backend definitions are evaluated in sequential order to see if any of them match
  881. * the request. The response from the first matched definition is returned.
  882. *
  883. *
  884. * # Flushing HTTP requests
  885. *
  886. * The $httpBackend used in production, always responds to requests with responses asynchronously.
  887. * If we preserved this behavior in unit testing, we'd have to create async unit tests, which are
  888. * hard to write, follow and maintain. At the same time the testing mock, can't respond
  889. * synchronously because that would change the execution of the code under test. For this reason the
  890. * mock $httpBackend has a `flush()` method, which allows the test to explicitly flush pending
  891. * requests and thus preserving the async api of the backend, while allowing the test to execute
  892. * synchronously.
  893. *
  894. *
  895. * # Unit testing with mock $httpBackend
  896. * The following code shows how to setup and use the mock backend in unit testing a controller.
  897. * First we create the controller under test
  898. *
  899. <pre>
  900. // The controller code
  901. function MyController($scope, $http) {
  902. var authToken;
  903. $http.get('/auth.py').success(function(data, status, headers) {
  904. authToken = headers('A-Token');
  905. $scope.user = data;
  906. });
  907. $scope.saveMessage = function(message) {
  908. var headers = { 'Authorization': authToken };
  909. $scope.status = 'Saving...';
  910. $http.post('/add-msg.py', message, { headers: headers } ).success(function(response) {
  911. $scope.status = '';
  912. }).error(function() {
  913. $scope.status = 'ERROR!';
  914. });
  915. };
  916. }
  917. </pre>
  918. *
  919. * Now we setup the mock backend and create the test specs.
  920. *
  921. <pre>
  922. // testing controller
  923. describe('MyController', function() {
  924. var $httpBackend, $rootScope, createController;
  925. beforeEach(inject(function($injector) {
  926. // Set up the mock http service responses
  927. $httpBackend = $injector.get('$httpBackend');
  928. // backend definition common for all tests
  929. $httpBackend.when('GET', '/auth.py').respond({userId: 'userX'}, {'A-Token': 'xxx'});
  930. // Get hold of a scope (i.e. the root scope)
  931. $rootScope = $injector.get('$rootScope');
  932. // The $controller service is used to create instances of controllers
  933. var $controller = $injector.get('$controller');
  934. createController = function() {
  935. return $controller('MyController', {'$scope' : $rootScope });
  936. };
  937. }));
  938. afterEach(function() {
  939. $httpBackend.verifyNoOutstandingExpectation();
  940. $httpBackend.verifyNoOutstandingRequest();
  941. });
  942. it('should fetch authentication token', function() {
  943. $httpBackend.expectGET('/auth.py');
  944. var controller = createController();
  945. $httpBackend.flush();
  946. });
  947. it('should send msg to server', function() {
  948. var controller = createController();
  949. $httpBackend.flush();
  950. // now you don’t care about the authentication, but
  951. // the controller will still send the request and
  952. // $httpBackend will respond without you having to
  953. // specify the expectation and response for this request
  954. $httpBackend.expectPOST('/add-msg.py', 'message content').respond(201, '');
  955. $rootScope.saveMessage('message content');
  956. expect($rootScope.status).toBe('Saving...');
  957. $httpBackend.flush();
  958. expect($rootScope.status).toBe('');
  959. });
  960. it('should send auth header', function() {
  961. var controller = createController();
  962. $httpBackend.flush();
  963. $httpBackend.expectPOST('/add-msg.py', undefined, function(headers) {
  964. // check if the header was send, if it wasn't the expectation won't
  965. // match the request and the test will fail
  966. return headers['Authorization'] == 'xxx';
  967. }).respond(201, '');
  968. $rootScope.saveMessage('whatever');
  969. $httpBackend.flush();
  970. });
  971. });
  972. </pre>
  973. */
  974. angular.mock.$HttpBackendProvider = function() {
  975. this.$get = ['$rootScope', createHttpBackendMock];
  976. };
  977. /**
  978. * General factory function for $httpBackend mock.
  979. * Returns instance for unit testing (when no arguments specified):
  980. * - passing through is disabled
  981. * - auto flushing is disabled
  982. *
  983. * Returns instance for e2e testing (when `$delegate` and `$browser` specified):
  984. * - passing through (delegating request to real backend) is enabled
  985. * - auto flushing is enabled
  986. *
  987. * @param {Object=} $delegate Real $httpBackend instance (allow passing through if specified)
  988. * @param {Object=} $browser Auto-flushing enabled if specified
  989. * @return {Object} Instance of $httpBackend mock
  990. */
  991. function createHttpBackendMock($rootScope, $delegate, $browser) {
  992. var definitions = [],
  993. expectations = [],
  994. responses = [],
  995. responsesPush = angular.bind(responses, responses.push),
  996. copy = angular.copy;
  997. function createResponse(status, data, headers) {
  998. if (angular.isFunction(status)) return status;
  999. return function() {
  1000. return angular.isNumber(status)
  1001. ? [status, data, headers]
  1002. : [200, status, data];
  1003. };
  1004. }
  1005. // TODO(vojta): change params to: method, url, data, headers, callback
  1006. function $httpBackend(method, url, data, callback, headers, timeout, withCredentials) {
  1007. var xhr = new MockXhr(),
  1008. expectation = expectations[0],
  1009. wasExpected = false;
  1010. function prettyPrint(data) {
  1011. return (angular.isString(data) || angular.isFunction(data) || data instanceof RegExp)
  1012. ? data
  1013. : angular.toJson(data);
  1014. }
  1015. function wrapResponse(wrapped) {
  1016. if (!$browser && timeout && timeout.then) timeout.then(handleTimeout);
  1017. return handleResponse;
  1018. function handleResponse() {
  1019. var response = wrapped.response(method, url, data, headers);
  1020. xhr.$$respHeaders = response[2];
  1021. callback(copy(response[0]), copy(response[1]), xhr.getAllResponseHeaders());
  1022. }
  1023. function handleTimeout() {
  1024. for (var i = 0, ii = responses.length; i < ii; i++) {
  1025. if (responses[i] === handleResponse) {
  1026. responses.splice(i, 1);
  1027. callback(-1, undefined, '');
  1028. break;
  1029. }
  1030. }
  1031. }
  1032. }
  1033. if (expectation && expectation.match(method, url)) {
  1034. if (!expectation.matchData(data))
  1035. throw new Error('Expected ' + expectation + ' with different data\n' +
  1036. 'EXPECTED: ' + prettyPrint(expectation.data) + '\nGOT: ' + data);
  1037. if (!expectation.matchHeaders(headers))
  1038. throw new Error('Expected ' + expectation + ' with different headers\n' +
  1039. 'EXPECTED: ' + prettyPrint(expectation.headers) + '\nGOT: ' +
  1040. prettyPrint(headers));
  1041. expectations.shift();
  1042. if (expectation.response) {
  1043. responses.push(wrapResponse(expectation));
  1044. return;
  1045. }
  1046. wasExpected = true;
  1047. }
  1048. var i = -1, definition;
  1049. while ((definition = definitions[++i])) {
  1050. if (definition.match(method, url, data, headers || {})) {
  1051. if (definition.response) {
  1052. // if $browser specified, we do auto flush all requests
  1053. ($browser ? $browser.defer : responsesPush)(wrapResponse(definition));
  1054. } else if (definition.passThrough) {
  1055. $delegate(method, url, data, callback, headers, timeout, withCredentials);
  1056. } else throw new Error('No response defined !');
  1057. return;
  1058. }
  1059. }
  1060. throw wasExpected ?
  1061. new Error('No response defined !') :
  1062. new Error('Unexpected request: ' + method + ' ' + url + '\n' +
  1063. (expectation ? 'Expected ' + expectation : 'No more request expected'));
  1064. }
  1065. /**
  1066. * @ngdoc method
  1067. * @name ngMock.$httpBackend#when
  1068. * @methodOf ngMock.$httpBackend
  1069. * @description
  1070. * Creates a new backend definition.
  1071. *
  1072. * @param {string} method HTTP method.
  1073. * @param {string|RegExp} url HTTP url.
  1074. * @param {(string|RegExp|function(string))=} data HTTP request body or function that receives
  1075. * data string and returns true if the data is as expected.
  1076. * @param {(Object|function(Object))=} headers HTTP headers or function that receives http header
  1077. * object and returns true if the headers match the current definition.
  1078. * @returns {requestHandler} Returns an object with `respond` method that controls how a matched
  1079. * request is handled.
  1080. *
  1081. * - respond –
  1082. * `{function([status,] data[, headers])|function(function(method, url, data, headers)}`
  1083. * – The respond method takes a set of static data to be returned or a function that can return
  1084. * an array containing response status (number), response data (string) and response headers
  1085. * (Object).
  1086. */
  1087. $httpBackend.when = function(method, url, data, headers) {
  1088. var definition = new MockHttpExpectation(method, url, data, headers),
  1089. chain = {
  1090. respond: function(status, data, headers) {
  1091. definition.response = createResponse(status, data, headers);
  1092. }
  1093. };
  1094. if ($browser) {
  1095. chain.passThrough = function() {
  1096. definition.passThrough = true;
  1097. };
  1098. }
  1099. definitions.push(definition);
  1100. return chain;
  1101. };
  1102. /**
  1103. * @ngdoc method
  1104. * @name ngMock.$httpBackend#whenGET
  1105. * @methodOf ngMock.$httpBackend
  1106. * @description
  1107. * Creates a new backend definition for GET requests. For more info see `when()`.
  1108. *
  1109. * @param {string|RegExp} url HTTP url.
  1110. * @param {(Object|function(Object))=} headers HTTP headers.
  1111. * @returns {requestHandler} Returns an object with `respond` method that control how a matched
  1112. * request is handled.
  1113. */
  1114. /**
  1115. * @ngdoc method
  1116. * @name ngMock.$httpBackend#whenHEAD
  1117. * @methodOf ngMock.$httpBackend
  1118. * @description
  1119. * Creates a new backend definition for HEAD requests. For more info see `when()`.
  1120. *
  1121. * @param {string|RegExp} url HTTP url.
  1122. * @param {(Object|function(Object))=} headers HTTP headers.
  1123. * @returns {requestHandler} Returns an object with `respond` method that control how a matched
  1124. * request is handled.
  1125. */
  1126. /**
  1127. * @ngdoc method
  1128. * @name ngMock.$httpBackend#whenDELETE
  1129. * @methodOf ngMock.$httpBackend
  1130. * @description
  1131. * Creates a new backend definition for DELETE requests. For more info see `when()`.
  1132. *
  1133. * @param {string|RegExp} url HTTP url.
  1134. * @param {(Object|function(Object))=} headers HTTP headers.
  1135. * @returns {requestHandler} Returns an object with `respond` method that control how a matched
  1136. * request is handled.
  1137. */
  1138. /**
  1139. * @ngdoc method
  1140. * @name ngMock.$httpBackend#whenPOST
  1141. * @methodOf ngMock.$httpBackend
  1142. * @description
  1143. * Creates a new backend definition for POST requests. For more info see `when()`.
  1144. *
  1145. * @param {string|RegExp} url HTTP url.
  1146. * @param {(string|RegExp|function(string))=} data HTTP request body or function that receives
  1147. * data string and returns true if the data is as expected.
  1148. * @param {(Object|function(Object))=} headers HTTP headers.
  1149. * @returns {requestHandler} Returns an object with `respond` method that control how a matched
  1150. * request is handled.
  1151. */
  1152. /**
  1153. * @ngdoc method
  1154. * @name ngMock.$httpBackend#whenPUT
  1155. * @methodOf ngMock.$httpBackend
  1156. * @description
  1157. * Creates a new backend definition for PUT requests. For more info see `when()`.
  1158. *
  1159. * @param {string|RegExp} url HTTP url.
  1160. * @param {(string|RegExp|function(string))=} data HTTP request body or function that receives
  1161. * data string and returns true if the data is as expected.
  1162. * @param {(Object|function(Object))=} headers HTTP headers.
  1163. * @returns {requestHandler} Returns an object with `respond` method that control how a matched
  1164. * request is handled.
  1165. */
  1166. /**
  1167. * @ngdoc method
  1168. * @name ngMock.$httpBackend#whenJSONP
  1169. * @methodOf ngMock.$httpBackend
  1170. * @description
  1171. * Creates a new backend definition for JSONP requests. For more info see `when()`.
  1172. *
  1173. * @param {string|RegExp} url HTTP url.
  1174. * @returns {requestHandler} Returns an object with `respond` method that control how a matched
  1175. * request is handled.
  1176. */
  1177. createShortMethods('when');
  1178. /**
  1179. * @ngdoc method
  1180. * @name ngMock.$httpBackend#expect
  1181. * @methodOf ngMock.$httpBackend
  1182. * @description
  1183. * Creates a new request expectation.
  1184. *
  1185. * @param {string} method HTTP method.
  1186. * @param {string|RegExp} url HTTP url.
  1187. * @param {(string|RegExp|function(string)|Object)=} data HTTP request body or function that
  1188. * receives data string and returns true if the data is as expected, or Object if request body
  1189. * is in JSON format.
  1190. * @param {(Object|function(Object))=} headers HTTP headers or function that receives http header
  1191. * object and returns true if the headers match the current expectation.
  1192. * @returns {requestHandler} Returns an object with `respond` method that control how a matched
  1193. * request is handled.
  1194. *
  1195. * - respond –
  1196. * `{function([status,] data[, headers])|function(function(method, url, data, headers)}`
  1197. * – The respond method takes a set of static data to be returned or a function that can return
  1198. * an array containing response status (number), response data (string) and response headers
  1199. * (Object).
  1200. */
  1201. $httpBackend.expect = function(method, url, data, headers) {
  1202. var expectation = new MockHttpExpectation(method, url, data, headers);
  1203. expectations.push(expectation);
  1204. return {
  1205. respond: function(status, data, headers) {
  1206. expectation.response = createResponse(status, data, headers);
  1207. }
  1208. };
  1209. };
  1210. /**
  1211. * @ngdoc method
  1212. * @name ngMock.$httpBackend#expectGET
  1213. * @methodOf ngMock.$httpBackend
  1214. * @description
  1215. * Creates a new request expectation for GET requests. For more info see `expect()`.
  1216. *
  1217. * @param {string|RegExp} url HTTP url.
  1218. * @param {Object=} headers HTTP headers.
  1219. * @returns {requestHandler} Returns an object with `respond` method that control how a matched
  1220. * request is handled. See #expect for more info.
  1221. */
  1222. /**
  1223. * @ngdoc method
  1224. * @name ngMock.$httpBackend#expectHEAD
  1225. * @methodOf ngMock.$httpBackend
  1226. * @description
  1227. * Creates a new request expectation for HEAD requests. For more info see `expect()`.
  1228. *
  1229. * @param {string|RegExp} url HTTP url.
  1230. * @param {Object=} headers HTTP headers.
  1231. * @returns {requestHandler} Returns an object with `respond` method that control how a matched
  1232. * request is handled.
  1233. */
  1234. /**
  1235. * @ngdoc method
  1236. * @name ngMock.$httpBackend#expectDELETE
  1237. * @methodOf ngMock.$httpBackend
  1238. * @description
  1239. * Creates a new request expectation for DELETE requests. For more info see `expect()`.
  1240. *
  1241. * @param {string|RegExp} url HTTP url.
  1242. * @param {Object=} headers HTTP headers.
  1243. * @returns {requestHandler} Returns an object with `respond` method that control how a matched
  1244. * request is handled.
  1245. */
  1246. /**
  1247. * @ngdoc method
  1248. * @name ngMock.$httpBackend#expectPOST
  1249. * @methodOf ngMock.$httpBackend
  1250. * @description
  1251. * Creates a new request expectation for POST requests. For more info see `expect()`.
  1252. *
  1253. * @param {string|RegExp} url HTTP url.
  1254. * @param {(string|RegExp|function(string)|Object)=} data HTTP request body or function that
  1255. * receives data string and returns true if the data is as expected, or Object if request body
  1256. * is in JSON format.
  1257. * @param {Object=} headers HTTP headers.
  1258. * @returns {requestHandler} Returns an object with `respond` method that control how a matched
  1259. * request is handled.
  1260. */
  1261. /**
  1262. * @ngdoc method
  1263. * @name ngMock.$httpBackend#expectPUT
  1264. * @methodOf ngMock.$httpBackend
  1265. * @description
  1266. * Creates a new request expectation for PUT requests. For more info see `expect()`.
  1267. *
  1268. * @param {string|RegExp} url HTTP url.
  1269. * @param {(string|RegExp|function(string)|Object)=} data HTTP request body or function that
  1270. * receives data string and returns true if the data is as expected, or Object if request body
  1271. * is in JSON format.
  1272. * @param {Object=} headers HTTP headers.
  1273. * @returns {requestHandler} Returns an object with `respond` method that control how a matched
  1274. * request is handled.
  1275. */
  1276. /**
  1277. * @ngdoc method
  1278. * @name ngMock.$httpBackend#expectPATCH
  1279. * @methodOf ngMock.$httpBackend
  1280. * @description
  1281. * Creates a new request expectation for PATCH requests. For more info see `expect()`.
  1282. *
  1283. * @param {string|RegExp} url HTTP url.
  1284. * @param {(string|RegExp|function(string)|Object)=} data HTTP request body or function that
  1285. * receives data string and returns true if the data is as expected, or Object if request body
  1286. * is in JSON format.
  1287. * @param {Object=} headers HTTP headers.
  1288. * @returns {requestHandler} Returns an object with `respond` method that control how a matched
  1289. * request is handled.
  1290. */
  1291. /**
  1292. * @ngdoc method
  1293. * @name ngMock.$httpBackend#expectJSONP
  1294. * @methodOf ngMock.$httpBackend
  1295. * @description
  1296. * Creates a new request expectation for JSONP requests. For more info see `expect()`.
  1297. *
  1298. * @param {string|RegExp} url HTTP url.
  1299. * @returns {requestHandler} Returns an object with `respond` method that control how a matched
  1300. * request is handled.
  1301. */
  1302. createShortMethods('expect');
  1303. /**
  1304. * @ngdoc method
  1305. * @name ngMock.$httpBackend#flush
  1306. * @methodOf ngMock.$httpBackend
  1307. * @description
  1308. * Flushes all pending requests using the trained responses.
  1309. *
  1310. * @param {number=} count Number of responses to flush (in the order they arrived). If undefined,
  1311. * all pending requests will be flushed. If there are no pending requests when the flush method
  1312. * is called an exception is thrown (as this typically a sign of programming error).
  1313. */
  1314. $httpBackend.flush = function(count) {
  1315. $rootScope.$digest();
  1316. if (!responses.length) throw new Error('No pending request to flush !');
  1317. if (angular.isDefined(count)) {
  1318. while (count--) {
  1319. if (!responses.length) throw new Error('No more pending request to flush !');
  1320. responses.shift()();
  1321. }
  1322. } else {
  1323. while (responses.length) {
  1324. responses.shift()();
  1325. }
  1326. }
  1327. $httpBackend.verifyNoOutstandingExpectation();
  1328. };
  1329. /**
  1330. * @ngdoc method
  1331. * @name ngMock.$httpBackend#verifyNoOutstandingExpectation
  1332. * @methodOf ngMock.$httpBackend
  1333. * @description
  1334. * Verifies that all of the requests defined via the `expect` api were made. If any of the
  1335. * requests were not made, verifyNoOutstandingExpectation throws an exception.
  1336. *
  1337. * Typically, you would call this method following each test case that asserts requests using an
  1338. * "afterEach" clause.
  1339. *
  1340. * <pre>
  1341. * afterEach($httpBackend.verifyNoOutstandingExpectation);
  1342. * </pre>
  1343. */
  1344. $httpBackend.verifyNoOutstandingExpectation = function() {
  1345. $rootScope.$digest();
  1346. if (expectations.length) {
  1347. throw new Error('Unsatisfied requests: ' + expectations.join(', '));
  1348. }
  1349. };
  1350. /**
  1351. * @ngdoc method
  1352. * @name ngMock.$httpBackend#verifyNoOutstandingRequest
  1353. * @methodOf ngMock.$httpBackend
  1354. * @description
  1355. * Verifies that there are no outstanding requests that need to be flushed.
  1356. *
  1357. * Typically, you would call this method following each test case that asserts requests using an
  1358. * "afterEach" clause.
  1359. *
  1360. * <pre>
  1361. * afterEach($httpBackend.verifyNoOutstandingRequest);
  1362. * </pre>
  1363. */
  1364. $httpBackend.verifyNoOutstandingRequest = function() {
  1365. if (responses.length) {
  1366. throw new Error('Unflushed requests: ' + responses.length);
  1367. }
  1368. };
  1369. /**
  1370. * @ngdoc method
  1371. * @name ngMock.$httpBackend#resetExpectations
  1372. * @methodOf ngMock.$httpBackend
  1373. * @description
  1374. * Resets all request expectations, but preserves all backend definitions. Typically, you would
  1375. * call resetExpectations during a multiple-phase test when you want to reuse the same instance of
  1376. * $httpBackend mock.
  1377. */
  1378. $httpBackend.resetExpectations = function() {
  1379. expectations.length = 0;
  1380. responses.length = 0;
  1381. };
  1382. return $httpBackend;
  1383. function createShortMethods(prefix) {
  1384. angular.forEach(['GET', 'DELETE', 'JSONP'], function(method) {
  1385. $httpBackend[prefix + method] = function(url, headers) {
  1386. return $httpBackend[prefix](method, url, undefined, headers);
  1387. };
  1388. });
  1389. angular.forEach(['PUT', 'POST', 'PATCH'], function(method) {
  1390. $httpBackend[prefix + method] = function(url, data, headers) {
  1391. return $httpBackend[prefix](method, url, data, headers);
  1392. };
  1393. });
  1394. }
  1395. }
  1396. function MockHttpExpectation(method, url, data, headers) {
  1397. this.data = data;
  1398. this.headers = headers;
  1399. this.match = function(m, u, d, h) {
  1400. if (method != m) return false;
  1401. if (!this.matchUrl(u)) return false;
  1402. if (angular.isDefined(d) && !this.matchData(d)) return false;
  1403. if (angular.isDefined(h) && !this.matchHeaders(h)) return false;
  1404. return true;
  1405. };
  1406. this.matchUrl = function(u) {
  1407. if (!url) return true;
  1408. if (angular.isFunction(url.test)) return url.test(u);
  1409. return url == u;
  1410. };
  1411. this.matchHeaders = function(h) {
  1412. if (angular.isUndefined(headers)) return true;
  1413. if (angular.isFunction(headers)) return headers(h);
  1414. return angular.equals(headers, h);
  1415. };
  1416. this.matchData = function(d) {
  1417. if (angular.isUndefined(data)) return true;
  1418. if (data && angular.isFunction(data.test)) return data.test(d);
  1419. if (data && angular.isFunction(data)) return data(d);
  1420. if (data && !angular.isString(data)) return angular.equals(data, angular.fromJson(d));
  1421. return data == d;
  1422. };
  1423. this.toString = function() {
  1424. return method + ' ' + url;
  1425. };
  1426. }
  1427. function createMockXhr() {
  1428. return new MockXhr();
  1429. }
  1430. function MockXhr() {
  1431. // hack for testing $http, $httpBackend
  1432. MockXhr.$$lastInstance = this;
  1433. this.open = function(method, url, async) {
  1434. this.$$method = method;
  1435. this.$$url = url;
  1436. this.$$async = async;
  1437. this.$$reqHeaders = {};
  1438. this.$$respHeaders = {};
  1439. };
  1440. this.send = function(data) {
  1441. this.$$data = data;
  1442. };
  1443. this.setRequestHeader = function(key, value) {
  1444. this.$$reqHeaders[key] = value;
  1445. };
  1446. this.getResponseHeader = function(name) {
  1447. // the lookup must be case insensitive,
  1448. // that's why we try two quick lookups first and full scan last
  1449. var header = this.$$respHeaders[name];
  1450. if (header) return header;
  1451. name = angular.lowercase(name);
  1452. header = this.$$respHeaders[name];
  1453. if (header) return header;
  1454. header = undefined;
  1455. angular.forEach(this.$$respHeaders, function(headerVal, headerName) {
  1456. if (!header && angular.lowercase(headerName) == name) header = headerVal;
  1457. });
  1458. return header;
  1459. };
  1460. this.getAllResponseHeaders = function() {
  1461. var lines = [];
  1462. angular.forEach(this.$$respHeaders, function(value, key) {
  1463. lines.push(key + ': ' + value);
  1464. });
  1465. return lines.join('\n');
  1466. };
  1467. this.abort = angular.noop;
  1468. }
  1469. /**
  1470. * @ngdoc function
  1471. * @name ngMock.$timeout
  1472. * @description
  1473. *
  1474. * This service is just a simple decorator for {@link ng.$timeout $timeout} service
  1475. * that adds a "flush" and "verifyNoPendingTasks" methods.
  1476. */
  1477. angular.mock.$TimeoutDecorator = function($delegate, $browser) {
  1478. /**
  1479. * @ngdoc method
  1480. * @name ngMock.$timeout#flush
  1481. * @methodOf ngMock.$timeout
  1482. * @description
  1483. *
  1484. * Flushes the queue of pending tasks.
  1485. *
  1486. * @param {number=} delay maximum timeout amount to flush up until
  1487. */
  1488. $delegate.flush = function(delay) {
  1489. $browser.defer.flush(delay);
  1490. };
  1491. /**
  1492. * @ngdoc method
  1493. * @name ngMock.$timeout#verifyNoPendingTasks
  1494. * @methodOf ngMock.$timeout
  1495. * @description
  1496. *
  1497. * Verifies that there are no pending tasks that need to be flushed.
  1498. */
  1499. $delegate.verifyNoPendingTasks = function() {
  1500. if ($browser.deferredFns.length) {
  1501. throw new Error('Deferred tasks to flush (' + $browser.deferredFns.length + '): ' +
  1502. formatPendingTasksAsString($browser.deferredFns));
  1503. }
  1504. };
  1505. function formatPendingTasksAsString(tasks) {
  1506. var result = [];
  1507. angular.forEach(tasks, function(task) {
  1508. result.push('{id: ' + task.id + ', ' + 'time: ' + task.time + '}');
  1509. });
  1510. return result.join(', ');
  1511. }
  1512. return $delegate;
  1513. };
  1514. /**
  1515. *
  1516. */
  1517. angular.mock.$RootElementProvider = function() {
  1518. this.$get = function() {
  1519. return angular.element('<div ng-app></div>');
  1520. };
  1521. };
  1522. /**
  1523. * @ngdoc overview
  1524. * @name ngMock
  1525. * @description
  1526. *
  1527. * # ngMock
  1528. *
  1529. * The `ngMock` module providers support to inject and mock Angular services into unit tests.
  1530. * In addition, ngMock also extends various core ng services such that they can be
  1531. * inspected and controlled in a synchronous manner within test code.
  1532. *
  1533. * {@installModule mocks}
  1534. *
  1535. * <div doc-module-components="ngMock"></div>
  1536. *
  1537. */
  1538. angular.module('ngMock', ['ng']).provider({
  1539. $browser: angular.mock.$BrowserProvider,
  1540. $exceptionHandler: angular.mock.$ExceptionHandlerProvider,
  1541. $log: angular.mock.$LogProvider,
  1542. $interval: angular.mock.$IntervalProvider,
  1543. $httpBackend: angular.mock.$HttpBackendProvider,
  1544. $rootElement: angular.mock.$RootElementProvider
  1545. }).config(['$provide', function($provide) {
  1546. $provide.decorator('$timeout', angular.mock.$TimeoutDecorator);
  1547. }]);
  1548. /**
  1549. * @ngdoc overview
  1550. * @name ngMockE2E
  1551. * @description
  1552. *
  1553. * The `ngMockE2E` is an angular module which contains mocks suitable for end-to-end testing.
  1554. * Currently there is only one mock present in this module -
  1555. * the {@link ngMockE2E.$httpBackend e2e $httpBackend} mock.
  1556. */
  1557. angular.module('ngMockE2E', ['ng']).config(['$provide', function($provide) {
  1558. $provide.decorator('$httpBackend', angular.mock.e2e.$httpBackendDecorator);
  1559. }]);
  1560. /**
  1561. * @ngdoc object
  1562. * @name ngMockE2E.$httpBackend
  1563. * @description
  1564. * Fake HTTP backend implementation suitable for end-to-end testing or backend-less development of
  1565. * applications that use the {@link ng.$http $http service}.
  1566. *
  1567. * *Note*: For fake http backend implementation suitable for unit testing please see
  1568. * {@link ngMock.$httpBackend unit-testing $httpBackend mock}.
  1569. *
  1570. * This implementation can be used to respond with static or dynamic responses via the `when` api
  1571. * and its shortcuts (`whenGET`, `whenPOST`, etc) and optionally pass through requests to the
  1572. * real $httpBackend for specific requests (e.g. to interact with certain remote apis or to fetch
  1573. * templates from a webserver).
  1574. *
  1575. * As opposed to unit-testing, in an end-to-end testing scenario or in scenario when an application
  1576. * is being developed with the real backend api replaced with a mock, it is often desirable for
  1577. * certain category of requests to bypass the mock and issue a real http request (e.g. to fetch
  1578. * templates or static files from the webserver). To configure the backend with this behavior
  1579. * use the `passThrough` request handler of `when` instead of `respond`.
  1580. *
  1581. * Additionally, we don't want to manually have to flush mocked out requests like we do during unit
  1582. * testing. For this reason the e2e $httpBackend automatically flushes mocked out requests
  1583. * automatically, closely simulating the behavior of the XMLHttpRequest object.
  1584. *
  1585. * To setup the application to run with this http backend, you have to create a module that depends
  1586. * on the `ngMockE2E` and your application modules and defines the fake backend:
  1587. *
  1588. * <pre>
  1589. * myAppDev = angular.module('myAppDev', ['myApp', 'ngMockE2E']);
  1590. * myAppDev.run(function($httpBackend) {
  1591. * phones = [{name: 'phone1'}, {name: 'phone2'}];
  1592. *
  1593. * // returns the current list of phones
  1594. * $httpBackend.whenGET('/phones').respond(phones);
  1595. *
  1596. * // adds a new phone to the phones array
  1597. * $httpBackend.whenPOST('/phones').respond(function(method, url, data) {
  1598. * phones.push(angular.fromJson(data));
  1599. * });
  1600. * $httpBackend.whenGET(/^\/templates\//).passThrough();
  1601. * //...
  1602. * });
  1603. * </pre>
  1604. *
  1605. * Afterwards, bootstrap your app with this new module.
  1606. */
  1607. /**
  1608. * @ngdoc method
  1609. * @name ngMockE2E.$httpBackend#when
  1610. * @methodOf ngMockE2E.$httpBackend
  1611. * @description
  1612. * Creates a new backend definition.
  1613. *
  1614. * @param {string} method HTTP method.
  1615. * @param {string|RegExp} url HTTP url.
  1616. * @param {(string|RegExp)=} data HTTP request body.
  1617. * @param {(Object|function(Object))=} headers HTTP headers or function that receives http header
  1618. * object and returns true if the headers match the current definition.
  1619. * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
  1620. * control how a matched request is handled.
  1621. *
  1622. * - respond –
  1623. * `{function([status,] data[, headers])|function(function(method, url, data, headers)}`
  1624. * – The respond method takes a set of static data to be returned or a function that can return
  1625. * an array containing response status (number), response data (string) and response headers
  1626. * (Object).
  1627. * - passThrough – `{function()}` – Any request matching a backend definition with `passThrough`
  1628. * handler, will be pass through to the real backend (an XHR request will be made to the
  1629. * server.
  1630. */
  1631. /**
  1632. * @ngdoc method
  1633. * @name ngMockE2E.$httpBackend#whenGET
  1634. * @methodOf ngMockE2E.$httpBackend
  1635. * @description
  1636. * Creates a new backend definition for GET requests. For more info see `when()`.
  1637. *
  1638. * @param {string|RegExp} url HTTP url.
  1639. * @param {(Object|function(Object))=} headers HTTP headers.
  1640. * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
  1641. * control how a matched request is handled.
  1642. */
  1643. /**
  1644. * @ngdoc method
  1645. * @name ngMockE2E.$httpBackend#whenHEAD
  1646. * @methodOf ngMockE2E.$httpBackend
  1647. * @description
  1648. * Creates a new backend definition for HEAD requests. For more info see `when()`.
  1649. *
  1650. * @param {string|RegExp} url HTTP url.
  1651. * @param {(Object|function(Object))=} headers HTTP headers.
  1652. * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
  1653. * control how a matched request is handled.
  1654. */
  1655. /**
  1656. * @ngdoc method
  1657. * @name ngMockE2E.$httpBackend#whenDELETE
  1658. * @methodOf ngMockE2E.$httpBackend
  1659. * @description
  1660. * Creates a new backend definition for DELETE requests. For more info see `when()`.
  1661. *
  1662. * @param {string|RegExp} url HTTP url.
  1663. * @param {(Object|function(Object))=} headers HTTP headers.
  1664. * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
  1665. * control how a matched request is handled.
  1666. */
  1667. /**
  1668. * @ngdoc method
  1669. * @name ngMockE2E.$httpBackend#whenPOST
  1670. * @methodOf ngMockE2E.$httpBackend
  1671. * @description
  1672. * Creates a new backend definition for POST requests. For more info see `when()`.
  1673. *
  1674. * @param {string|RegExp} url HTTP url.
  1675. * @param {(string|RegExp)=} data HTTP request body.
  1676. * @param {(Object|function(Object))=} headers HTTP headers.
  1677. * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
  1678. * control how a matched request is handled.
  1679. */
  1680. /**
  1681. * @ngdoc method
  1682. * @name ngMockE2E.$httpBackend#whenPUT
  1683. * @methodOf ngMockE2E.$httpBackend
  1684. * @description
  1685. * Creates a new backend definition for PUT requests. For more info see `when()`.
  1686. *
  1687. * @param {string|RegExp} url HTTP url.
  1688. * @param {(string|RegExp)=} data HTTP request body.
  1689. * @param {(Object|function(Object))=} headers HTTP headers.
  1690. * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
  1691. * control how a matched request is handled.
  1692. */
  1693. /**
  1694. * @ngdoc method
  1695. * @name ngMockE2E.$httpBackend#whenPATCH
  1696. * @methodOf ngMockE2E.$httpBackend
  1697. * @description
  1698. * Creates a new backend definition for PATCH requests. For more info see `when()`.
  1699. *
  1700. * @param {string|RegExp} url HTTP url.
  1701. * @param {(string|RegExp)=} data HTTP request body.
  1702. * @param {(Object|function(Object))=} headers HTTP headers.
  1703. * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
  1704. * control how a matched request is handled.
  1705. */
  1706. /**
  1707. * @ngdoc method
  1708. * @name ngMockE2E.$httpBackend#whenJSONP
  1709. * @methodOf ngMockE2E.$httpBackend
  1710. * @description
  1711. * Creates a new backend definition for JSONP requests. For more info see `when()`.
  1712. *
  1713. * @param {string|RegExp} url HTTP url.
  1714. * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
  1715. * control how a matched request is handled.
  1716. */
  1717. angular.mock.e2e = {};
  1718. angular.mock.e2e.$httpBackendDecorator =
  1719. ['$rootScope', '$delegate', '$browser', createHttpBackendMock];
  1720. angular.mock.clearDataCache = function() {
  1721. var key,
  1722. cache = angular.element.cache;
  1723. for(key in cache) {
  1724. if (Object.prototype.hasOwnProperty.call(cache,key)) {
  1725. var handle = cache[key].handle;
  1726. handle && angular.element(handle.elem).off();
  1727. delete cache[key];
  1728. }
  1729. }
  1730. };
  1731. if(window.jasmine || window.mocha) {
  1732. var currentSpec = null,
  1733. isSpecRunning = function() {
  1734. return currentSpec && (window.mocha || currentSpec.queue.running);
  1735. };
  1736. beforeEach(function() {
  1737. currentSpec = this;
  1738. });
  1739. afterEach(function() {
  1740. var injector = currentSpec.$injector;
  1741. currentSpec.$injector = null;
  1742. currentSpec.$modules = null;
  1743. currentSpec = null;
  1744. if (injector) {
  1745. injector.get('$rootElement').off();
  1746. injector.get('$browser').pollFns.length = 0;
  1747. }
  1748. angular.mock.clearDataCache();
  1749. // clean up jquery's fragment cache
  1750. angular.forEach(angular.element.fragments, function(val, key) {
  1751. delete angular.element.fragments[key];
  1752. });
  1753. MockXhr.$$lastInstance = null;
  1754. angular.forEach(angular.callbacks, function(val, key) {
  1755. delete angular.callbacks[key];
  1756. });
  1757. angular.callbacks.counter = 0;
  1758. });
  1759. /**
  1760. * @ngdoc function
  1761. * @name angular.mock.module
  1762. * @description
  1763. *
  1764. * *NOTE*: This function is also published on window for easy access.<br>
  1765. *
  1766. * This function registers a module configuration code. It collects the configuration information
  1767. * which will be used when the injector is created by {@link angular.mock.inject inject}.
  1768. *
  1769. * See {@link angular.mock.inject inject} for usage example
  1770. *
  1771. * @param {...(string|Function|Object)} fns any number of modules which are represented as string
  1772. * aliases or as anonymous module initialization functions. The modules are used to
  1773. * configure the injector. The 'ng' and 'ngMock' modules are automatically loaded. If an
  1774. * object literal is passed they will be register as values in the module, the key being
  1775. * the module name and the value being what is returned.
  1776. */
  1777. window.module = angular.mock.module = function() {
  1778. var moduleFns = Array.prototype.slice.call(arguments, 0);
  1779. return isSpecRunning() ? workFn() : workFn;
  1780. /////////////////////
  1781. function workFn() {
  1782. if (currentSpec.$injector) {
  1783. throw new Error('Injector already created, can not register a module!');
  1784. } else {
  1785. var modules = currentSpec.$modules || (currentSpec.$modules = []);
  1786. angular.forEach(moduleFns, function(module) {
  1787. if (angular.isObject(module) && !angular.isArray(module)) {
  1788. modules.push(function($provide) {
  1789. angular.forEach(module, function(value, key) {
  1790. $provide.value(key, value);
  1791. });
  1792. });
  1793. } else {
  1794. modules.push(module);
  1795. }
  1796. });
  1797. }
  1798. }
  1799. };
  1800. /**
  1801. * @ngdoc function
  1802. * @name angular.mock.inject
  1803. * @description
  1804. *
  1805. * *NOTE*: This function is also published on window for easy access.<br>
  1806. *
  1807. * The inject function wraps a function into an injectable function. The inject() creates new
  1808. * instance of {@link AUTO.$injector $injector} per test, which is then used for
  1809. * resolving references.
  1810. *
  1811. *
  1812. * ## Resolving References (Underscore Wrapping)
  1813. * Often, we would like to inject a reference once, in a `beforeEach()` block and reuse this
  1814. * in multiple `it()` clauses. To be able to do this we must assign the reference to a variable
  1815. * that is declared in the scope of the `describe()` block. Since we would, most likely, want
  1816. * the variable to have the same name of the reference we have a problem, since the parameter
  1817. * to the `inject()` function would hide the outer variable.
  1818. *
  1819. * To help with this, the injected parameters can, optionally, be enclosed with underscores.
  1820. * These are ignored by the injector when the reference name is resolved.
  1821. *
  1822. * For example, the parameter `_myService_` would be resolved as the reference `myService`.
  1823. * Since it is available in the function body as _myService_, we can then assign it to a variable
  1824. * defined in an outer scope.
  1825. *
  1826. * ```
  1827. * // Defined out reference variable outside
  1828. * var myService;
  1829. *
  1830. * // Wrap the parameter in underscores
  1831. * beforeEach( inject( function(_myService_){
  1832. * myService = _myService_;
  1833. * }));
  1834. *
  1835. * // Use myService in a series of tests.
  1836. * it('makes use of myService', function() {
  1837. * myService.doStuff();
  1838. * });
  1839. *
  1840. * ```
  1841. *
  1842. * See also {@link angular.mock.module angular.mock.module}
  1843. *
  1844. * ## Example
  1845. * Example of what a typical jasmine tests looks like with the inject method.
  1846. * <pre>
  1847. *
  1848. * angular.module('myApplicationModule', [])
  1849. * .value('mode', 'app')
  1850. * .value('version', 'v1.0.1');
  1851. *
  1852. *
  1853. * describe('MyApp', function() {
  1854. *
  1855. * // You need to load modules that you want to test,
  1856. * // it loads only the "ng" module by default.
  1857. * beforeEach(module('myApplicationModule'));
  1858. *
  1859. *
  1860. * // inject() is used to inject arguments of all given functions
  1861. * it('should provide a version', inject(function(mode, version) {
  1862. * expect(version).toEqual('v1.0.1');
  1863. * expect(mode).toEqual('app');
  1864. * }));
  1865. *
  1866. *
  1867. * // The inject and module method can also be used inside of the it or beforeEach
  1868. * it('should override a version and test the new version is injected', function() {
  1869. * // module() takes functions or strings (module aliases)
  1870. * module(function($provide) {
  1871. * $provide.value('version', 'overridden'); // override version here
  1872. * });
  1873. *
  1874. * inject(function(version) {
  1875. * expect(version).toEqual('overridden');
  1876. * });
  1877. * });
  1878. * });
  1879. *
  1880. * </pre>
  1881. *
  1882. * @param {...Function} fns any number of functions which will be injected using the injector.
  1883. */
  1884. var ErrorAddingDeclarationLocationStack = function(e, errorForStack) {
  1885. this.message = e.message;
  1886. this.name = e.name;
  1887. if (e.line) this.line = e.line;
  1888. if (e.sourceId) this.sourceId = e.sourceId;
  1889. if (e.stack && errorForStack)
  1890. this.stack = e.stack + '\n' + errorForStack.stack;
  1891. if (e.stackArray) this.stackArray = e.stackArray;
  1892. };
  1893. ErrorAddingDeclarationLocationStack.prototype.toString = Error.prototype.toString;
  1894. window.inject = angular.mock.inject = function() {
  1895. var blockFns = Array.prototype.slice.call(arguments, 0);
  1896. var errorForStack = new Error('Declaration Location');
  1897. return isSpecRunning() ? workFn() : workFn;
  1898. /////////////////////
  1899. function workFn() {
  1900. var modules = currentSpec.$modules || [];
  1901. modules.unshift('ngMock');
  1902. modules.unshift('ng');
  1903. var injector = currentSpec.$injector;
  1904. if (!injector) {
  1905. injector = currentSpec.$injector = angular.injector(modules);
  1906. }
  1907. for(var i = 0, ii = blockFns.length; i < ii; i++) {
  1908. try {
  1909. /* jshint -W040 *//* Jasmine explicitly provides a `this` object when calling functions */
  1910. injector.invoke(blockFns[i] || angular.noop, this);
  1911. /* jshint +W040 */
  1912. } catch (e) {
  1913. if (e.stack && errorForStack) {
  1914. throw new ErrorAddingDeclarationLocationStack(e, errorForStack);
  1915. }
  1916. throw e;
  1917. } finally {
  1918. errorForStack = null;
  1919. }
  1920. }
  1921. }
  1922. };
  1923. }
  1924. })(window, window.angular);