angular-mocks.js 74 KB

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