angular-mocks.js 58 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886
  1. /**
  2. * @license AngularJS v1.1.5
  3. * (c) 2010-2012 Google, Inc. http://angularjs.org
  4. * License: MIT
  5. *
  6. * TODO(vojta): wrap whole file into closure during build
  7. */
  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. self.defer.now = 0;
  66. self.defer.cancel = function(deferId) {
  67. var fnIndex;
  68. angular.forEach(self.deferredFns, function(fn, index) {
  69. if (fn.id === deferId) fnIndex = index;
  70. });
  71. if (fnIndex !== undefined) {
  72. self.deferredFns.splice(fnIndex, 1);
  73. return true;
  74. }
  75. return false;
  76. };
  77. /**
  78. * @name ngMock.$browser#defer.flush
  79. * @methodOf ngMock.$browser
  80. *
  81. * @description
  82. * Flushes all pending requests and executes the defer callbacks.
  83. *
  84. * @param {number=} number of milliseconds to flush. See {@link #defer.now}
  85. */
  86. self.defer.flush = function(delay) {
  87. if (angular.isDefined(delay)) {
  88. self.defer.now += delay;
  89. } else {
  90. if (self.deferredFns.length) {
  91. self.defer.now = self.deferredFns[self.deferredFns.length-1].time;
  92. } else {
  93. throw Error('No deferred tasks to be flushed');
  94. }
  95. }
  96. while (self.deferredFns.length && self.deferredFns[0].time <= self.defer.now) {
  97. self.deferredFns.shift().fn();
  98. }
  99. };
  100. /**
  101. * @name ngMock.$browser#defer.now
  102. * @propertyOf ngMock.$browser
  103. *
  104. * @description
  105. * Current milliseconds mock time.
  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 (value == undefined) {
  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 passed
  164. * 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` mode stores an
  215. * array of errors in `$exceptionHandler.errors`, to allow later assertion of them.
  216. * 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 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. function concat(array1, array2, index) {
  258. return array1.concat(Array.prototype.slice.call(array2, index));
  259. }
  260. this.$get = function () {
  261. var $log = {
  262. log: function() { $log.log.logs.push(concat([], arguments, 0)); },
  263. warn: function() { $log.warn.logs.push(concat([], arguments, 0)); },
  264. info: function() { $log.info.logs.push(concat([], arguments, 0)); },
  265. error: function() { $log.error.logs.push(concat([], arguments, 0)); }
  266. };
  267. /**
  268. * @ngdoc method
  269. * @name ngMock.$log#reset
  270. * @methodOf ngMock.$log
  271. *
  272. * @description
  273. * Reset all of the logging arrays to empty.
  274. */
  275. $log.reset = function () {
  276. /**
  277. * @ngdoc property
  278. * @name ngMock.$log#log.logs
  279. * @propertyOf ngMock.$log
  280. *
  281. * @description
  282. * Array of messages logged using {@link ngMock.$log#log}.
  283. *
  284. * @example
  285. * <pre>
  286. * $log.log('Some Log');
  287. * var first = $log.log.logs.unshift();
  288. * </pre>
  289. */
  290. $log.log.logs = [];
  291. /**
  292. * @ngdoc property
  293. * @name ngMock.$log#warn.logs
  294. * @propertyOf ngMock.$log
  295. *
  296. * @description
  297. * Array of messages logged using {@link ngMock.$log#warn}.
  298. *
  299. * @example
  300. * <pre>
  301. * $log.warn('Some Warning');
  302. * var first = $log.warn.logs.unshift();
  303. * </pre>
  304. */
  305. $log.warn.logs = [];
  306. /**
  307. * @ngdoc property
  308. * @name ngMock.$log#info.logs
  309. * @propertyOf ngMock.$log
  310. *
  311. * @description
  312. * Array of messages logged using {@link ngMock.$log#info}.
  313. *
  314. * @example
  315. * <pre>
  316. * $log.info('Some Info');
  317. * var first = $log.info.logs.unshift();
  318. * </pre>
  319. */
  320. $log.info.logs = [];
  321. /**
  322. * @ngdoc property
  323. * @name ngMock.$log#error.logs
  324. * @propertyOf ngMock.$log
  325. *
  326. * @description
  327. * Array of messages logged using {@link ngMock.$log#error}.
  328. *
  329. * @example
  330. * <pre>
  331. * $log.log('Some Error');
  332. * var first = $log.error.logs.unshift();
  333. * </pre>
  334. */
  335. $log.error.logs = [];
  336. };
  337. /**
  338. * @ngdoc method
  339. * @name ngMock.$log#assertEmpty
  340. * @methodOf ngMock.$log
  341. *
  342. * @description
  343. * Assert that the all of the logging methods have no logged messages. If messages present, an exception is thrown.
  344. */
  345. $log.assertEmpty = function() {
  346. var errors = [];
  347. angular.forEach(['error', 'warn', 'info', 'log'], function(logLevel) {
  348. angular.forEach($log[logLevel].logs, function(log) {
  349. angular.forEach(log, function (logItem) {
  350. errors.push('MOCK $log (' + logLevel + '): ' + String(logItem) + '\n' + (logItem.stack || ''));
  351. });
  352. });
  353. });
  354. if (errors.length) {
  355. errors.unshift("Expected $log to be empty! Either a message was logged unexpectedly, or an expected " +
  356. "log message was not checked and removed:");
  357. errors.push('');
  358. throw new Error(errors.join('\n---------\n'));
  359. }
  360. };
  361. $log.reset();
  362. return $log;
  363. };
  364. };
  365. (function() {
  366. var R_ISO8061_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?:\:?(\d\d)(?:\:?(\d\d)(?:\.(\d{3}))?)?)?(Z|([+-])(\d\d):?(\d\d)))?$/;
  367. function jsonStringToDate(string){
  368. var match;
  369. if (match = string.match(R_ISO8061_STR)) {
  370. var date = new Date(0),
  371. tzHour = 0,
  372. tzMin = 0;
  373. if (match[9]) {
  374. tzHour = int(match[9] + match[10]);
  375. tzMin = int(match[9] + match[11]);
  376. }
  377. date.setUTCFullYear(int(match[1]), int(match[2]) - 1, int(match[3]));
  378. date.setUTCHours(int(match[4]||0) - tzHour, int(match[5]||0) - tzMin, int(match[6]||0), int(match[7]||0));
  379. return date;
  380. }
  381. return string;
  382. }
  383. function int(str) {
  384. return parseInt(str, 10);
  385. }
  386. function padNumber(num, digits, trim) {
  387. var neg = '';
  388. if (num < 0) {
  389. neg = '-';
  390. num = -num;
  391. }
  392. num = '' + num;
  393. while(num.length < digits) num = '0' + num;
  394. if (trim)
  395. num = num.substr(num.length - digits);
  396. return neg + num;
  397. }
  398. /**
  399. * @ngdoc object
  400. * @name angular.mock.TzDate
  401. * @description
  402. *
  403. * *NOTE*: this is not an injectable instance, just a globally available mock class of `Date`.
  404. *
  405. * Mock of the Date type which has its timezone specified via constructor arg.
  406. *
  407. * The main purpose is to create Date-like instances with timezone fixed to the specified timezone
  408. * offset, so that we can test code that depends on local timezone settings without dependency on
  409. * the time zone settings of the machine where the code is running.
  410. *
  411. * @param {number} offset Offset of the *desired* timezone in hours (fractions will be honored)
  412. * @param {(number|string)} timestamp Timestamp representing the desired time in *UTC*
  413. *
  414. * @example
  415. * !!!! WARNING !!!!!
  416. * This is not a complete Date object so only methods that were implemented can be called safely.
  417. * To make matters worse, TzDate instances inherit stuff from Date via a prototype.
  418. *
  419. * We do our best to intercept calls to "unimplemented" methods, but since the list of methods is
  420. * incomplete we might be missing some non-standard methods. This can result in errors like:
  421. * "Date.prototype.foo called on incompatible Object".
  422. *
  423. * <pre>
  424. * var newYearInBratislava = new TzDate(-1, '2009-12-31T23:00:00Z');
  425. * newYearInBratislava.getTimezoneOffset() => -60;
  426. * newYearInBratislava.getFullYear() => 2010;
  427. * newYearInBratislava.getMonth() => 0;
  428. * newYearInBratislava.getDate() => 1;
  429. * newYearInBratislava.getHours() => 0;
  430. * newYearInBratislava.getMinutes() => 0;
  431. * newYearInBratislava.getSeconds() => 0;
  432. * </pre>
  433. *
  434. */
  435. angular.mock.TzDate = function (offset, timestamp) {
  436. var self = new Date(0);
  437. if (angular.isString(timestamp)) {
  438. var tsStr = timestamp;
  439. self.origDate = jsonStringToDate(timestamp);
  440. timestamp = self.origDate.getTime();
  441. if (isNaN(timestamp))
  442. throw {
  443. name: "Illegal Argument",
  444. message: "Arg '" + tsStr + "' passed into TzDate constructor is not a valid date string"
  445. };
  446. } else {
  447. self.origDate = new Date(timestamp);
  448. }
  449. var localOffset = new Date(timestamp).getTimezoneOffset();
  450. self.offsetDiff = localOffset*60*1000 - offset*1000*60*60;
  451. self.date = new Date(timestamp + self.offsetDiff);
  452. self.getTime = function() {
  453. return self.date.getTime() - self.offsetDiff;
  454. };
  455. self.toLocaleDateString = function() {
  456. return self.date.toLocaleDateString();
  457. };
  458. self.getFullYear = function() {
  459. return self.date.getFullYear();
  460. };
  461. self.getMonth = function() {
  462. return self.date.getMonth();
  463. };
  464. self.getDate = function() {
  465. return self.date.getDate();
  466. };
  467. self.getHours = function() {
  468. return self.date.getHours();
  469. };
  470. self.getMinutes = function() {
  471. return self.date.getMinutes();
  472. };
  473. self.getSeconds = function() {
  474. return self.date.getSeconds();
  475. };
  476. self.getMilliseconds = function() {
  477. return self.date.getMilliseconds();
  478. };
  479. self.getTimezoneOffset = function() {
  480. return offset * 60;
  481. };
  482. self.getUTCFullYear = function() {
  483. return self.origDate.getUTCFullYear();
  484. };
  485. self.getUTCMonth = function() {
  486. return self.origDate.getUTCMonth();
  487. };
  488. self.getUTCDate = function() {
  489. return self.origDate.getUTCDate();
  490. };
  491. self.getUTCHours = function() {
  492. return self.origDate.getUTCHours();
  493. };
  494. self.getUTCMinutes = function() {
  495. return self.origDate.getUTCMinutes();
  496. };
  497. self.getUTCSeconds = function() {
  498. return self.origDate.getUTCSeconds();
  499. };
  500. self.getUTCMilliseconds = function() {
  501. return self.origDate.getUTCMilliseconds();
  502. };
  503. self.getDay = function() {
  504. return self.date.getDay();
  505. };
  506. // provide this method only on browsers that already have it
  507. if (self.toISOString) {
  508. self.toISOString = function() {
  509. return padNumber(self.origDate.getUTCFullYear(), 4) + '-' +
  510. padNumber(self.origDate.getUTCMonth() + 1, 2) + '-' +
  511. padNumber(self.origDate.getUTCDate(), 2) + 'T' +
  512. padNumber(self.origDate.getUTCHours(), 2) + ':' +
  513. padNumber(self.origDate.getUTCMinutes(), 2) + ':' +
  514. padNumber(self.origDate.getUTCSeconds(), 2) + '.' +
  515. padNumber(self.origDate.getUTCMilliseconds(), 3) + 'Z'
  516. }
  517. }
  518. //hide all methods not implemented in this mock that the Date prototype exposes
  519. var unimplementedMethods = ['getUTCDay',
  520. 'getYear', 'setDate', 'setFullYear', 'setHours', 'setMilliseconds',
  521. 'setMinutes', 'setMonth', 'setSeconds', 'setTime', 'setUTCDate', 'setUTCFullYear',
  522. 'setUTCHours', 'setUTCMilliseconds', 'setUTCMinutes', 'setUTCMonth', 'setUTCSeconds',
  523. 'setYear', 'toDateString', 'toGMTString', 'toJSON', 'toLocaleFormat', 'toLocaleString',
  524. 'toLocaleTimeString', 'toSource', 'toString', 'toTimeString', 'toUTCString', 'valueOf'];
  525. angular.forEach(unimplementedMethods, function(methodName) {
  526. self[methodName] = function() {
  527. throw Error("Method '" + methodName + "' is not implemented in the TzDate mock");
  528. };
  529. });
  530. return self;
  531. };
  532. //make "tzDateInstance instanceof Date" return true
  533. angular.mock.TzDate.prototype = Date.prototype;
  534. })();
  535. /**
  536. * @ngdoc function
  537. * @name angular.mock.createMockWindow
  538. * @description
  539. *
  540. * This function creates a mock window object useful for controlling access ot setTimeout, but mocking out
  541. * sufficient window's properties to allow Angular to execute.
  542. *
  543. * @example
  544. *
  545. * <pre>
  546. beforeEach(module(function($provide) {
  547. $provide.value('$window', window = angular.mock.createMockWindow());
  548. }));
  549. it('should do something', inject(function($window) {
  550. var val = null;
  551. $window.setTimeout(function() { val = 123; }, 10);
  552. expect(val).toEqual(null);
  553. window.setTimeout.expect(10).process();
  554. expect(val).toEqual(123);
  555. });
  556. * </pre>
  557. *
  558. */
  559. angular.mock.createMockWindow = function() {
  560. var mockWindow = {};
  561. var setTimeoutQueue = [];
  562. mockWindow.document = window.document;
  563. mockWindow.getComputedStyle = angular.bind(window, window.getComputedStyle);
  564. mockWindow.scrollTo = angular.bind(window, window.scrollTo);
  565. mockWindow.navigator = window.navigator;
  566. mockWindow.setTimeout = function(fn, delay) {
  567. setTimeoutQueue.push({fn: fn, delay: delay});
  568. };
  569. mockWindow.setTimeout.queue = setTimeoutQueue;
  570. mockWindow.setTimeout.expect = function(delay) {
  571. if (setTimeoutQueue.length > 0) {
  572. return {
  573. process: function() {
  574. var tick = setTimeoutQueue.shift();
  575. expect(tick.delay).toEqual(delay);
  576. tick.fn();
  577. }
  578. };
  579. } else {
  580. expect('SetTimoutQueue empty. Expecting delay of ').toEqual(delay);
  581. }
  582. };
  583. return mockWindow;
  584. };
  585. /**
  586. * @ngdoc function
  587. * @name angular.mock.dump
  588. * @description
  589. *
  590. * *NOTE*: this is not an injectable instance, just a globally available function.
  591. *
  592. * Method for serializing common angular objects (scope, elements, etc..) into strings, useful for debugging.
  593. *
  594. * This method is also available on window, where it can be used to display objects on debug console.
  595. *
  596. * @param {*} object - any object to turn into string.
  597. * @return {string} a serialized string of the argument
  598. */
  599. angular.mock.dump = function(object) {
  600. return serialize(object);
  601. function serialize(object) {
  602. var out;
  603. if (angular.isElement(object)) {
  604. object = angular.element(object);
  605. out = angular.element('<div></div>');
  606. angular.forEach(object, function(element) {
  607. out.append(angular.element(element).clone());
  608. });
  609. out = out.html();
  610. } else if (angular.isArray(object)) {
  611. out = [];
  612. angular.forEach(object, function(o) {
  613. out.push(serialize(o));
  614. });
  615. out = '[ ' + out.join(', ') + ' ]';
  616. } else if (angular.isObject(object)) {
  617. if (angular.isFunction(object.$eval) && angular.isFunction(object.$apply)) {
  618. out = serializeScope(object);
  619. } else if (object instanceof Error) {
  620. out = object.stack || ('' + object.name + ': ' + object.message);
  621. } else {
  622. out = angular.toJson(object, true);
  623. }
  624. } else {
  625. out = String(object);
  626. }
  627. return out;
  628. }
  629. function serializeScope(scope, offset) {
  630. offset = offset || ' ';
  631. var log = [offset + 'Scope(' + scope.$id + '): {'];
  632. for ( var key in scope ) {
  633. if (scope.hasOwnProperty(key) && !key.match(/^(\$|this)/)) {
  634. log.push(' ' + key + ': ' + angular.toJson(scope[key]));
  635. }
  636. }
  637. var child = scope.$$childHead;
  638. while(child) {
  639. log.push(serializeScope(child, offset + ' '));
  640. child = child.$$nextSibling;
  641. }
  642. log.push('}');
  643. return log.join('\n' + offset);
  644. }
  645. };
  646. /**
  647. * @ngdoc object
  648. * @name ngMock.$httpBackend
  649. * @description
  650. * Fake HTTP backend implementation suitable for unit testing applications that use the
  651. * {@link ng.$http $http service}.
  652. *
  653. * *Note*: For fake HTTP backend implementation suitable for end-to-end testing or backend-less
  654. * development please see {@link ngMockE2E.$httpBackend e2e $httpBackend mock}.
  655. *
  656. * During unit testing, we want our unit tests to run quickly and have no external dependencies so
  657. * we don’t want to send {@link https://developer.mozilla.org/en/xmlhttprequest XHR} or
  658. * {@link http://en.wikipedia.org/wiki/JSONP JSONP} requests to a real server. All we really need is
  659. * to verify whether a certain request has been sent or not, or alternatively just let the
  660. * application make requests, respond with pre-trained responses and assert that the end result is
  661. * what we expect it to be.
  662. *
  663. * This mock implementation can be used to respond with static or dynamic responses via the
  664. * `expect` and `when` apis and their shortcuts (`expectGET`, `whenPOST`, etc).
  665. *
  666. * When an Angular application needs some data from a server, it calls the $http service, which
  667. * sends the request to a real server using $httpBackend service. With dependency injection, it is
  668. * easy to inject $httpBackend mock (which has the same API as $httpBackend) and use it to verify
  669. * the requests and respond with some testing data without sending a request to real server.
  670. *
  671. * There are two ways to specify what test data should be returned as http responses by the mock
  672. * backend when the code under test makes http requests:
  673. *
  674. * - `$httpBackend.expect` - specifies a request expectation
  675. * - `$httpBackend.when` - specifies a backend definition
  676. *
  677. *
  678. * # Request Expectations vs Backend Definitions
  679. *
  680. * Request expectations provide a way to make assertions about requests made by the application and
  681. * to define responses for those requests. The test will fail if the expected requests are not made
  682. * or they are made in the wrong order.
  683. *
  684. * Backend definitions allow you to define a fake backend for your application which doesn't assert
  685. * if a particular request was made or not, it just returns a trained response if a request is made.
  686. * The test will pass whether or not the request gets made during testing.
  687. *
  688. *
  689. * <table class="table">
  690. * <tr><th width="220px"></th><th>Request expectations</th><th>Backend definitions</th></tr>
  691. * <tr>
  692. * <th>Syntax</th>
  693. * <td>.expect(...).respond(...)</td>
  694. * <td>.when(...).respond(...)</td>
  695. * </tr>
  696. * <tr>
  697. * <th>Typical usage</th>
  698. * <td>strict unit tests</td>
  699. * <td>loose (black-box) unit testing</td>
  700. * </tr>
  701. * <tr>
  702. * <th>Fulfills multiple requests</th>
  703. * <td>NO</td>
  704. * <td>YES</td>
  705. * </tr>
  706. * <tr>
  707. * <th>Order of requests matters</th>
  708. * <td>YES</td>
  709. * <td>NO</td>
  710. * </tr>
  711. * <tr>
  712. * <th>Request required</th>
  713. * <td>YES</td>
  714. * <td>NO</td>
  715. * </tr>
  716. * <tr>
  717. * <th>Response required</th>
  718. * <td>optional (see below)</td>
  719. * <td>YES</td>
  720. * </tr>
  721. * </table>
  722. *
  723. * In cases where both backend definitions and request expectations are specified during unit
  724. * testing, the request expectations are evaluated first.
  725. *
  726. * If a request expectation has no response specified, the algorithm will search your backend
  727. * definitions for an appropriate response.
  728. *
  729. * If a request didn't match any expectation or if the expectation doesn't have the response
  730. * defined, the backend definitions are evaluated in sequential order to see if any of them match
  731. * the request. The response from the first matched definition is returned.
  732. *
  733. *
  734. * # Flushing HTTP requests
  735. *
  736. * The $httpBackend used in production, always responds to requests with responses asynchronously.
  737. * If we preserved this behavior in unit testing, we'd have to create async unit tests, which are
  738. * hard to write, follow and maintain. At the same time the testing mock, can't respond
  739. * synchronously because that would change the execution of the code under test. For this reason the
  740. * mock $httpBackend has a `flush()` method, which allows the test to explicitly flush pending
  741. * requests and thus preserving the async api of the backend, while allowing the test to execute
  742. * synchronously.
  743. *
  744. *
  745. * # Unit testing with mock $httpBackend
  746. *
  747. * <pre>
  748. // controller
  749. function MyController($scope, $http) {
  750. $http.get('/auth.py').success(function(data) {
  751. $scope.user = data;
  752. });
  753. this.saveMessage = function(message) {
  754. $scope.status = 'Saving...';
  755. $http.post('/add-msg.py', message).success(function(response) {
  756. $scope.status = '';
  757. }).error(function() {
  758. $scope.status = 'ERROR!';
  759. });
  760. };
  761. }
  762. // testing controller
  763. var $httpBackend;
  764. beforeEach(inject(function($injector) {
  765. $httpBackend = $injector.get('$httpBackend');
  766. // backend definition common for all tests
  767. $httpBackend.when('GET', '/auth.py').respond({userId: 'userX'}, {'A-Token': 'xxx'});
  768. }));
  769. afterEach(function() {
  770. $httpBackend.verifyNoOutstandingExpectation();
  771. $httpBackend.verifyNoOutstandingRequest();
  772. });
  773. it('should fetch authentication token', function() {
  774. $httpBackend.expectGET('/auth.py');
  775. var controller = scope.$new(MyController);
  776. $httpBackend.flush();
  777. });
  778. it('should send msg to server', function() {
  779. // now you don’t care about the authentication, but
  780. // the controller will still send the request and
  781. // $httpBackend will respond without you having to
  782. // specify the expectation and response for this request
  783. $httpBackend.expectPOST('/add-msg.py', 'message content').respond(201, '');
  784. var controller = scope.$new(MyController);
  785. $httpBackend.flush();
  786. controller.saveMessage('message content');
  787. expect(controller.status).toBe('Saving...');
  788. $httpBackend.flush();
  789. expect(controller.status).toBe('');
  790. });
  791. it('should send auth header', function() {
  792. $httpBackend.expectPOST('/add-msg.py', undefined, function(headers) {
  793. // check if the header was send, if it wasn't the expectation won't
  794. // match the request and the test will fail
  795. return headers['Authorization'] == 'xxx';
  796. }).respond(201, '');
  797. var controller = scope.$new(MyController);
  798. controller.saveMessage('whatever');
  799. $httpBackend.flush();
  800. });
  801. </pre>
  802. */
  803. angular.mock.$HttpBackendProvider = function() {
  804. this.$get = ['$rootScope', createHttpBackendMock];
  805. };
  806. /**
  807. * General factory function for $httpBackend mock.
  808. * Returns instance for unit testing (when no arguments specified):
  809. * - passing through is disabled
  810. * - auto flushing is disabled
  811. *
  812. * Returns instance for e2e testing (when `$delegate` and `$browser` specified):
  813. * - passing through (delegating request to real backend) is enabled
  814. * - auto flushing is enabled
  815. *
  816. * @param {Object=} $delegate Real $httpBackend instance (allow passing through if specified)
  817. * @param {Object=} $browser Auto-flushing enabled if specified
  818. * @return {Object} Instance of $httpBackend mock
  819. */
  820. function createHttpBackendMock($rootScope, $delegate, $browser) {
  821. var definitions = [],
  822. expectations = [],
  823. responses = [],
  824. responsesPush = angular.bind(responses, responses.push);
  825. function createResponse(status, data, headers) {
  826. if (angular.isFunction(status)) return status;
  827. return function() {
  828. return angular.isNumber(status)
  829. ? [status, data, headers]
  830. : [200, status, data];
  831. };
  832. }
  833. // TODO(vojta): change params to: method, url, data, headers, callback
  834. function $httpBackend(method, url, data, callback, headers, timeout) {
  835. var xhr = new MockXhr(),
  836. expectation = expectations[0],
  837. wasExpected = false;
  838. function prettyPrint(data) {
  839. return (angular.isString(data) || angular.isFunction(data) || data instanceof RegExp)
  840. ? data
  841. : angular.toJson(data);
  842. }
  843. function wrapResponse(wrapped) {
  844. if (!$browser && timeout && timeout.then) timeout.then(handleTimeout);
  845. return handleResponse;
  846. function handleResponse() {
  847. var response = wrapped.response(method, url, data, headers);
  848. xhr.$$respHeaders = response[2];
  849. callback(response[0], response[1], xhr.getAllResponseHeaders());
  850. }
  851. function handleTimeout() {
  852. for (var i = 0, ii = responses.length; i < ii; i++) {
  853. if (responses[i] === handleResponse) {
  854. responses.splice(i, 1);
  855. callback(-1, undefined, '');
  856. break;
  857. }
  858. }
  859. }
  860. }
  861. if (expectation && expectation.match(method, url)) {
  862. if (!expectation.matchData(data))
  863. throw Error('Expected ' + expectation + ' with different data\n' +
  864. 'EXPECTED: ' + prettyPrint(expectation.data) + '\nGOT: ' + data);
  865. if (!expectation.matchHeaders(headers))
  866. throw Error('Expected ' + expectation + ' with different headers\n' +
  867. 'EXPECTED: ' + prettyPrint(expectation.headers) + '\nGOT: ' +
  868. prettyPrint(headers));
  869. expectations.shift();
  870. if (expectation.response) {
  871. responses.push(wrapResponse(expectation));
  872. return;
  873. }
  874. wasExpected = true;
  875. }
  876. var i = -1, definition;
  877. while ((definition = definitions[++i])) {
  878. if (definition.match(method, url, data, headers || {})) {
  879. if (definition.response) {
  880. // if $browser specified, we do auto flush all requests
  881. ($browser ? $browser.defer : responsesPush)(wrapResponse(definition));
  882. } else if (definition.passThrough) {
  883. $delegate(method, url, data, callback, headers, timeout);
  884. } else throw Error('No response defined !');
  885. return;
  886. }
  887. }
  888. throw wasExpected ?
  889. Error('No response defined !') :
  890. Error('Unexpected request: ' + method + ' ' + url + '\n' +
  891. (expectation ? 'Expected ' + expectation : 'No more request expected'));
  892. }
  893. /**
  894. * @ngdoc method
  895. * @name ngMock.$httpBackend#when
  896. * @methodOf ngMock.$httpBackend
  897. * @description
  898. * Creates a new backend definition.
  899. *
  900. * @param {string} method HTTP method.
  901. * @param {string|RegExp} url HTTP url.
  902. * @param {(string|RegExp)=} data HTTP request body.
  903. * @param {(Object|function(Object))=} headers HTTP headers or function that receives http header
  904. * object and returns true if the headers match the current definition.
  905. * @returns {requestHandler} Returns an object with `respond` method that control how a matched
  906. * request is handled.
  907. *
  908. * - respond – `{function([status,] data[, headers])|function(function(method, url, data, headers)}`
  909. * – The respond method takes a set of static data to be returned or a function that can return
  910. * an array containing response status (number), response data (string) and response headers
  911. * (Object).
  912. */
  913. $httpBackend.when = function(method, url, data, headers) {
  914. var definition = new MockHttpExpectation(method, url, data, headers),
  915. chain = {
  916. respond: function(status, data, headers) {
  917. definition.response = createResponse(status, data, headers);
  918. }
  919. };
  920. if ($browser) {
  921. chain.passThrough = function() {
  922. definition.passThrough = true;
  923. };
  924. }
  925. definitions.push(definition);
  926. return chain;
  927. };
  928. /**
  929. * @ngdoc method
  930. * @name ngMock.$httpBackend#whenGET
  931. * @methodOf ngMock.$httpBackend
  932. * @description
  933. * Creates a new backend definition for GET requests. For more info see `when()`.
  934. *
  935. * @param {string|RegExp} url HTTP url.
  936. * @param {(Object|function(Object))=} headers HTTP headers.
  937. * @returns {requestHandler} Returns an object with `respond` method that control how a matched
  938. * request is handled.
  939. */
  940. /**
  941. * @ngdoc method
  942. * @name ngMock.$httpBackend#whenHEAD
  943. * @methodOf ngMock.$httpBackend
  944. * @description
  945. * Creates a new backend definition for HEAD requests. For more info see `when()`.
  946. *
  947. * @param {string|RegExp} url HTTP url.
  948. * @param {(Object|function(Object))=} headers HTTP headers.
  949. * @returns {requestHandler} Returns an object with `respond` method that control how a matched
  950. * request is handled.
  951. */
  952. /**
  953. * @ngdoc method
  954. * @name ngMock.$httpBackend#whenDELETE
  955. * @methodOf ngMock.$httpBackend
  956. * @description
  957. * Creates a new backend definition for DELETE requests. For more info see `when()`.
  958. *
  959. * @param {string|RegExp} url HTTP url.
  960. * @param {(Object|function(Object))=} headers HTTP headers.
  961. * @returns {requestHandler} Returns an object with `respond` method that control how a matched
  962. * request is handled.
  963. */
  964. /**
  965. * @ngdoc method
  966. * @name ngMock.$httpBackend#whenPOST
  967. * @methodOf ngMock.$httpBackend
  968. * @description
  969. * Creates a new backend definition for POST requests. For more info see `when()`.
  970. *
  971. * @param {string|RegExp} url HTTP url.
  972. * @param {(string|RegExp)=} data HTTP request body.
  973. * @param {(Object|function(Object))=} headers HTTP headers.
  974. * @returns {requestHandler} Returns an object with `respond` method that control how a matched
  975. * request is handled.
  976. */
  977. /**
  978. * @ngdoc method
  979. * @name ngMock.$httpBackend#whenPUT
  980. * @methodOf ngMock.$httpBackend
  981. * @description
  982. * Creates a new backend definition for PUT requests. For more info see `when()`.
  983. *
  984. * @param {string|RegExp} url HTTP url.
  985. * @param {(string|RegExp)=} data HTTP request body.
  986. * @param {(Object|function(Object))=} headers HTTP headers.
  987. * @returns {requestHandler} Returns an object with `respond` method that control how a matched
  988. * request is handled.
  989. */
  990. /**
  991. * @ngdoc method
  992. * @name ngMock.$httpBackend#whenJSONP
  993. * @methodOf ngMock.$httpBackend
  994. * @description
  995. * Creates a new backend definition for JSONP requests. For more info see `when()`.
  996. *
  997. * @param {string|RegExp} url HTTP url.
  998. * @returns {requestHandler} Returns an object with `respond` method that control how a matched
  999. * request is handled.
  1000. */
  1001. createShortMethods('when');
  1002. /**
  1003. * @ngdoc method
  1004. * @name ngMock.$httpBackend#expect
  1005. * @methodOf ngMock.$httpBackend
  1006. * @description
  1007. * Creates a new request expectation.
  1008. *
  1009. * @param {string} method HTTP method.
  1010. * @param {string|RegExp} url HTTP url.
  1011. * @param {(string|RegExp)=} data HTTP request body.
  1012. * @param {(Object|function(Object))=} headers HTTP headers or function that receives http header
  1013. * object and returns true if the headers match the current expectation.
  1014. * @returns {requestHandler} Returns an object with `respond` method that control how a matched
  1015. * request is handled.
  1016. *
  1017. * - respond – `{function([status,] data[, headers])|function(function(method, url, data, headers)}`
  1018. * – The respond method takes a set of static data to be returned or a function that can return
  1019. * an array containing response status (number), response data (string) and response headers
  1020. * (Object).
  1021. */
  1022. $httpBackend.expect = function(method, url, data, headers) {
  1023. var expectation = new MockHttpExpectation(method, url, data, headers);
  1024. expectations.push(expectation);
  1025. return {
  1026. respond: function(status, data, headers) {
  1027. expectation.response = createResponse(status, data, headers);
  1028. }
  1029. };
  1030. };
  1031. /**
  1032. * @ngdoc method
  1033. * @name ngMock.$httpBackend#expectGET
  1034. * @methodOf ngMock.$httpBackend
  1035. * @description
  1036. * Creates a new request expectation for GET requests. For more info see `expect()`.
  1037. *
  1038. * @param {string|RegExp} url HTTP url.
  1039. * @param {Object=} headers HTTP headers.
  1040. * @returns {requestHandler} Returns an object with `respond` method that control how a matched
  1041. * request is handled. See #expect for more info.
  1042. */
  1043. /**
  1044. * @ngdoc method
  1045. * @name ngMock.$httpBackend#expectHEAD
  1046. * @methodOf ngMock.$httpBackend
  1047. * @description
  1048. * Creates a new request expectation for HEAD requests. For more info see `expect()`.
  1049. *
  1050. * @param {string|RegExp} url HTTP url.
  1051. * @param {Object=} headers HTTP headers.
  1052. * @returns {requestHandler} Returns an object with `respond` method that control how a matched
  1053. * request is handled.
  1054. */
  1055. /**
  1056. * @ngdoc method
  1057. * @name ngMock.$httpBackend#expectDELETE
  1058. * @methodOf ngMock.$httpBackend
  1059. * @description
  1060. * Creates a new request expectation for DELETE requests. For more info see `expect()`.
  1061. *
  1062. * @param {string|RegExp} url HTTP url.
  1063. * @param {Object=} headers HTTP headers.
  1064. * @returns {requestHandler} Returns an object with `respond` method that control how a matched
  1065. * request is handled.
  1066. */
  1067. /**
  1068. * @ngdoc method
  1069. * @name ngMock.$httpBackend#expectPOST
  1070. * @methodOf ngMock.$httpBackend
  1071. * @description
  1072. * Creates a new request expectation for POST requests. For more info see `expect()`.
  1073. *
  1074. * @param {string|RegExp} url HTTP url.
  1075. * @param {(string|RegExp)=} data HTTP request body.
  1076. * @param {Object=} headers HTTP headers.
  1077. * @returns {requestHandler} Returns an object with `respond` method that control how a matched
  1078. * request is handled.
  1079. */
  1080. /**
  1081. * @ngdoc method
  1082. * @name ngMock.$httpBackend#expectPUT
  1083. * @methodOf ngMock.$httpBackend
  1084. * @description
  1085. * Creates a new request expectation for PUT requests. For more info see `expect()`.
  1086. *
  1087. * @param {string|RegExp} url HTTP url.
  1088. * @param {(string|RegExp)=} data HTTP request body.
  1089. * @param {Object=} headers HTTP headers.
  1090. * @returns {requestHandler} Returns an object with `respond` method that control how a matched
  1091. * request is handled.
  1092. */
  1093. /**
  1094. * @ngdoc method
  1095. * @name ngMock.$httpBackend#expectPATCH
  1096. * @methodOf ngMock.$httpBackend
  1097. * @description
  1098. * Creates a new request expectation for PATCH requests. For more info see `expect()`.
  1099. *
  1100. * @param {string|RegExp} url HTTP url.
  1101. * @param {(string|RegExp)=} data HTTP request body.
  1102. * @param {Object=} headers HTTP headers.
  1103. * @returns {requestHandler} Returns an object with `respond` method that control how a matched
  1104. * request is handled.
  1105. */
  1106. /**
  1107. * @ngdoc method
  1108. * @name ngMock.$httpBackend#expectJSONP
  1109. * @methodOf ngMock.$httpBackend
  1110. * @description
  1111. * Creates a new request expectation for JSONP requests. For more info see `expect()`.
  1112. *
  1113. * @param {string|RegExp} url HTTP url.
  1114. * @returns {requestHandler} Returns an object with `respond` method that control how a matched
  1115. * request is handled.
  1116. */
  1117. createShortMethods('expect');
  1118. /**
  1119. * @ngdoc method
  1120. * @name ngMock.$httpBackend#flush
  1121. * @methodOf ngMock.$httpBackend
  1122. * @description
  1123. * Flushes all pending requests using the trained responses.
  1124. *
  1125. * @param {number=} count Number of responses to flush (in the order they arrived). If undefined,
  1126. * all pending requests will be flushed. If there are no pending requests when the flush method
  1127. * is called an exception is thrown (as this typically a sign of programming error).
  1128. */
  1129. $httpBackend.flush = function(count) {
  1130. $rootScope.$digest();
  1131. if (!responses.length) throw Error('No pending request to flush !');
  1132. if (angular.isDefined(count)) {
  1133. while (count--) {
  1134. if (!responses.length) throw Error('No more pending request to flush !');
  1135. responses.shift()();
  1136. }
  1137. } else {
  1138. while (responses.length) {
  1139. responses.shift()();
  1140. }
  1141. }
  1142. $httpBackend.verifyNoOutstandingExpectation();
  1143. };
  1144. /**
  1145. * @ngdoc method
  1146. * @name ngMock.$httpBackend#verifyNoOutstandingExpectation
  1147. * @methodOf ngMock.$httpBackend
  1148. * @description
  1149. * Verifies that all of the requests defined via the `expect` api were made. If any of the
  1150. * requests were not made, verifyNoOutstandingExpectation throws an exception.
  1151. *
  1152. * Typically, you would call this method following each test case that asserts requests using an
  1153. * "afterEach" clause.
  1154. *
  1155. * <pre>
  1156. * afterEach($httpBackend.verifyExpectations);
  1157. * </pre>
  1158. */
  1159. $httpBackend.verifyNoOutstandingExpectation = function() {
  1160. $rootScope.$digest();
  1161. if (expectations.length) {
  1162. throw Error('Unsatisfied requests: ' + expectations.join(', '));
  1163. }
  1164. };
  1165. /**
  1166. * @ngdoc method
  1167. * @name ngMock.$httpBackend#verifyNoOutstandingRequest
  1168. * @methodOf ngMock.$httpBackend
  1169. * @description
  1170. * Verifies that there are no outstanding requests that need to be flushed.
  1171. *
  1172. * Typically, you would call this method following each test case that asserts requests using an
  1173. * "afterEach" clause.
  1174. *
  1175. * <pre>
  1176. * afterEach($httpBackend.verifyNoOutstandingRequest);
  1177. * </pre>
  1178. */
  1179. $httpBackend.verifyNoOutstandingRequest = function() {
  1180. if (responses.length) {
  1181. throw Error('Unflushed requests: ' + responses.length);
  1182. }
  1183. };
  1184. /**
  1185. * @ngdoc method
  1186. * @name ngMock.$httpBackend#resetExpectations
  1187. * @methodOf ngMock.$httpBackend
  1188. * @description
  1189. * Resets all request expectations, but preserves all backend definitions. Typically, you would
  1190. * call resetExpectations during a multiple-phase test when you want to reuse the same instance of
  1191. * $httpBackend mock.
  1192. */
  1193. $httpBackend.resetExpectations = function() {
  1194. expectations.length = 0;
  1195. responses.length = 0;
  1196. };
  1197. return $httpBackend;
  1198. function createShortMethods(prefix) {
  1199. angular.forEach(['GET', 'DELETE', 'JSONP'], function(method) {
  1200. $httpBackend[prefix + method] = function(url, headers) {
  1201. return $httpBackend[prefix](method, url, undefined, headers)
  1202. }
  1203. });
  1204. angular.forEach(['PUT', 'POST', 'PATCH'], function(method) {
  1205. $httpBackend[prefix + method] = function(url, data, headers) {
  1206. return $httpBackend[prefix](method, url, data, headers)
  1207. }
  1208. });
  1209. }
  1210. }
  1211. function MockHttpExpectation(method, url, data, headers) {
  1212. this.data = data;
  1213. this.headers = headers;
  1214. this.match = function(m, u, d, h) {
  1215. if (method != m) return false;
  1216. if (!this.matchUrl(u)) return false;
  1217. if (angular.isDefined(d) && !this.matchData(d)) return false;
  1218. if (angular.isDefined(h) && !this.matchHeaders(h)) return false;
  1219. return true;
  1220. };
  1221. this.matchUrl = function(u) {
  1222. if (!url) return true;
  1223. if (angular.isFunction(url.test)) return url.test(u);
  1224. return url == u;
  1225. };
  1226. this.matchHeaders = function(h) {
  1227. if (angular.isUndefined(headers)) return true;
  1228. if (angular.isFunction(headers)) return headers(h);
  1229. return angular.equals(headers, h);
  1230. };
  1231. this.matchData = function(d) {
  1232. if (angular.isUndefined(data)) return true;
  1233. if (data && angular.isFunction(data.test)) return data.test(d);
  1234. if (data && !angular.isString(data)) return angular.toJson(data) == d;
  1235. return data == d;
  1236. };
  1237. this.toString = function() {
  1238. return method + ' ' + url;
  1239. };
  1240. }
  1241. function MockXhr() {
  1242. // hack for testing $http, $httpBackend
  1243. MockXhr.$$lastInstance = this;
  1244. this.open = function(method, url, async) {
  1245. this.$$method = method;
  1246. this.$$url = url;
  1247. this.$$async = async;
  1248. this.$$reqHeaders = {};
  1249. this.$$respHeaders = {};
  1250. };
  1251. this.send = function(data) {
  1252. this.$$data = data;
  1253. };
  1254. this.setRequestHeader = function(key, value) {
  1255. this.$$reqHeaders[key] = value;
  1256. };
  1257. this.getResponseHeader = function(name) {
  1258. // the lookup must be case insensitive, that's why we try two quick lookups and full scan at last
  1259. var header = this.$$respHeaders[name];
  1260. if (header) return header;
  1261. name = angular.lowercase(name);
  1262. header = this.$$respHeaders[name];
  1263. if (header) return header;
  1264. header = undefined;
  1265. angular.forEach(this.$$respHeaders, function(headerVal, headerName) {
  1266. if (!header && angular.lowercase(headerName) == name) header = headerVal;
  1267. });
  1268. return header;
  1269. };
  1270. this.getAllResponseHeaders = function() {
  1271. var lines = [];
  1272. angular.forEach(this.$$respHeaders, function(value, key) {
  1273. lines.push(key + ': ' + value);
  1274. });
  1275. return lines.join('\n');
  1276. };
  1277. this.abort = angular.noop;
  1278. }
  1279. /**
  1280. * @ngdoc function
  1281. * @name ngMock.$timeout
  1282. * @description
  1283. *
  1284. * This service is just a simple decorator for {@link ng.$timeout $timeout} service
  1285. * that adds a "flush" and "verifyNoPendingTasks" methods.
  1286. */
  1287. angular.mock.$TimeoutDecorator = function($delegate, $browser) {
  1288. /**
  1289. * @ngdoc method
  1290. * @name ngMock.$timeout#flush
  1291. * @methodOf ngMock.$timeout
  1292. * @description
  1293. *
  1294. * Flushes the queue of pending tasks.
  1295. */
  1296. $delegate.flush = function() {
  1297. $browser.defer.flush();
  1298. };
  1299. /**
  1300. * @ngdoc method
  1301. * @name ngMock.$timeout#verifyNoPendingTasks
  1302. * @methodOf ngMock.$timeout
  1303. * @description
  1304. *
  1305. * Verifies that there are no pending tasks that need to be flushed.
  1306. */
  1307. $delegate.verifyNoPendingTasks = function() {
  1308. if ($browser.deferredFns.length) {
  1309. throw Error('Deferred tasks to flush (' + $browser.deferredFns.length + '): ' +
  1310. formatPendingTasksAsString($browser.deferredFns));
  1311. }
  1312. };
  1313. function formatPendingTasksAsString(tasks) {
  1314. var result = [];
  1315. angular.forEach(tasks, function(task) {
  1316. result.push('{id: ' + task.id + ', ' + 'time: ' + task.time + '}');
  1317. });
  1318. return result.join(', ');
  1319. }
  1320. return $delegate;
  1321. };
  1322. /**
  1323. *
  1324. */
  1325. angular.mock.$RootElementProvider = function() {
  1326. this.$get = function() {
  1327. return angular.element('<div ng-app></div>');
  1328. }
  1329. };
  1330. /**
  1331. * @ngdoc overview
  1332. * @name ngMock
  1333. * @description
  1334. *
  1335. * The `ngMock` is an angular module which is used with `ng` module and adds unit-test configuration as well as useful
  1336. * mocks to the {@link AUTO.$injector $injector}.
  1337. */
  1338. angular.module('ngMock', ['ng']).provider({
  1339. $browser: angular.mock.$BrowserProvider,
  1340. $exceptionHandler: angular.mock.$ExceptionHandlerProvider,
  1341. $log: angular.mock.$LogProvider,
  1342. $httpBackend: angular.mock.$HttpBackendProvider,
  1343. $rootElement: angular.mock.$RootElementProvider
  1344. }).config(function($provide) {
  1345. $provide.decorator('$timeout', angular.mock.$TimeoutDecorator);
  1346. });
  1347. /**
  1348. * @ngdoc overview
  1349. * @name ngMockE2E
  1350. * @description
  1351. *
  1352. * The `ngMockE2E` is an angular module which contains mocks suitable for end-to-end testing.
  1353. * Currently there is only one mock present in this module -
  1354. * the {@link ngMockE2E.$httpBackend e2e $httpBackend} mock.
  1355. */
  1356. angular.module('ngMockE2E', ['ng']).config(function($provide) {
  1357. $provide.decorator('$httpBackend', angular.mock.e2e.$httpBackendDecorator);
  1358. });
  1359. /**
  1360. * @ngdoc object
  1361. * @name ngMockE2E.$httpBackend
  1362. * @description
  1363. * Fake HTTP backend implementation suitable for end-to-end testing or backend-less development of
  1364. * applications that use the {@link ng.$http $http service}.
  1365. *
  1366. * *Note*: For fake http backend implementation suitable for unit testing please see
  1367. * {@link ngMock.$httpBackend unit-testing $httpBackend mock}.
  1368. *
  1369. * This implementation can be used to respond with static or dynamic responses via the `when` api
  1370. * and its shortcuts (`whenGET`, `whenPOST`, etc) and optionally pass through requests to the
  1371. * real $httpBackend for specific requests (e.g. to interact with certain remote apis or to fetch
  1372. * templates from a webserver).
  1373. *
  1374. * As opposed to unit-testing, in an end-to-end testing scenario or in scenario when an application
  1375. * is being developed with the real backend api replaced with a mock, it is often desirable for
  1376. * certain category of requests to bypass the mock and issue a real http request (e.g. to fetch
  1377. * templates or static files from the webserver). To configure the backend with this behavior
  1378. * use the `passThrough` request handler of `when` instead of `respond`.
  1379. *
  1380. * Additionally, we don't want to manually have to flush mocked out requests like we do during unit
  1381. * testing. For this reason the e2e $httpBackend automatically flushes mocked out requests
  1382. * automatically, closely simulating the behavior of the XMLHttpRequest object.
  1383. *
  1384. * To setup the application to run with this http backend, you have to create a module that depends
  1385. * on the `ngMockE2E` and your application modules and defines the fake backend:
  1386. *
  1387. * <pre>
  1388. * myAppDev = angular.module('myAppDev', ['myApp', 'ngMockE2E']);
  1389. * myAppDev.run(function($httpBackend) {
  1390. * phones = [{name: 'phone1'}, {name: 'phone2'}];
  1391. *
  1392. * // returns the current list of phones
  1393. * $httpBackend.whenGET('/phones').respond(phones);
  1394. *
  1395. * // adds a new phone to the phones array
  1396. * $httpBackend.whenPOST('/phones').respond(function(method, url, data) {
  1397. * phones.push(angular.fromJSON(data));
  1398. * });
  1399. * $httpBackend.whenGET(/^\/templates\//).passThrough();
  1400. * //...
  1401. * });
  1402. * </pre>
  1403. *
  1404. * Afterwards, bootstrap your app with this new module.
  1405. */
  1406. /**
  1407. * @ngdoc method
  1408. * @name ngMockE2E.$httpBackend#when
  1409. * @methodOf ngMockE2E.$httpBackend
  1410. * @description
  1411. * Creates a new backend definition.
  1412. *
  1413. * @param {string} method HTTP method.
  1414. * @param {string|RegExp} url HTTP url.
  1415. * @param {(string|RegExp)=} data HTTP request body.
  1416. * @param {(Object|function(Object))=} headers HTTP headers or function that receives http header
  1417. * object and returns true if the headers match the current definition.
  1418. * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
  1419. * control how a matched request is handled.
  1420. *
  1421. * - respond – `{function([status,] data[, headers])|function(function(method, url, data, headers)}`
  1422. * – The respond method takes a set of static data to be returned or a function that can return
  1423. * an array containing response status (number), response data (string) and response headers
  1424. * (Object).
  1425. * - passThrough – `{function()}` – Any request matching a backend definition with `passThrough`
  1426. * handler, will be pass through to the real backend (an XHR request will be made to the
  1427. * server.
  1428. */
  1429. /**
  1430. * @ngdoc method
  1431. * @name ngMockE2E.$httpBackend#whenGET
  1432. * @methodOf ngMockE2E.$httpBackend
  1433. * @description
  1434. * Creates a new backend definition for GET requests. For more info see `when()`.
  1435. *
  1436. * @param {string|RegExp} url HTTP url.
  1437. * @param {(Object|function(Object))=} headers HTTP headers.
  1438. * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
  1439. * control how a matched request is handled.
  1440. */
  1441. /**
  1442. * @ngdoc method
  1443. * @name ngMockE2E.$httpBackend#whenHEAD
  1444. * @methodOf ngMockE2E.$httpBackend
  1445. * @description
  1446. * Creates a new backend definition for HEAD requests. For more info see `when()`.
  1447. *
  1448. * @param {string|RegExp} url HTTP url.
  1449. * @param {(Object|function(Object))=} headers HTTP headers.
  1450. * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
  1451. * control how a matched request is handled.
  1452. */
  1453. /**
  1454. * @ngdoc method
  1455. * @name ngMockE2E.$httpBackend#whenDELETE
  1456. * @methodOf ngMockE2E.$httpBackend
  1457. * @description
  1458. * Creates a new backend definition for DELETE requests. For more info see `when()`.
  1459. *
  1460. * @param {string|RegExp} url HTTP url.
  1461. * @param {(Object|function(Object))=} headers HTTP headers.
  1462. * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
  1463. * control how a matched request is handled.
  1464. */
  1465. /**
  1466. * @ngdoc method
  1467. * @name ngMockE2E.$httpBackend#whenPOST
  1468. * @methodOf ngMockE2E.$httpBackend
  1469. * @description
  1470. * Creates a new backend definition for POST requests. For more info see `when()`.
  1471. *
  1472. * @param {string|RegExp} url HTTP url.
  1473. * @param {(string|RegExp)=} data HTTP request body.
  1474. * @param {(Object|function(Object))=} headers HTTP headers.
  1475. * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
  1476. * control how a matched request is handled.
  1477. */
  1478. /**
  1479. * @ngdoc method
  1480. * @name ngMockE2E.$httpBackend#whenPUT
  1481. * @methodOf ngMockE2E.$httpBackend
  1482. * @description
  1483. * Creates a new backend definition for PUT requests. For more info see `when()`.
  1484. *
  1485. * @param {string|RegExp} url HTTP url.
  1486. * @param {(string|RegExp)=} data HTTP request body.
  1487. * @param {(Object|function(Object))=} headers HTTP headers.
  1488. * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
  1489. * control how a matched request is handled.
  1490. */
  1491. /**
  1492. * @ngdoc method
  1493. * @name ngMockE2E.$httpBackend#whenPATCH
  1494. * @methodOf ngMockE2E.$httpBackend
  1495. * @description
  1496. * Creates a new backend definition for PATCH requests. For more info see `when()`.
  1497. *
  1498. * @param {string|RegExp} url HTTP url.
  1499. * @param {(string|RegExp)=} data HTTP request body.
  1500. * @param {(Object|function(Object))=} headers HTTP headers.
  1501. * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
  1502. * control how a matched request is handled.
  1503. */
  1504. /**
  1505. * @ngdoc method
  1506. * @name ngMockE2E.$httpBackend#whenJSONP
  1507. * @methodOf ngMockE2E.$httpBackend
  1508. * @description
  1509. * Creates a new backend definition for JSONP requests. For more info see `when()`.
  1510. *
  1511. * @param {string|RegExp} url HTTP url.
  1512. * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
  1513. * control how a matched request is handled.
  1514. */
  1515. angular.mock.e2e = {};
  1516. angular.mock.e2e.$httpBackendDecorator = ['$rootScope', '$delegate', '$browser', createHttpBackendMock];
  1517. angular.mock.clearDataCache = function() {
  1518. var key,
  1519. cache = angular.element.cache;
  1520. for(key in cache) {
  1521. if (cache.hasOwnProperty(key)) {
  1522. var handle = cache[key].handle;
  1523. handle && angular.element(handle.elem).unbind();
  1524. delete cache[key];
  1525. }
  1526. }
  1527. };
  1528. window.jstestdriver && (function(window) {
  1529. /**
  1530. * Global method to output any number of objects into JSTD console. Useful for debugging.
  1531. */
  1532. window.dump = function() {
  1533. var args = [];
  1534. angular.forEach(arguments, function(arg) {
  1535. args.push(angular.mock.dump(arg));
  1536. });
  1537. jstestdriver.console.log.apply(jstestdriver.console, args);
  1538. if (window.console) {
  1539. window.console.log.apply(window.console, args);
  1540. }
  1541. };
  1542. })(window);
  1543. (window.jasmine || window.mocha) && (function(window) {
  1544. var currentSpec = null;
  1545. beforeEach(function() {
  1546. currentSpec = this;
  1547. });
  1548. afterEach(function() {
  1549. var injector = currentSpec.$injector;
  1550. currentSpec.$injector = null;
  1551. currentSpec.$modules = null;
  1552. currentSpec = null;
  1553. if (injector) {
  1554. injector.get('$rootElement').unbind();
  1555. injector.get('$browser').pollFns.length = 0;
  1556. }
  1557. angular.mock.clearDataCache();
  1558. // clean up jquery's fragment cache
  1559. angular.forEach(angular.element.fragments, function(val, key) {
  1560. delete angular.element.fragments[key];
  1561. });
  1562. MockXhr.$$lastInstance = null;
  1563. angular.forEach(angular.callbacks, function(val, key) {
  1564. delete angular.callbacks[key];
  1565. });
  1566. angular.callbacks.counter = 0;
  1567. });
  1568. function isSpecRunning() {
  1569. return currentSpec && (window.mocha || currentSpec.queue.running);
  1570. }
  1571. /**
  1572. * @ngdoc function
  1573. * @name angular.mock.module
  1574. * @description
  1575. *
  1576. * *NOTE*: This function is also published on window for easy access.<br>
  1577. *
  1578. * This function registers a module configuration code. It collects the configuration information
  1579. * which will be used when the injector is created by {@link angular.mock.inject inject}.
  1580. *
  1581. * See {@link angular.mock.inject inject} for usage example
  1582. *
  1583. * @param {...(string|Function)} fns any number of modules which are represented as string
  1584. * aliases or as anonymous module initialization functions. The modules are used to
  1585. * configure the injector. The 'ng' and 'ngMock' modules are automatically loaded.
  1586. */
  1587. window.module = angular.mock.module = function() {
  1588. var moduleFns = Array.prototype.slice.call(arguments, 0);
  1589. return isSpecRunning() ? workFn() : workFn;
  1590. /////////////////////
  1591. function workFn() {
  1592. if (currentSpec.$injector) {
  1593. throw Error('Injector already created, can not register a module!');
  1594. } else {
  1595. var modules = currentSpec.$modules || (currentSpec.$modules = []);
  1596. angular.forEach(moduleFns, function(module) {
  1597. modules.push(module);
  1598. });
  1599. }
  1600. }
  1601. };
  1602. /**
  1603. * @ngdoc function
  1604. * @name angular.mock.inject
  1605. * @description
  1606. *
  1607. * *NOTE*: This function is also published on window for easy access.<br>
  1608. *
  1609. * The inject function wraps a function into an injectable function. The inject() creates new
  1610. * instance of {@link AUTO.$injector $injector} per test, which is then used for
  1611. * resolving references.
  1612. *
  1613. * See also {@link angular.mock.module module}
  1614. *
  1615. * Example of what a typical jasmine tests looks like with the inject method.
  1616. * <pre>
  1617. *
  1618. * angular.module('myApplicationModule', [])
  1619. * .value('mode', 'app')
  1620. * .value('version', 'v1.0.1');
  1621. *
  1622. *
  1623. * describe('MyApp', function() {
  1624. *
  1625. * // You need to load modules that you want to test,
  1626. * // it loads only the "ng" module by default.
  1627. * beforeEach(module('myApplicationModule'));
  1628. *
  1629. *
  1630. * // inject() is used to inject arguments of all given functions
  1631. * it('should provide a version', inject(function(mode, version) {
  1632. * expect(version).toEqual('v1.0.1');
  1633. * expect(mode).toEqual('app');
  1634. * }));
  1635. *
  1636. *
  1637. * // The inject and module method can also be used inside of the it or beforeEach
  1638. * it('should override a version and test the new version is injected', function() {
  1639. * // module() takes functions or strings (module aliases)
  1640. * module(function($provide) {
  1641. * $provide.value('version', 'overridden'); // override version here
  1642. * });
  1643. *
  1644. * inject(function(version) {
  1645. * expect(version).toEqual('overridden');
  1646. * });
  1647. * ));
  1648. * });
  1649. *
  1650. * </pre>
  1651. *
  1652. * @param {...Function} fns any number of functions which will be injected using the injector.
  1653. */
  1654. window.inject = angular.mock.inject = function() {
  1655. var blockFns = Array.prototype.slice.call(arguments, 0);
  1656. var errorForStack = new Error('Declaration Location');
  1657. return isSpecRunning() ? workFn() : workFn;
  1658. /////////////////////
  1659. function workFn() {
  1660. var modules = currentSpec.$modules || [];
  1661. modules.unshift('ngMock');
  1662. modules.unshift('ng');
  1663. var injector = currentSpec.$injector;
  1664. if (!injector) {
  1665. injector = currentSpec.$injector = angular.injector(modules);
  1666. }
  1667. for(var i = 0, ii = blockFns.length; i < ii; i++) {
  1668. try {
  1669. injector.invoke(blockFns[i] || angular.noop, this);
  1670. } catch (e) {
  1671. if(e.stack && errorForStack) e.stack += '\n' + errorForStack.stack;
  1672. throw e;
  1673. } finally {
  1674. errorForStack = null;
  1675. }
  1676. }
  1677. }
  1678. };
  1679. })(window);