jasmine.js 69 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600
  1. var isCommonJS = typeof window == "undefined" && typeof exports == "object";
  2. /**
  3. * Top level namespace for Jasmine, a lightweight JavaScript BDD/spec/testing framework.
  4. *
  5. * @namespace
  6. */
  7. var jasmine = {};
  8. if (isCommonJS) exports.jasmine = jasmine;
  9. /**
  10. * @private
  11. */
  12. jasmine.unimplementedMethod_ = function() {
  13. throw new Error("unimplemented method");
  14. };
  15. /**
  16. * Use <code>jasmine.undefined</code> instead of <code>undefined</code>, since <code>undefined</code> is just
  17. * a plain old variable and may be redefined by somebody else.
  18. *
  19. * @private
  20. */
  21. jasmine.undefined = jasmine.___undefined___;
  22. /**
  23. * Show diagnostic messages in the console if set to true
  24. *
  25. */
  26. jasmine.VERBOSE = false;
  27. /**
  28. * Default interval in milliseconds for event loop yields (e.g. to allow network activity or to refresh the screen with the HTML-based runner). Small values here may result in slow test running. Zero means no updates until all tests have completed.
  29. *
  30. */
  31. jasmine.DEFAULT_UPDATE_INTERVAL = 250;
  32. /**
  33. * Maximum levels of nesting that will be included when an object is pretty-printed
  34. */
  35. jasmine.MAX_PRETTY_PRINT_DEPTH = 40;
  36. /**
  37. * Default timeout interval in milliseconds for waitsFor() blocks.
  38. */
  39. jasmine.DEFAULT_TIMEOUT_INTERVAL = 5000;
  40. /**
  41. * By default exceptions thrown in the context of a test are caught by jasmine so that it can run the remaining tests in the suite.
  42. * Set to false to let the exception bubble up in the browser.
  43. *
  44. */
  45. jasmine.CATCH_EXCEPTIONS = true;
  46. jasmine.getGlobal = function() {
  47. function getGlobal() {
  48. return this;
  49. }
  50. return getGlobal();
  51. };
  52. /**
  53. * Allows for bound functions to be compared. Internal use only.
  54. *
  55. * @ignore
  56. * @private
  57. * @param base {Object} bound 'this' for the function
  58. * @param name {Function} function to find
  59. */
  60. jasmine.bindOriginal_ = function(base, name) {
  61. var original = base[name];
  62. if (original.apply) {
  63. return function() {
  64. return original.apply(base, arguments);
  65. };
  66. } else {
  67. // IE support
  68. return jasmine.getGlobal()[name];
  69. }
  70. };
  71. jasmine.setTimeout = jasmine.bindOriginal_(jasmine.getGlobal(), 'setTimeout');
  72. jasmine.clearTimeout = jasmine.bindOriginal_(jasmine.getGlobal(), 'clearTimeout');
  73. jasmine.setInterval = jasmine.bindOriginal_(jasmine.getGlobal(), 'setInterval');
  74. jasmine.clearInterval = jasmine.bindOriginal_(jasmine.getGlobal(), 'clearInterval');
  75. jasmine.MessageResult = function(values) {
  76. this.type = 'log';
  77. this.values = values;
  78. this.trace = new Error(); // todo: test better
  79. };
  80. jasmine.MessageResult.prototype.toString = function() {
  81. var text = "";
  82. for (var i = 0; i < this.values.length; i++) {
  83. if (i > 0) text += " ";
  84. if (jasmine.isString_(this.values[i])) {
  85. text += this.values[i];
  86. } else {
  87. text += jasmine.pp(this.values[i]);
  88. }
  89. }
  90. return text;
  91. };
  92. jasmine.ExpectationResult = function(params) {
  93. this.type = 'expect';
  94. this.matcherName = params.matcherName;
  95. this.passed_ = params.passed;
  96. this.expected = params.expected;
  97. this.actual = params.actual;
  98. this.message = this.passed_ ? 'Passed.' : params.message;
  99. var trace = (params.trace || new Error(this.message));
  100. this.trace = this.passed_ ? '' : trace;
  101. };
  102. jasmine.ExpectationResult.prototype.toString = function () {
  103. return this.message;
  104. };
  105. jasmine.ExpectationResult.prototype.passed = function () {
  106. return this.passed_;
  107. };
  108. /**
  109. * Getter for the Jasmine environment. Ensures one gets created
  110. */
  111. jasmine.getEnv = function() {
  112. var env = jasmine.currentEnv_ = jasmine.currentEnv_ || new jasmine.Env();
  113. return env;
  114. };
  115. /**
  116. * @ignore
  117. * @private
  118. * @param value
  119. * @returns {Boolean}
  120. */
  121. jasmine.isArray_ = function(value) {
  122. return jasmine.isA_("Array", value);
  123. };
  124. /**
  125. * @ignore
  126. * @private
  127. * @param value
  128. * @returns {Boolean}
  129. */
  130. jasmine.isString_ = function(value) {
  131. return jasmine.isA_("String", value);
  132. };
  133. /**
  134. * @ignore
  135. * @private
  136. * @param value
  137. * @returns {Boolean}
  138. */
  139. jasmine.isNumber_ = function(value) {
  140. return jasmine.isA_("Number", value);
  141. };
  142. /**
  143. * @ignore
  144. * @private
  145. * @param {String} typeName
  146. * @param value
  147. * @returns {Boolean}
  148. */
  149. jasmine.isA_ = function(typeName, value) {
  150. return Object.prototype.toString.apply(value) === '[object ' + typeName + ']';
  151. };
  152. /**
  153. * Pretty printer for expecations. Takes any object and turns it into a human-readable string.
  154. *
  155. * @param value {Object} an object to be outputted
  156. * @returns {String}
  157. */
  158. jasmine.pp = function(value) {
  159. var stringPrettyPrinter = new jasmine.StringPrettyPrinter();
  160. stringPrettyPrinter.format(value);
  161. return stringPrettyPrinter.string;
  162. };
  163. /**
  164. * Returns true if the object is a DOM Node.
  165. *
  166. * @param {Object} obj object to check
  167. * @returns {Boolean}
  168. */
  169. jasmine.isDomNode = function(obj) {
  170. return obj.nodeType > 0;
  171. };
  172. /**
  173. * Returns a matchable 'generic' object of the class type. For use in expecations of type when values don't matter.
  174. *
  175. * @example
  176. * // don't care about which function is passed in, as long as it's a function
  177. * expect(mySpy).toHaveBeenCalledWith(jasmine.any(Function));
  178. *
  179. * @param {Class} clazz
  180. * @returns matchable object of the type clazz
  181. */
  182. jasmine.any = function(clazz) {
  183. return new jasmine.Matchers.Any(clazz);
  184. };
  185. /**
  186. * Returns a matchable subset of a JSON object. For use in expectations when you don't care about all of the
  187. * attributes on the object.
  188. *
  189. * @example
  190. * // don't care about any other attributes than foo.
  191. * expect(mySpy).toHaveBeenCalledWith(jasmine.objectContaining({foo: "bar"});
  192. *
  193. * @param sample {Object} sample
  194. * @returns matchable object for the sample
  195. */
  196. jasmine.objectContaining = function (sample) {
  197. return new jasmine.Matchers.ObjectContaining(sample);
  198. };
  199. /**
  200. * Jasmine Spies are test doubles that can act as stubs, spies, fakes or when used in an expecation, mocks.
  201. *
  202. * Spies should be created in test setup, before expectations. They can then be checked, using the standard Jasmine
  203. * expectation syntax. Spies can be checked if they were called or not and what the calling params were.
  204. *
  205. * A Spy has the following fields: wasCalled, callCount, mostRecentCall, and argsForCall (see docs).
  206. *
  207. * Spies are torn down at the end of every spec.
  208. *
  209. * Note: Do <b>not</b> call new jasmine.Spy() directly - a spy must be created using spyOn, jasmine.createSpy or jasmine.createSpyObj.
  210. *
  211. * @example
  212. * // a stub
  213. * var myStub = jasmine.createSpy('myStub'); // can be used anywhere
  214. *
  215. * // spy example
  216. * var foo = {
  217. * not: function(bool) { return !bool; }
  218. * }
  219. *
  220. * // actual foo.not will not be called, execution stops
  221. * spyOn(foo, 'not');
  222. // foo.not spied upon, execution will continue to implementation
  223. * spyOn(foo, 'not').andCallThrough();
  224. *
  225. * // fake example
  226. * var foo = {
  227. * not: function(bool) { return !bool; }
  228. * }
  229. *
  230. * // foo.not(val) will return val
  231. * spyOn(foo, 'not').andCallFake(function(value) {return value;});
  232. *
  233. * // mock example
  234. * foo.not(7 == 7);
  235. * expect(foo.not).toHaveBeenCalled();
  236. * expect(foo.not).toHaveBeenCalledWith(true);
  237. *
  238. * @constructor
  239. * @see spyOn, jasmine.createSpy, jasmine.createSpyObj
  240. * @param {String} name
  241. */
  242. jasmine.Spy = function(name) {
  243. /**
  244. * The name of the spy, if provided.
  245. */
  246. this.identity = name || 'unknown';
  247. /**
  248. * Is this Object a spy?
  249. */
  250. this.isSpy = true;
  251. /**
  252. * The actual function this spy stubs.
  253. */
  254. this.plan = function() {
  255. };
  256. /**
  257. * Tracking of the most recent call to the spy.
  258. * @example
  259. * var mySpy = jasmine.createSpy('foo');
  260. * mySpy(1, 2);
  261. * mySpy.mostRecentCall.args = [1, 2];
  262. */
  263. this.mostRecentCall = {};
  264. /**
  265. * Holds arguments for each call to the spy, indexed by call count
  266. * @example
  267. * var mySpy = jasmine.createSpy('foo');
  268. * mySpy(1, 2);
  269. * mySpy(7, 8);
  270. * mySpy.mostRecentCall.args = [7, 8];
  271. * mySpy.argsForCall[0] = [1, 2];
  272. * mySpy.argsForCall[1] = [7, 8];
  273. */
  274. this.argsForCall = [];
  275. this.calls = [];
  276. };
  277. /**
  278. * Tells a spy to call through to the actual implemenatation.
  279. *
  280. * @example
  281. * var foo = {
  282. * bar: function() { // do some stuff }
  283. * }
  284. *
  285. * // defining a spy on an existing property: foo.bar
  286. * spyOn(foo, 'bar').andCallThrough();
  287. */
  288. jasmine.Spy.prototype.andCallThrough = function() {
  289. this.plan = this.originalValue;
  290. return this;
  291. };
  292. /**
  293. * For setting the return value of a spy.
  294. *
  295. * @example
  296. * // defining a spy from scratch: foo() returns 'baz'
  297. * var foo = jasmine.createSpy('spy on foo').andReturn('baz');
  298. *
  299. * // defining a spy on an existing property: foo.bar() returns 'baz'
  300. * spyOn(foo, 'bar').andReturn('baz');
  301. *
  302. * @param {Object} value
  303. */
  304. jasmine.Spy.prototype.andReturn = function(value) {
  305. this.plan = function() {
  306. return value;
  307. };
  308. return this;
  309. };
  310. /**
  311. * For throwing an exception when a spy is called.
  312. *
  313. * @example
  314. * // defining a spy from scratch: foo() throws an exception w/ message 'ouch'
  315. * var foo = jasmine.createSpy('spy on foo').andThrow('baz');
  316. *
  317. * // defining a spy on an existing property: foo.bar() throws an exception w/ message 'ouch'
  318. * spyOn(foo, 'bar').andThrow('baz');
  319. *
  320. * @param {String} exceptionMsg
  321. */
  322. jasmine.Spy.prototype.andThrow = function(exceptionMsg) {
  323. this.plan = function() {
  324. throw exceptionMsg;
  325. };
  326. return this;
  327. };
  328. /**
  329. * Calls an alternate implementation when a spy is called.
  330. *
  331. * @example
  332. * var baz = function() {
  333. * // do some stuff, return something
  334. * }
  335. * // defining a spy from scratch: foo() calls the function baz
  336. * var foo = jasmine.createSpy('spy on foo').andCall(baz);
  337. *
  338. * // defining a spy on an existing property: foo.bar() calls an anonymnous function
  339. * spyOn(foo, 'bar').andCall(function() { return 'baz';} );
  340. *
  341. * @param {Function} fakeFunc
  342. */
  343. jasmine.Spy.prototype.andCallFake = function(fakeFunc) {
  344. this.plan = fakeFunc;
  345. return this;
  346. };
  347. /**
  348. * Resets all of a spy's the tracking variables so that it can be used again.
  349. *
  350. * @example
  351. * spyOn(foo, 'bar');
  352. *
  353. * foo.bar();
  354. *
  355. * expect(foo.bar.callCount).toEqual(1);
  356. *
  357. * foo.bar.reset();
  358. *
  359. * expect(foo.bar.callCount).toEqual(0);
  360. */
  361. jasmine.Spy.prototype.reset = function() {
  362. this.wasCalled = false;
  363. this.callCount = 0;
  364. this.argsForCall = [];
  365. this.calls = [];
  366. this.mostRecentCall = {};
  367. };
  368. jasmine.createSpy = function(name) {
  369. var spyObj = function() {
  370. spyObj.wasCalled = true;
  371. spyObj.callCount++;
  372. var args = jasmine.util.argsToArray(arguments);
  373. spyObj.mostRecentCall.object = this;
  374. spyObj.mostRecentCall.args = args;
  375. spyObj.argsForCall.push(args);
  376. spyObj.calls.push({object: this, args: args});
  377. return spyObj.plan.apply(this, arguments);
  378. };
  379. var spy = new jasmine.Spy(name);
  380. for (var prop in spy) {
  381. spyObj[prop] = spy[prop];
  382. }
  383. spyObj.reset();
  384. return spyObj;
  385. };
  386. /**
  387. * Determines whether an object is a spy.
  388. *
  389. * @param {jasmine.Spy|Object} putativeSpy
  390. * @returns {Boolean}
  391. */
  392. jasmine.isSpy = function(putativeSpy) {
  393. return putativeSpy && putativeSpy.isSpy;
  394. };
  395. /**
  396. * Creates a more complicated spy: an Object that has every property a function that is a spy. Used for stubbing something
  397. * large in one call.
  398. *
  399. * @param {String} baseName name of spy class
  400. * @param {Array} methodNames array of names of methods to make spies
  401. */
  402. jasmine.createSpyObj = function(baseName, methodNames) {
  403. if (!jasmine.isArray_(methodNames) || methodNames.length === 0) {
  404. throw new Error('createSpyObj requires a non-empty array of method names to create spies for');
  405. }
  406. var obj = {};
  407. for (var i = 0; i < methodNames.length; i++) {
  408. obj[methodNames[i]] = jasmine.createSpy(baseName + '.' + methodNames[i]);
  409. }
  410. return obj;
  411. };
  412. /**
  413. * All parameters are pretty-printed and concatenated together, then written to the current spec's output.
  414. *
  415. * Be careful not to leave calls to <code>jasmine.log</code> in production code.
  416. */
  417. jasmine.log = function() {
  418. var spec = jasmine.getEnv().currentSpec;
  419. spec.log.apply(spec, arguments);
  420. };
  421. /**
  422. * Function that installs a spy on an existing object's method name. Used within a Spec to create a spy.
  423. *
  424. * @example
  425. * // spy example
  426. * var foo = {
  427. * not: function(bool) { return !bool; }
  428. * }
  429. * spyOn(foo, 'not'); // actual foo.not will not be called, execution stops
  430. *
  431. * @see jasmine.createSpy
  432. * @param obj
  433. * @param methodName
  434. * @return {jasmine.Spy} a Jasmine spy that can be chained with all spy methods
  435. */
  436. var spyOn = function(obj, methodName) {
  437. return jasmine.getEnv().currentSpec.spyOn(obj, methodName);
  438. };
  439. if (isCommonJS) exports.spyOn = spyOn;
  440. /**
  441. * Creates a Jasmine spec that will be added to the current suite.
  442. *
  443. * // TODO: pending tests
  444. *
  445. * @example
  446. * it('should be true', function() {
  447. * expect(true).toEqual(true);
  448. * });
  449. *
  450. * @param {String} desc description of this specification
  451. * @param {Function} func defines the preconditions and expectations of the spec
  452. */
  453. var it = function(desc, func) {
  454. return jasmine.getEnv().it(desc, func);
  455. };
  456. if (isCommonJS) exports.it = it;
  457. /**
  458. * Creates a <em>disabled</em> Jasmine spec.
  459. *
  460. * A convenience method that allows existing specs to be disabled temporarily during development.
  461. *
  462. * @param {String} desc description of this specification
  463. * @param {Function} func defines the preconditions and expectations of the spec
  464. */
  465. var xit = function(desc, func) {
  466. return jasmine.getEnv().xit(desc, func);
  467. };
  468. if (isCommonJS) exports.xit = xit;
  469. /**
  470. * Starts a chain for a Jasmine expectation.
  471. *
  472. * It is passed an Object that is the actual value and should chain to one of the many
  473. * jasmine.Matchers functions.
  474. *
  475. * @param {Object} actual Actual value to test against and expected value
  476. * @return {jasmine.Matchers}
  477. */
  478. var expect = function(actual) {
  479. return jasmine.getEnv().currentSpec.expect(actual);
  480. };
  481. if (isCommonJS) exports.expect = expect;
  482. /**
  483. * Defines part of a jasmine spec. Used in cominbination with waits or waitsFor in asynchrnous specs.
  484. *
  485. * @param {Function} func Function that defines part of a jasmine spec.
  486. */
  487. var runs = function(func) {
  488. jasmine.getEnv().currentSpec.runs(func);
  489. };
  490. if (isCommonJS) exports.runs = runs;
  491. /**
  492. * Waits a fixed time period before moving to the next block.
  493. *
  494. * @deprecated Use waitsFor() instead
  495. * @param {Number} timeout milliseconds to wait
  496. */
  497. var waits = function(timeout) {
  498. jasmine.getEnv().currentSpec.waits(timeout);
  499. };
  500. if (isCommonJS) exports.waits = waits;
  501. /**
  502. * Waits for the latchFunction to return true before proceeding to the next block.
  503. *
  504. * @param {Function} latchFunction
  505. * @param {String} optional_timeoutMessage
  506. * @param {Number} optional_timeout
  507. */
  508. var waitsFor = function(latchFunction, optional_timeoutMessage, optional_timeout) {
  509. jasmine.getEnv().currentSpec.waitsFor.apply(jasmine.getEnv().currentSpec, arguments);
  510. };
  511. if (isCommonJS) exports.waitsFor = waitsFor;
  512. /**
  513. * A function that is called before each spec in a suite.
  514. *
  515. * Used for spec setup, including validating assumptions.
  516. *
  517. * @param {Function} beforeEachFunction
  518. */
  519. var beforeEach = function(beforeEachFunction) {
  520. jasmine.getEnv().beforeEach(beforeEachFunction);
  521. };
  522. if (isCommonJS) exports.beforeEach = beforeEach;
  523. /**
  524. * A function that is called after each spec in a suite.
  525. *
  526. * Used for restoring any state that is hijacked during spec execution.
  527. *
  528. * @param {Function} afterEachFunction
  529. */
  530. var afterEach = function(afterEachFunction) {
  531. jasmine.getEnv().afterEach(afterEachFunction);
  532. };
  533. if (isCommonJS) exports.afterEach = afterEach;
  534. /**
  535. * Defines a suite of specifications.
  536. *
  537. * Stores the description and all defined specs in the Jasmine environment as one suite of specs. Variables declared
  538. * are accessible by calls to beforeEach, it, and afterEach. Describe blocks can be nested, allowing for specialization
  539. * of setup in some tests.
  540. *
  541. * @example
  542. * // TODO: a simple suite
  543. *
  544. * // TODO: a simple suite with a nested describe block
  545. *
  546. * @param {String} description A string, usually the class under test.
  547. * @param {Function} specDefinitions function that defines several specs.
  548. */
  549. var describe = function(description, specDefinitions) {
  550. return jasmine.getEnv().describe(description, specDefinitions);
  551. };
  552. if (isCommonJS) exports.describe = describe;
  553. /**
  554. * Disables a suite of specifications. Used to disable some suites in a file, or files, temporarily during development.
  555. *
  556. * @param {String} description A string, usually the class under test.
  557. * @param {Function} specDefinitions function that defines several specs.
  558. */
  559. var xdescribe = function(description, specDefinitions) {
  560. return jasmine.getEnv().xdescribe(description, specDefinitions);
  561. };
  562. if (isCommonJS) exports.xdescribe = xdescribe;
  563. // Provide the XMLHttpRequest class for IE 5.x-6.x:
  564. jasmine.XmlHttpRequest = (typeof XMLHttpRequest == "undefined") ? function() {
  565. function tryIt(f) {
  566. try {
  567. return f();
  568. } catch(e) {
  569. }
  570. return null;
  571. }
  572. var xhr = tryIt(function() {
  573. return new ActiveXObject("Msxml2.XMLHTTP.6.0");
  574. }) ||
  575. tryIt(function() {
  576. return new ActiveXObject("Msxml2.XMLHTTP.3.0");
  577. }) ||
  578. tryIt(function() {
  579. return new ActiveXObject("Msxml2.XMLHTTP");
  580. }) ||
  581. tryIt(function() {
  582. return new ActiveXObject("Microsoft.XMLHTTP");
  583. });
  584. if (!xhr) throw new Error("This browser does not support XMLHttpRequest.");
  585. return xhr;
  586. } : XMLHttpRequest;
  587. /**
  588. * @namespace
  589. */
  590. jasmine.util = {};
  591. /**
  592. * Declare that a child class inherit it's prototype from the parent class.
  593. *
  594. * @private
  595. * @param {Function} childClass
  596. * @param {Function} parentClass
  597. */
  598. jasmine.util.inherit = function(childClass, parentClass) {
  599. /**
  600. * @private
  601. */
  602. var subclass = function() {
  603. };
  604. subclass.prototype = parentClass.prototype;
  605. childClass.prototype = new subclass();
  606. };
  607. jasmine.util.formatException = function(e) {
  608. var lineNumber;
  609. if (e.line) {
  610. lineNumber = e.line;
  611. }
  612. else if (e.lineNumber) {
  613. lineNumber = e.lineNumber;
  614. }
  615. var file;
  616. if (e.sourceURL) {
  617. file = e.sourceURL;
  618. }
  619. else if (e.fileName) {
  620. file = e.fileName;
  621. }
  622. var message = (e.name && e.message) ? (e.name + ': ' + e.message) : e.toString();
  623. if (file && lineNumber) {
  624. message += ' in ' + file + ' (line ' + lineNumber + ')';
  625. }
  626. return message;
  627. };
  628. jasmine.util.htmlEscape = function(str) {
  629. if (!str) return str;
  630. return str.replace(/&/g, '&amp;')
  631. .replace(/</g, '&lt;')
  632. .replace(/>/g, '&gt;');
  633. };
  634. jasmine.util.argsToArray = function(args) {
  635. var arrayOfArgs = [];
  636. for (var i = 0; i < args.length; i++) arrayOfArgs.push(args[i]);
  637. return arrayOfArgs;
  638. };
  639. jasmine.util.extend = function(destination, source) {
  640. for (var property in source) destination[property] = source[property];
  641. return destination;
  642. };
  643. /**
  644. * Environment for Jasmine
  645. *
  646. * @constructor
  647. */
  648. jasmine.Env = function() {
  649. this.currentSpec = null;
  650. this.currentSuite = null;
  651. this.currentRunner_ = new jasmine.Runner(this);
  652. this.reporter = new jasmine.MultiReporter();
  653. this.updateInterval = jasmine.DEFAULT_UPDATE_INTERVAL;
  654. this.defaultTimeoutInterval = jasmine.DEFAULT_TIMEOUT_INTERVAL;
  655. this.lastUpdate = 0;
  656. this.specFilter = function() {
  657. return true;
  658. };
  659. this.nextSpecId_ = 0;
  660. this.nextSuiteId_ = 0;
  661. this.equalityTesters_ = [];
  662. // wrap matchers
  663. this.matchersClass = function() {
  664. jasmine.Matchers.apply(this, arguments);
  665. };
  666. jasmine.util.inherit(this.matchersClass, jasmine.Matchers);
  667. jasmine.Matchers.wrapInto_(jasmine.Matchers.prototype, this.matchersClass);
  668. };
  669. jasmine.Env.prototype.setTimeout = jasmine.setTimeout;
  670. jasmine.Env.prototype.clearTimeout = jasmine.clearTimeout;
  671. jasmine.Env.prototype.setInterval = jasmine.setInterval;
  672. jasmine.Env.prototype.clearInterval = jasmine.clearInterval;
  673. /**
  674. * @returns an object containing jasmine version build info, if set.
  675. */
  676. jasmine.Env.prototype.version = function () {
  677. if (jasmine.version_) {
  678. return jasmine.version_;
  679. } else {
  680. throw new Error('Version not set');
  681. }
  682. };
  683. /**
  684. * @returns string containing jasmine version build info, if set.
  685. */
  686. jasmine.Env.prototype.versionString = function() {
  687. if (!jasmine.version_) {
  688. return "version unknown";
  689. }
  690. var version = this.version();
  691. var versionString = version.major + "." + version.minor + "." + version.build;
  692. if (version.release_candidate) {
  693. versionString += ".rc" + version.release_candidate;
  694. }
  695. versionString += " revision " + version.revision;
  696. return versionString;
  697. };
  698. /**
  699. * @returns a sequential integer starting at 0
  700. */
  701. jasmine.Env.prototype.nextSpecId = function () {
  702. return this.nextSpecId_++;
  703. };
  704. /**
  705. * @returns a sequential integer starting at 0
  706. */
  707. jasmine.Env.prototype.nextSuiteId = function () {
  708. return this.nextSuiteId_++;
  709. };
  710. /**
  711. * Register a reporter to receive status updates from Jasmine.
  712. * @param {jasmine.Reporter} reporter An object which will receive status updates.
  713. */
  714. jasmine.Env.prototype.addReporter = function(reporter) {
  715. this.reporter.addReporter(reporter);
  716. };
  717. jasmine.Env.prototype.execute = function() {
  718. this.currentRunner_.execute();
  719. };
  720. jasmine.Env.prototype.describe = function(description, specDefinitions) {
  721. var suite = new jasmine.Suite(this, description, specDefinitions, this.currentSuite);
  722. var parentSuite = this.currentSuite;
  723. if (parentSuite) {
  724. parentSuite.add(suite);
  725. } else {
  726. this.currentRunner_.add(suite);
  727. }
  728. this.currentSuite = suite;
  729. var declarationError = null;
  730. try {
  731. specDefinitions.call(suite);
  732. } catch(e) {
  733. declarationError = e;
  734. }
  735. if (declarationError) {
  736. this.it("encountered a declaration exception", function() {
  737. throw declarationError;
  738. });
  739. }
  740. this.currentSuite = parentSuite;
  741. return suite;
  742. };
  743. jasmine.Env.prototype.beforeEach = function(beforeEachFunction) {
  744. if (this.currentSuite) {
  745. this.currentSuite.beforeEach(beforeEachFunction);
  746. } else {
  747. this.currentRunner_.beforeEach(beforeEachFunction);
  748. }
  749. };
  750. jasmine.Env.prototype.currentRunner = function () {
  751. return this.currentRunner_;
  752. };
  753. jasmine.Env.prototype.afterEach = function(afterEachFunction) {
  754. if (this.currentSuite) {
  755. this.currentSuite.afterEach(afterEachFunction);
  756. } else {
  757. this.currentRunner_.afterEach(afterEachFunction);
  758. }
  759. };
  760. jasmine.Env.prototype.xdescribe = function(desc, specDefinitions) {
  761. return {
  762. execute: function() {
  763. }
  764. };
  765. };
  766. jasmine.Env.prototype.it = function(description, func) {
  767. var spec = new jasmine.Spec(this, this.currentSuite, description);
  768. this.currentSuite.add(spec);
  769. this.currentSpec = spec;
  770. if (func) {
  771. spec.runs(func);
  772. }
  773. return spec;
  774. };
  775. jasmine.Env.prototype.xit = function(desc, func) {
  776. return {
  777. id: this.nextSpecId(),
  778. runs: function() {
  779. }
  780. };
  781. };
  782. jasmine.Env.prototype.compareRegExps_ = function(a, b, mismatchKeys, mismatchValues) {
  783. if (a.source != b.source)
  784. mismatchValues.push("expected pattern /" + b.source + "/ is not equal to the pattern /" + a.source + "/");
  785. if (a.ignoreCase != b.ignoreCase)
  786. mismatchValues.push("expected modifier i was" + (b.ignoreCase ? " " : " not ") + "set and does not equal the origin modifier");
  787. if (a.global != b.global)
  788. mismatchValues.push("expected modifier g was" + (b.global ? " " : " not ") + "set and does not equal the origin modifier");
  789. if (a.multiline != b.multiline)
  790. mismatchValues.push("expected modifier m was" + (b.multiline ? " " : " not ") + "set and does not equal the origin modifier");
  791. if (a.sticky != b.sticky)
  792. mismatchValues.push("expected modifier y was" + (b.sticky ? " " : " not ") + "set and does not equal the origin modifier");
  793. return (mismatchValues.length === 0);
  794. };
  795. jasmine.Env.prototype.compareObjects_ = function(a, b, mismatchKeys, mismatchValues) {
  796. if (a.__Jasmine_been_here_before__ === b && b.__Jasmine_been_here_before__ === a) {
  797. return true;
  798. }
  799. a.__Jasmine_been_here_before__ = b;
  800. b.__Jasmine_been_here_before__ = a;
  801. var hasKey = function(obj, keyName) {
  802. return obj !== null && obj[keyName] !== jasmine.undefined;
  803. };
  804. for (var property in b) {
  805. if (!hasKey(a, property) && hasKey(b, property)) {
  806. mismatchKeys.push("expected has key '" + property + "', but missing from actual.");
  807. }
  808. }
  809. for (property in a) {
  810. if (!hasKey(b, property) && hasKey(a, property)) {
  811. mismatchKeys.push("expected missing key '" + property + "', but present in actual.");
  812. }
  813. }
  814. for (property in b) {
  815. if (property == '__Jasmine_been_here_before__') continue;
  816. if (!this.equals_(a[property], b[property], mismatchKeys, mismatchValues)) {
  817. mismatchValues.push("'" + property + "' was '" + (b[property] ? jasmine.util.htmlEscape(b[property].toString()) : b[property]) + "' in expected, but was '" + (a[property] ? jasmine.util.htmlEscape(a[property].toString()) : a[property]) + "' in actual.");
  818. }
  819. }
  820. if (jasmine.isArray_(a) && jasmine.isArray_(b) && a.length != b.length) {
  821. mismatchValues.push("arrays were not the same length");
  822. }
  823. delete a.__Jasmine_been_here_before__;
  824. delete b.__Jasmine_been_here_before__;
  825. return (mismatchKeys.length === 0 && mismatchValues.length === 0);
  826. };
  827. jasmine.Env.prototype.equals_ = function(a, b, mismatchKeys, mismatchValues) {
  828. mismatchKeys = mismatchKeys || [];
  829. mismatchValues = mismatchValues || [];
  830. for (var i = 0; i < this.equalityTesters_.length; i++) {
  831. var equalityTester = this.equalityTesters_[i];
  832. var result = equalityTester(a, b, this, mismatchKeys, mismatchValues);
  833. if (result !== jasmine.undefined) return result;
  834. }
  835. if (a === b) return true;
  836. if (a === jasmine.undefined || a === null || b === jasmine.undefined || b === null) {
  837. return (a == jasmine.undefined && b == jasmine.undefined);
  838. }
  839. if (jasmine.isDomNode(a) && jasmine.isDomNode(b)) {
  840. return a === b;
  841. }
  842. if (a instanceof Date && b instanceof Date) {
  843. return a.getTime() == b.getTime();
  844. }
  845. if (a.jasmineMatches) {
  846. return a.jasmineMatches(b);
  847. }
  848. if (b.jasmineMatches) {
  849. return b.jasmineMatches(a);
  850. }
  851. if (a instanceof jasmine.Matchers.ObjectContaining) {
  852. return a.matches(b);
  853. }
  854. if (b instanceof jasmine.Matchers.ObjectContaining) {
  855. return b.matches(a);
  856. }
  857. if (jasmine.isString_(a) && jasmine.isString_(b)) {
  858. return (a == b);
  859. }
  860. if (jasmine.isNumber_(a) && jasmine.isNumber_(b)) {
  861. return (a == b);
  862. }
  863. if (a instanceof RegExp && b instanceof RegExp) {
  864. return this.compareRegExps_(a, b, mismatchKeys, mismatchValues);
  865. }
  866. if (typeof a === "object" && typeof b === "object") {
  867. return this.compareObjects_(a, b, mismatchKeys, mismatchValues);
  868. }
  869. //Straight check
  870. return (a === b);
  871. };
  872. jasmine.Env.prototype.contains_ = function(haystack, needle) {
  873. if (jasmine.isArray_(haystack)) {
  874. for (var i = 0; i < haystack.length; i++) {
  875. if (this.equals_(haystack[i], needle)) return true;
  876. }
  877. return false;
  878. }
  879. return haystack.indexOf(needle) >= 0;
  880. };
  881. jasmine.Env.prototype.addEqualityTester = function(equalityTester) {
  882. this.equalityTesters_.push(equalityTester);
  883. };
  884. /** No-op base class for Jasmine reporters.
  885. *
  886. * @constructor
  887. */
  888. jasmine.Reporter = function() {
  889. };
  890. //noinspection JSUnusedLocalSymbols
  891. jasmine.Reporter.prototype.reportRunnerStarting = function(runner) {
  892. };
  893. //noinspection JSUnusedLocalSymbols
  894. jasmine.Reporter.prototype.reportRunnerResults = function(runner) {
  895. };
  896. //noinspection JSUnusedLocalSymbols
  897. jasmine.Reporter.prototype.reportSuiteResults = function(suite) {
  898. };
  899. //noinspection JSUnusedLocalSymbols
  900. jasmine.Reporter.prototype.reportSpecStarting = function(spec) {
  901. };
  902. //noinspection JSUnusedLocalSymbols
  903. jasmine.Reporter.prototype.reportSpecResults = function(spec) {
  904. };
  905. //noinspection JSUnusedLocalSymbols
  906. jasmine.Reporter.prototype.log = function(str) {
  907. };
  908. /**
  909. * Blocks are functions with executable code that make up a spec.
  910. *
  911. * @constructor
  912. * @param {jasmine.Env} env
  913. * @param {Function} func
  914. * @param {jasmine.Spec} spec
  915. */
  916. jasmine.Block = function(env, func, spec) {
  917. this.env = env;
  918. this.func = func;
  919. this.spec = spec;
  920. };
  921. jasmine.Block.prototype.execute = function(onComplete) {
  922. if (!jasmine.CATCH_EXCEPTIONS) {
  923. this.func.apply(this.spec);
  924. }
  925. else {
  926. try {
  927. this.func.apply(this.spec);
  928. } catch (e) {
  929. this.spec.fail(e);
  930. }
  931. }
  932. onComplete();
  933. };
  934. /** JavaScript API reporter.
  935. *
  936. * @constructor
  937. */
  938. jasmine.JsApiReporter = function() {
  939. this.started = false;
  940. this.finished = false;
  941. this.suites_ = [];
  942. this.results_ = {};
  943. };
  944. jasmine.JsApiReporter.prototype.reportRunnerStarting = function(runner) {
  945. this.started = true;
  946. var suites = runner.topLevelSuites();
  947. for (var i = 0; i < suites.length; i++) {
  948. var suite = suites[i];
  949. this.suites_.push(this.summarize_(suite));
  950. }
  951. };
  952. jasmine.JsApiReporter.prototype.suites = function() {
  953. return this.suites_;
  954. };
  955. jasmine.JsApiReporter.prototype.summarize_ = function(suiteOrSpec) {
  956. var isSuite = suiteOrSpec instanceof jasmine.Suite;
  957. var summary = {
  958. id: suiteOrSpec.id,
  959. name: suiteOrSpec.description,
  960. type: isSuite ? 'suite' : 'spec',
  961. children: []
  962. };
  963. if (isSuite) {
  964. var children = suiteOrSpec.children();
  965. for (var i = 0; i < children.length; i++) {
  966. summary.children.push(this.summarize_(children[i]));
  967. }
  968. }
  969. return summary;
  970. };
  971. jasmine.JsApiReporter.prototype.results = function() {
  972. return this.results_;
  973. };
  974. jasmine.JsApiReporter.prototype.resultsForSpec = function(specId) {
  975. return this.results_[specId];
  976. };
  977. //noinspection JSUnusedLocalSymbols
  978. jasmine.JsApiReporter.prototype.reportRunnerResults = function(runner) {
  979. this.finished = true;
  980. };
  981. //noinspection JSUnusedLocalSymbols
  982. jasmine.JsApiReporter.prototype.reportSuiteResults = function(suite) {
  983. };
  984. //noinspection JSUnusedLocalSymbols
  985. jasmine.JsApiReporter.prototype.reportSpecResults = function(spec) {
  986. this.results_[spec.id] = {
  987. messages: spec.results().getItems(),
  988. result: spec.results().failedCount > 0 ? "failed" : "passed"
  989. };
  990. };
  991. //noinspection JSUnusedLocalSymbols
  992. jasmine.JsApiReporter.prototype.log = function(str) {
  993. };
  994. jasmine.JsApiReporter.prototype.resultsForSpecs = function(specIds){
  995. var results = {};
  996. for (var i = 0; i < specIds.length; i++) {
  997. var specId = specIds[i];
  998. results[specId] = this.summarizeResult_(this.results_[specId]);
  999. }
  1000. return results;
  1001. };
  1002. jasmine.JsApiReporter.prototype.summarizeResult_ = function(result){
  1003. var summaryMessages = [];
  1004. var messagesLength = result.messages.length;
  1005. for (var messageIndex = 0; messageIndex < messagesLength; messageIndex++) {
  1006. var resultMessage = result.messages[messageIndex];
  1007. summaryMessages.push({
  1008. text: resultMessage.type == 'log' ? resultMessage.toString() : jasmine.undefined,
  1009. passed: resultMessage.passed ? resultMessage.passed() : true,
  1010. type: resultMessage.type,
  1011. message: resultMessage.message,
  1012. trace: {
  1013. stack: resultMessage.passed && !resultMessage.passed() ? resultMessage.trace.stack : jasmine.undefined
  1014. }
  1015. });
  1016. }
  1017. return {
  1018. result : result.result,
  1019. messages : summaryMessages
  1020. };
  1021. };
  1022. /**
  1023. * @constructor
  1024. * @param {jasmine.Env} env
  1025. * @param actual
  1026. * @param {jasmine.Spec} spec
  1027. */
  1028. jasmine.Matchers = function(env, actual, spec, opt_isNot) {
  1029. this.env = env;
  1030. this.actual = actual;
  1031. this.spec = spec;
  1032. this.isNot = opt_isNot || false;
  1033. this.reportWasCalled_ = false;
  1034. };
  1035. // todo: @deprecated as of Jasmine 0.11, remove soon [xw]
  1036. jasmine.Matchers.pp = function(str) {
  1037. throw new Error("jasmine.Matchers.pp() is no longer supported, please use jasmine.pp() instead!");
  1038. };
  1039. // todo: @deprecated Deprecated as of Jasmine 0.10. Rewrite your custom matchers to return true or false. [xw]
  1040. jasmine.Matchers.prototype.report = function(result, failing_message, details) {
  1041. throw new Error("As of jasmine 0.11, custom matchers must be implemented differently -- please see jasmine docs");
  1042. };
  1043. jasmine.Matchers.wrapInto_ = function(prototype, matchersClass) {
  1044. for (var methodName in prototype) {
  1045. if (methodName == 'report') continue;
  1046. var orig = prototype[methodName];
  1047. matchersClass.prototype[methodName] = jasmine.Matchers.matcherFn_(methodName, orig);
  1048. }
  1049. };
  1050. jasmine.Matchers.matcherFn_ = function(matcherName, matcherFunction) {
  1051. return function() {
  1052. var matcherArgs = jasmine.util.argsToArray(arguments);
  1053. var result = matcherFunction.apply(this, arguments);
  1054. if (this.isNot) {
  1055. result = !result;
  1056. }
  1057. if (this.reportWasCalled_) return result;
  1058. var message;
  1059. if (!result) {
  1060. if (this.message) {
  1061. message = this.message.apply(this, arguments);
  1062. if (jasmine.isArray_(message)) {
  1063. message = message[this.isNot ? 1 : 0];
  1064. }
  1065. } else {
  1066. var englishyPredicate = matcherName.replace(/[A-Z]/g, function(s) { return ' ' + s.toLowerCase(); });
  1067. message = "Expected " + jasmine.pp(this.actual) + (this.isNot ? " not " : " ") + englishyPredicate;
  1068. if (matcherArgs.length > 0) {
  1069. for (var i = 0; i < matcherArgs.length; i++) {
  1070. if (i > 0) message += ",";
  1071. message += " " + jasmine.pp(matcherArgs[i]);
  1072. }
  1073. }
  1074. message += ".";
  1075. }
  1076. }
  1077. var expectationResult = new jasmine.ExpectationResult({
  1078. matcherName: matcherName,
  1079. passed: result,
  1080. expected: matcherArgs.length > 1 ? matcherArgs : matcherArgs[0],
  1081. actual: this.actual,
  1082. message: message
  1083. });
  1084. this.spec.addMatcherResult(expectationResult);
  1085. return jasmine.undefined;
  1086. };
  1087. };
  1088. /**
  1089. * toBe: compares the actual to the expected using ===
  1090. * @param expected
  1091. */
  1092. jasmine.Matchers.prototype.toBe = function(expected) {
  1093. return this.actual === expected;
  1094. };
  1095. /**
  1096. * toNotBe: compares the actual to the expected using !==
  1097. * @param expected
  1098. * @deprecated as of 1.0. Use not.toBe() instead.
  1099. */
  1100. jasmine.Matchers.prototype.toNotBe = function(expected) {
  1101. return this.actual !== expected;
  1102. };
  1103. /**
  1104. * toEqual: compares the actual to the expected using common sense equality. Handles Objects, Arrays, etc.
  1105. *
  1106. * @param expected
  1107. */
  1108. jasmine.Matchers.prototype.toEqual = function(expected) {
  1109. return this.env.equals_(this.actual, expected);
  1110. };
  1111. /**
  1112. * toNotEqual: compares the actual to the expected using the ! of jasmine.Matchers.toEqual
  1113. * @param expected
  1114. * @deprecated as of 1.0. Use not.toEqual() instead.
  1115. */
  1116. jasmine.Matchers.prototype.toNotEqual = function(expected) {
  1117. return !this.env.equals_(this.actual, expected);
  1118. };
  1119. /**
  1120. * Matcher that compares the actual to the expected using a regular expression. Constructs a RegExp, so takes
  1121. * a pattern or a String.
  1122. *
  1123. * @param expected
  1124. */
  1125. jasmine.Matchers.prototype.toMatch = function(expected) {
  1126. return new RegExp(expected).test(this.actual);
  1127. };
  1128. /**
  1129. * Matcher that compares the actual to the expected using the boolean inverse of jasmine.Matchers.toMatch
  1130. * @param expected
  1131. * @deprecated as of 1.0. Use not.toMatch() instead.
  1132. */
  1133. jasmine.Matchers.prototype.toNotMatch = function(expected) {
  1134. return !(new RegExp(expected).test(this.actual));
  1135. };
  1136. /**
  1137. * Matcher that compares the actual to jasmine.undefined.
  1138. */
  1139. jasmine.Matchers.prototype.toBeDefined = function() {
  1140. return (this.actual !== jasmine.undefined);
  1141. };
  1142. /**
  1143. * Matcher that compares the actual to jasmine.undefined.
  1144. */
  1145. jasmine.Matchers.prototype.toBeUndefined = function() {
  1146. return (this.actual === jasmine.undefined);
  1147. };
  1148. /**
  1149. * Matcher that compares the actual to null.
  1150. */
  1151. jasmine.Matchers.prototype.toBeNull = function() {
  1152. return (this.actual === null);
  1153. };
  1154. /**
  1155. * Matcher that compares the actual to NaN.
  1156. */
  1157. jasmine.Matchers.prototype.toBeNaN = function() {
  1158. this.message = function() {
  1159. return [ "Expected " + jasmine.pp(this.actual) + " to be NaN." ];
  1160. };
  1161. return (this.actual !== this.actual);
  1162. };
  1163. /**
  1164. * Matcher that boolean not-nots the actual.
  1165. */
  1166. jasmine.Matchers.prototype.toBeTruthy = function() {
  1167. return !!this.actual;
  1168. };
  1169. /**
  1170. * Matcher that boolean nots the actual.
  1171. */
  1172. jasmine.Matchers.prototype.toBeFalsy = function() {
  1173. return !this.actual;
  1174. };
  1175. /**
  1176. * Matcher that checks to see if the actual, a Jasmine spy, was called.
  1177. */
  1178. jasmine.Matchers.prototype.toHaveBeenCalled = function() {
  1179. if (arguments.length > 0) {
  1180. throw new Error('toHaveBeenCalled does not take arguments, use toHaveBeenCalledWith');
  1181. }
  1182. if (!jasmine.isSpy(this.actual)) {
  1183. throw new Error('Expected a spy, but got ' + jasmine.pp(this.actual) + '.');
  1184. }
  1185. this.message = function() {
  1186. return [
  1187. "Expected spy " + this.actual.identity + " to have been called.",
  1188. "Expected spy " + this.actual.identity + " not to have been called."
  1189. ];
  1190. };
  1191. return this.actual.wasCalled;
  1192. };
  1193. /** @deprecated Use expect(xxx).toHaveBeenCalled() instead */
  1194. jasmine.Matchers.prototype.wasCalled = jasmine.Matchers.prototype.toHaveBeenCalled;
  1195. /**
  1196. * Matcher that checks to see if the actual, a Jasmine spy, was not called.
  1197. *
  1198. * @deprecated Use expect(xxx).not.toHaveBeenCalled() instead
  1199. */
  1200. jasmine.Matchers.prototype.wasNotCalled = function() {
  1201. if (arguments.length > 0) {
  1202. throw new Error('wasNotCalled does not take arguments');
  1203. }
  1204. if (!jasmine.isSpy(this.actual)) {
  1205. throw new Error('Expected a spy, but got ' + jasmine.pp(this.actual) + '.');
  1206. }
  1207. this.message = function() {
  1208. return [
  1209. "Expected spy " + this.actual.identity + " to not have been called.",
  1210. "Expected spy " + this.actual.identity + " to have been called."
  1211. ];
  1212. };
  1213. return !this.actual.wasCalled;
  1214. };
  1215. /**
  1216. * Matcher that checks to see if the actual, a Jasmine spy, was called with a set of parameters.
  1217. *
  1218. * @example
  1219. *
  1220. */
  1221. jasmine.Matchers.prototype.toHaveBeenCalledWith = function() {
  1222. var expectedArgs = jasmine.util.argsToArray(arguments);
  1223. if (!jasmine.isSpy(this.actual)) {
  1224. throw new Error('Expected a spy, but got ' + jasmine.pp(this.actual) + '.');
  1225. }
  1226. this.message = function() {
  1227. var invertedMessage = "Expected spy " + this.actual.identity + " not to have been called with " + jasmine.pp(expectedArgs) + " but it was.";
  1228. var positiveMessage = "";
  1229. if (this.actual.callCount === 0) {
  1230. positiveMessage = "Expected spy " + this.actual.identity + " to have been called with " + jasmine.pp(expectedArgs) + " but it was never called.";
  1231. } else {
  1232. positiveMessage = "Expected spy " + this.actual.identity + " to have been called with " + jasmine.pp(expectedArgs) + " but actual calls were " + jasmine.pp(this.actual.argsForCall).replace(/^\[ | \]$/g, '')
  1233. }
  1234. return [positiveMessage, invertedMessage];
  1235. };
  1236. return this.env.contains_(this.actual.argsForCall, expectedArgs);
  1237. };
  1238. /** @deprecated Use expect(xxx).toHaveBeenCalledWith() instead */
  1239. jasmine.Matchers.prototype.wasCalledWith = jasmine.Matchers.prototype.toHaveBeenCalledWith;
  1240. /** @deprecated Use expect(xxx).not.toHaveBeenCalledWith() instead */
  1241. jasmine.Matchers.prototype.wasNotCalledWith = function() {
  1242. var expectedArgs = jasmine.util.argsToArray(arguments);
  1243. if (!jasmine.isSpy(this.actual)) {
  1244. throw new Error('Expected a spy, but got ' + jasmine.pp(this.actual) + '.');
  1245. }
  1246. this.message = function() {
  1247. return [
  1248. "Expected spy not to have been called with " + jasmine.pp(expectedArgs) + " but it was",
  1249. "Expected spy to have been called with " + jasmine.pp(expectedArgs) + " but it was"
  1250. ];
  1251. };
  1252. return !this.env.contains_(this.actual.argsForCall, expectedArgs);
  1253. };
  1254. /**
  1255. * Matcher that checks that the expected item is an element in the actual Array.
  1256. *
  1257. * @param {Object} expected
  1258. */
  1259. jasmine.Matchers.prototype.toContain = function(expected) {
  1260. return this.env.contains_(this.actual, expected);
  1261. };
  1262. /**
  1263. * Matcher that checks that the expected item is NOT an element in the actual Array.
  1264. *
  1265. * @param {Object} expected
  1266. * @deprecated as of 1.0. Use not.toContain() instead.
  1267. */
  1268. jasmine.Matchers.prototype.toNotContain = function(expected) {
  1269. return !this.env.contains_(this.actual, expected);
  1270. };
  1271. jasmine.Matchers.prototype.toBeLessThan = function(expected) {
  1272. return this.actual < expected;
  1273. };
  1274. jasmine.Matchers.prototype.toBeGreaterThan = function(expected) {
  1275. return this.actual > expected;
  1276. };
  1277. /**
  1278. * Matcher that checks that the expected item is equal to the actual item
  1279. * up to a given level of decimal precision (default 2).
  1280. *
  1281. * @param {Number} expected
  1282. * @param {Number} precision, as number of decimal places
  1283. */
  1284. jasmine.Matchers.prototype.toBeCloseTo = function(expected, precision) {
  1285. if (!(precision === 0)) {
  1286. precision = precision || 2;
  1287. }
  1288. return Math.abs(expected - this.actual) < (Math.pow(10, -precision) / 2);
  1289. };
  1290. /**
  1291. * Matcher that checks that the expected exception was thrown by the actual.
  1292. *
  1293. * @param {String} [expected]
  1294. */
  1295. jasmine.Matchers.prototype.toThrow = function(expected) {
  1296. var result = false;
  1297. var exception;
  1298. if (typeof this.actual != 'function') {
  1299. throw new Error('Actual is not a function');
  1300. }
  1301. try {
  1302. this.actual();
  1303. } catch (e) {
  1304. exception = e;
  1305. }
  1306. if (exception) {
  1307. result = (expected === jasmine.undefined || this.env.equals_(exception.message || exception, expected.message || expected));
  1308. }
  1309. var not = this.isNot ? "not " : "";
  1310. this.message = function() {
  1311. if (exception && (expected === jasmine.undefined || !this.env.equals_(exception.message || exception, expected.message || expected))) {
  1312. return ["Expected function " + not + "to throw", expected ? expected.message || expected : "an exception", ", but it threw", exception.message || exception].join(' ');
  1313. } else {
  1314. return "Expected function to throw an exception.";
  1315. }
  1316. };
  1317. return result;
  1318. };
  1319. jasmine.Matchers.Any = function(expectedClass) {
  1320. this.expectedClass = expectedClass;
  1321. };
  1322. jasmine.Matchers.Any.prototype.jasmineMatches = function(other) {
  1323. if (this.expectedClass == String) {
  1324. return typeof other == 'string' || other instanceof String;
  1325. }
  1326. if (this.expectedClass == Number) {
  1327. return typeof other == 'number' || other instanceof Number;
  1328. }
  1329. if (this.expectedClass == Function) {
  1330. return typeof other == 'function' || other instanceof Function;
  1331. }
  1332. if (this.expectedClass == Object) {
  1333. return typeof other == 'object';
  1334. }
  1335. return other instanceof this.expectedClass;
  1336. };
  1337. jasmine.Matchers.Any.prototype.jasmineToString = function() {
  1338. return '<jasmine.any(' + this.expectedClass + ')>';
  1339. };
  1340. jasmine.Matchers.ObjectContaining = function (sample) {
  1341. this.sample = sample;
  1342. };
  1343. jasmine.Matchers.ObjectContaining.prototype.jasmineMatches = function(other, mismatchKeys, mismatchValues) {
  1344. mismatchKeys = mismatchKeys || [];
  1345. mismatchValues = mismatchValues || [];
  1346. var env = jasmine.getEnv();
  1347. var hasKey = function(obj, keyName) {
  1348. return obj != null && obj[keyName] !== jasmine.undefined;
  1349. };
  1350. for (var property in this.sample) {
  1351. if (!hasKey(other, property) && hasKey(this.sample, property)) {
  1352. mismatchKeys.push("expected has key '" + property + "', but missing from actual.");
  1353. }
  1354. else if (!env.equals_(this.sample[property], other[property], mismatchKeys, mismatchValues)) {
  1355. mismatchValues.push("'" + property + "' was '" + (other[property] ? jasmine.util.htmlEscape(other[property].toString()) : other[property]) + "' in expected, but was '" + (this.sample[property] ? jasmine.util.htmlEscape(this.sample[property].toString()) : this.sample[property]) + "' in actual.");
  1356. }
  1357. }
  1358. return (mismatchKeys.length === 0 && mismatchValues.length === 0);
  1359. };
  1360. jasmine.Matchers.ObjectContaining.prototype.jasmineToString = function () {
  1361. return "<jasmine.objectContaining(" + jasmine.pp(this.sample) + ")>";
  1362. };
  1363. // Mock setTimeout, clearTimeout
  1364. // Contributed by Pivotal Computer Systems, www.pivotalsf.com
  1365. jasmine.FakeTimer = function() {
  1366. this.reset();
  1367. var self = this;
  1368. self.setTimeout = function(funcToCall, millis) {
  1369. self.timeoutsMade++;
  1370. self.scheduleFunction(self.timeoutsMade, funcToCall, millis, false);
  1371. return self.timeoutsMade;
  1372. };
  1373. self.setInterval = function(funcToCall, millis) {
  1374. self.timeoutsMade++;
  1375. self.scheduleFunction(self.timeoutsMade, funcToCall, millis, true);
  1376. return self.timeoutsMade;
  1377. };
  1378. self.clearTimeout = function(timeoutKey) {
  1379. self.scheduledFunctions[timeoutKey] = jasmine.undefined;
  1380. };
  1381. self.clearInterval = function(timeoutKey) {
  1382. self.scheduledFunctions[timeoutKey] = jasmine.undefined;
  1383. };
  1384. };
  1385. jasmine.FakeTimer.prototype.reset = function() {
  1386. this.timeoutsMade = 0;
  1387. this.scheduledFunctions = {};
  1388. this.nowMillis = 0;
  1389. };
  1390. jasmine.FakeTimer.prototype.tick = function(millis) {
  1391. var oldMillis = this.nowMillis;
  1392. var newMillis = oldMillis + millis;
  1393. this.runFunctionsWithinRange(oldMillis, newMillis);
  1394. this.nowMillis = newMillis;
  1395. };
  1396. jasmine.FakeTimer.prototype.runFunctionsWithinRange = function(oldMillis, nowMillis) {
  1397. var scheduledFunc;
  1398. var funcsToRun = [];
  1399. for (var timeoutKey in this.scheduledFunctions) {
  1400. scheduledFunc = this.scheduledFunctions[timeoutKey];
  1401. if (scheduledFunc != jasmine.undefined &&
  1402. scheduledFunc.runAtMillis >= oldMillis &&
  1403. scheduledFunc.runAtMillis <= nowMillis) {
  1404. funcsToRun.push(scheduledFunc);
  1405. this.scheduledFunctions[timeoutKey] = jasmine.undefined;
  1406. }
  1407. }
  1408. if (funcsToRun.length > 0) {
  1409. funcsToRun.sort(function(a, b) {
  1410. return a.runAtMillis - b.runAtMillis;
  1411. });
  1412. for (var i = 0; i < funcsToRun.length; ++i) {
  1413. try {
  1414. var funcToRun = funcsToRun[i];
  1415. this.nowMillis = funcToRun.runAtMillis;
  1416. funcToRun.funcToCall();
  1417. if (funcToRun.recurring) {
  1418. this.scheduleFunction(funcToRun.timeoutKey,
  1419. funcToRun.funcToCall,
  1420. funcToRun.millis,
  1421. true);
  1422. }
  1423. } catch(e) {
  1424. }
  1425. }
  1426. this.runFunctionsWithinRange(oldMillis, nowMillis);
  1427. }
  1428. };
  1429. jasmine.FakeTimer.prototype.scheduleFunction = function(timeoutKey, funcToCall, millis, recurring) {
  1430. this.scheduledFunctions[timeoutKey] = {
  1431. runAtMillis: this.nowMillis + millis,
  1432. funcToCall: funcToCall,
  1433. recurring: recurring,
  1434. timeoutKey: timeoutKey,
  1435. millis: millis
  1436. };
  1437. };
  1438. /**
  1439. * @namespace
  1440. */
  1441. jasmine.Clock = {
  1442. defaultFakeTimer: new jasmine.FakeTimer(),
  1443. reset: function() {
  1444. jasmine.Clock.assertInstalled();
  1445. jasmine.Clock.defaultFakeTimer.reset();
  1446. },
  1447. tick: function(millis) {
  1448. jasmine.Clock.assertInstalled();
  1449. jasmine.Clock.defaultFakeTimer.tick(millis);
  1450. },
  1451. runFunctionsWithinRange: function(oldMillis, nowMillis) {
  1452. jasmine.Clock.defaultFakeTimer.runFunctionsWithinRange(oldMillis, nowMillis);
  1453. },
  1454. scheduleFunction: function(timeoutKey, funcToCall, millis, recurring) {
  1455. jasmine.Clock.defaultFakeTimer.scheduleFunction(timeoutKey, funcToCall, millis, recurring);
  1456. },
  1457. useMock: function() {
  1458. if (!jasmine.Clock.isInstalled()) {
  1459. var spec = jasmine.getEnv().currentSpec;
  1460. spec.after(jasmine.Clock.uninstallMock);
  1461. jasmine.Clock.installMock();
  1462. }
  1463. },
  1464. installMock: function() {
  1465. jasmine.Clock.installed = jasmine.Clock.defaultFakeTimer;
  1466. },
  1467. uninstallMock: function() {
  1468. jasmine.Clock.assertInstalled();
  1469. jasmine.Clock.installed = jasmine.Clock.real;
  1470. },
  1471. real: {
  1472. setTimeout: jasmine.getGlobal().setTimeout,
  1473. clearTimeout: jasmine.getGlobal().clearTimeout,
  1474. setInterval: jasmine.getGlobal().setInterval,
  1475. clearInterval: jasmine.getGlobal().clearInterval
  1476. },
  1477. assertInstalled: function() {
  1478. if (!jasmine.Clock.isInstalled()) {
  1479. throw new Error("Mock clock is not installed, use jasmine.Clock.useMock()");
  1480. }
  1481. },
  1482. isInstalled: function() {
  1483. return jasmine.Clock.installed == jasmine.Clock.defaultFakeTimer;
  1484. },
  1485. installed: null
  1486. };
  1487. jasmine.Clock.installed = jasmine.Clock.real;
  1488. //else for IE support
  1489. jasmine.getGlobal().setTimeout = function(funcToCall, millis) {
  1490. if (jasmine.Clock.installed.setTimeout.apply) {
  1491. return jasmine.Clock.installed.setTimeout.apply(this, arguments);
  1492. } else {
  1493. return jasmine.Clock.installed.setTimeout(funcToCall, millis);
  1494. }
  1495. };
  1496. jasmine.getGlobal().setInterval = function(funcToCall, millis) {
  1497. if (jasmine.Clock.installed.setInterval.apply) {
  1498. return jasmine.Clock.installed.setInterval.apply(this, arguments);
  1499. } else {
  1500. return jasmine.Clock.installed.setInterval(funcToCall, millis);
  1501. }
  1502. };
  1503. jasmine.getGlobal().clearTimeout = function(timeoutKey) {
  1504. if (jasmine.Clock.installed.clearTimeout.apply) {
  1505. return jasmine.Clock.installed.clearTimeout.apply(this, arguments);
  1506. } else {
  1507. return jasmine.Clock.installed.clearTimeout(timeoutKey);
  1508. }
  1509. };
  1510. jasmine.getGlobal().clearInterval = function(timeoutKey) {
  1511. if (jasmine.Clock.installed.clearTimeout.apply) {
  1512. return jasmine.Clock.installed.clearInterval.apply(this, arguments);
  1513. } else {
  1514. return jasmine.Clock.installed.clearInterval(timeoutKey);
  1515. }
  1516. };
  1517. /**
  1518. * @constructor
  1519. */
  1520. jasmine.MultiReporter = function() {
  1521. this.subReporters_ = [];
  1522. };
  1523. jasmine.util.inherit(jasmine.MultiReporter, jasmine.Reporter);
  1524. jasmine.MultiReporter.prototype.addReporter = function(reporter) {
  1525. this.subReporters_.push(reporter);
  1526. };
  1527. (function() {
  1528. var functionNames = [
  1529. "reportRunnerStarting",
  1530. "reportRunnerResults",
  1531. "reportSuiteResults",
  1532. "reportSpecStarting",
  1533. "reportSpecResults",
  1534. "log"
  1535. ];
  1536. for (var i = 0; i < functionNames.length; i++) {
  1537. var functionName = functionNames[i];
  1538. jasmine.MultiReporter.prototype[functionName] = (function(functionName) {
  1539. return function() {
  1540. for (var j = 0; j < this.subReporters_.length; j++) {
  1541. var subReporter = this.subReporters_[j];
  1542. if (subReporter[functionName]) {
  1543. subReporter[functionName].apply(subReporter, arguments);
  1544. }
  1545. }
  1546. };
  1547. })(functionName);
  1548. }
  1549. })();
  1550. /**
  1551. * Holds results for a set of Jasmine spec. Allows for the results array to hold another jasmine.NestedResults
  1552. *
  1553. * @constructor
  1554. */
  1555. jasmine.NestedResults = function() {
  1556. /**
  1557. * The total count of results
  1558. */
  1559. this.totalCount = 0;
  1560. /**
  1561. * Number of passed results
  1562. */
  1563. this.passedCount = 0;
  1564. /**
  1565. * Number of failed results
  1566. */
  1567. this.failedCount = 0;
  1568. /**
  1569. * Was this suite/spec skipped?
  1570. */
  1571. this.skipped = false;
  1572. /**
  1573. * @ignore
  1574. */
  1575. this.items_ = [];
  1576. };
  1577. /**
  1578. * Roll up the result counts.
  1579. *
  1580. * @param result
  1581. */
  1582. jasmine.NestedResults.prototype.rollupCounts = function(result) {
  1583. this.totalCount += result.totalCount;
  1584. this.passedCount += result.passedCount;
  1585. this.failedCount += result.failedCount;
  1586. };
  1587. /**
  1588. * Adds a log message.
  1589. * @param values Array of message parts which will be concatenated later.
  1590. */
  1591. jasmine.NestedResults.prototype.log = function(values) {
  1592. this.items_.push(new jasmine.MessageResult(values));
  1593. };
  1594. /**
  1595. * Getter for the results: message & results.
  1596. */
  1597. jasmine.NestedResults.prototype.getItems = function() {
  1598. return this.items_;
  1599. };
  1600. /**
  1601. * Adds a result, tracking counts (total, passed, & failed)
  1602. * @param {jasmine.ExpectationResult|jasmine.NestedResults} result
  1603. */
  1604. jasmine.NestedResults.prototype.addResult = function(result) {
  1605. if (result.type != 'log') {
  1606. if (result.items_) {
  1607. this.rollupCounts(result);
  1608. } else {
  1609. this.totalCount++;
  1610. if (result.passed()) {
  1611. this.passedCount++;
  1612. } else {
  1613. this.failedCount++;
  1614. }
  1615. }
  1616. }
  1617. this.items_.push(result);
  1618. };
  1619. /**
  1620. * @returns {Boolean} True if <b>everything</b> below passed
  1621. */
  1622. jasmine.NestedResults.prototype.passed = function() {
  1623. return this.passedCount === this.totalCount;
  1624. };
  1625. /**
  1626. * Base class for pretty printing for expectation results.
  1627. */
  1628. jasmine.PrettyPrinter = function() {
  1629. this.ppNestLevel_ = 0;
  1630. };
  1631. /**
  1632. * Formats a value in a nice, human-readable string.
  1633. *
  1634. * @param value
  1635. */
  1636. jasmine.PrettyPrinter.prototype.format = function(value) {
  1637. this.ppNestLevel_++;
  1638. try {
  1639. if (value === jasmine.undefined) {
  1640. this.emitScalar('undefined');
  1641. } else if (value === null) {
  1642. this.emitScalar('null');
  1643. } else if (value === jasmine.getGlobal()) {
  1644. this.emitScalar('<global>');
  1645. } else if (value.jasmineToString) {
  1646. this.emitScalar(value.jasmineToString());
  1647. } else if (typeof value === 'string') {
  1648. this.emitString(value);
  1649. } else if (jasmine.isSpy(value)) {
  1650. this.emitScalar("spy on " + value.identity);
  1651. } else if (value instanceof RegExp) {
  1652. this.emitScalar(value.toString());
  1653. } else if (typeof value === 'function') {
  1654. this.emitScalar('Function');
  1655. } else if (typeof value.nodeType === 'number') {
  1656. this.emitScalar('HTMLNode');
  1657. } else if (value instanceof Date) {
  1658. this.emitScalar('Date(' + value + ')');
  1659. } else if (value.__Jasmine_been_here_before__) {
  1660. this.emitScalar('<circular reference: ' + (jasmine.isArray_(value) ? 'Array' : 'Object') + '>');
  1661. } else if (jasmine.isArray_(value) || typeof value == 'object') {
  1662. value.__Jasmine_been_here_before__ = true;
  1663. if (jasmine.isArray_(value)) {
  1664. this.emitArray(value);
  1665. } else {
  1666. this.emitObject(value);
  1667. }
  1668. delete value.__Jasmine_been_here_before__;
  1669. } else {
  1670. this.emitScalar(value.toString());
  1671. }
  1672. } finally {
  1673. this.ppNestLevel_--;
  1674. }
  1675. };
  1676. jasmine.PrettyPrinter.prototype.iterateObject = function(obj, fn) {
  1677. for (var property in obj) {
  1678. if (!obj.hasOwnProperty(property)) continue;
  1679. if (property == '__Jasmine_been_here_before__') continue;
  1680. fn(property, obj.__lookupGetter__ ? (obj.__lookupGetter__(property) !== jasmine.undefined &&
  1681. obj.__lookupGetter__(property) !== null) : false);
  1682. }
  1683. };
  1684. jasmine.PrettyPrinter.prototype.emitArray = jasmine.unimplementedMethod_;
  1685. jasmine.PrettyPrinter.prototype.emitObject = jasmine.unimplementedMethod_;
  1686. jasmine.PrettyPrinter.prototype.emitScalar = jasmine.unimplementedMethod_;
  1687. jasmine.PrettyPrinter.prototype.emitString = jasmine.unimplementedMethod_;
  1688. jasmine.StringPrettyPrinter = function() {
  1689. jasmine.PrettyPrinter.call(this);
  1690. this.string = '';
  1691. };
  1692. jasmine.util.inherit(jasmine.StringPrettyPrinter, jasmine.PrettyPrinter);
  1693. jasmine.StringPrettyPrinter.prototype.emitScalar = function(value) {
  1694. this.append(value);
  1695. };
  1696. jasmine.StringPrettyPrinter.prototype.emitString = function(value) {
  1697. this.append("'" + value + "'");
  1698. };
  1699. jasmine.StringPrettyPrinter.prototype.emitArray = function(array) {
  1700. if (this.ppNestLevel_ > jasmine.MAX_PRETTY_PRINT_DEPTH) {
  1701. this.append("Array");
  1702. return;
  1703. }
  1704. this.append('[ ');
  1705. for (var i = 0; i < array.length; i++) {
  1706. if (i > 0) {
  1707. this.append(', ');
  1708. }
  1709. this.format(array[i]);
  1710. }
  1711. this.append(' ]');
  1712. };
  1713. jasmine.StringPrettyPrinter.prototype.emitObject = function(obj) {
  1714. if (this.ppNestLevel_ > jasmine.MAX_PRETTY_PRINT_DEPTH) {
  1715. this.append("Object");
  1716. return;
  1717. }
  1718. var self = this;
  1719. this.append('{ ');
  1720. var first = true;
  1721. this.iterateObject(obj, function(property, isGetter) {
  1722. if (first) {
  1723. first = false;
  1724. } else {
  1725. self.append(', ');
  1726. }
  1727. self.append(property);
  1728. self.append(' : ');
  1729. if (isGetter) {
  1730. self.append('<getter>');
  1731. } else {
  1732. self.format(obj[property]);
  1733. }
  1734. });
  1735. this.append(' }');
  1736. };
  1737. jasmine.StringPrettyPrinter.prototype.append = function(value) {
  1738. this.string += value;
  1739. };
  1740. jasmine.Queue = function(env) {
  1741. this.env = env;
  1742. // parallel to blocks. each true value in this array means the block will
  1743. // get executed even if we abort
  1744. this.ensured = [];
  1745. this.blocks = [];
  1746. this.running = false;
  1747. this.index = 0;
  1748. this.offset = 0;
  1749. this.abort = false;
  1750. };
  1751. jasmine.Queue.prototype.addBefore = function(block, ensure) {
  1752. if (ensure === jasmine.undefined) {
  1753. ensure = false;
  1754. }
  1755. this.blocks.unshift(block);
  1756. this.ensured.unshift(ensure);
  1757. };
  1758. jasmine.Queue.prototype.add = function(block, ensure) {
  1759. if (ensure === jasmine.undefined) {
  1760. ensure = false;
  1761. }
  1762. this.blocks.push(block);
  1763. this.ensured.push(ensure);
  1764. };
  1765. jasmine.Queue.prototype.insertNext = function(block, ensure) {
  1766. if (ensure === jasmine.undefined) {
  1767. ensure = false;
  1768. }
  1769. this.ensured.splice((this.index + this.offset + 1), 0, ensure);
  1770. this.blocks.splice((this.index + this.offset + 1), 0, block);
  1771. this.offset++;
  1772. };
  1773. jasmine.Queue.prototype.start = function(onComplete) {
  1774. this.running = true;
  1775. this.onComplete = onComplete;
  1776. this.next_();
  1777. };
  1778. jasmine.Queue.prototype.isRunning = function() {
  1779. return this.running;
  1780. };
  1781. jasmine.Queue.LOOP_DONT_RECURSE = true;
  1782. jasmine.Queue.prototype.next_ = function() {
  1783. var self = this;
  1784. var goAgain = true;
  1785. while (goAgain) {
  1786. goAgain = false;
  1787. if (self.index < self.blocks.length && !(this.abort && !this.ensured[self.index])) {
  1788. var calledSynchronously = true;
  1789. var completedSynchronously = false;
  1790. var onComplete = function () {
  1791. if (jasmine.Queue.LOOP_DONT_RECURSE && calledSynchronously) {
  1792. completedSynchronously = true;
  1793. return;
  1794. }
  1795. if (self.blocks[self.index].abort) {
  1796. self.abort = true;
  1797. }
  1798. self.offset = 0;
  1799. self.index++;
  1800. var now = new Date().getTime();
  1801. if (self.env.updateInterval && now - self.env.lastUpdate > self.env.updateInterval) {
  1802. self.env.lastUpdate = now;
  1803. self.env.setTimeout(function() {
  1804. self.next_();
  1805. }, 0);
  1806. } else {
  1807. if (jasmine.Queue.LOOP_DONT_RECURSE && completedSynchronously) {
  1808. goAgain = true;
  1809. } else {
  1810. self.next_();
  1811. }
  1812. }
  1813. };
  1814. self.blocks[self.index].execute(onComplete);
  1815. calledSynchronously = false;
  1816. if (completedSynchronously) {
  1817. onComplete();
  1818. }
  1819. } else {
  1820. self.running = false;
  1821. if (self.onComplete) {
  1822. self.onComplete();
  1823. }
  1824. }
  1825. }
  1826. };
  1827. jasmine.Queue.prototype.results = function() {
  1828. var results = new jasmine.NestedResults();
  1829. for (var i = 0; i < this.blocks.length; i++) {
  1830. if (this.blocks[i].results) {
  1831. results.addResult(this.blocks[i].results());
  1832. }
  1833. }
  1834. return results;
  1835. };
  1836. /**
  1837. * Runner
  1838. *
  1839. * @constructor
  1840. * @param {jasmine.Env} env
  1841. */
  1842. jasmine.Runner = function(env) {
  1843. var self = this;
  1844. self.env = env;
  1845. self.queue = new jasmine.Queue(env);
  1846. self.before_ = [];
  1847. self.after_ = [];
  1848. self.suites_ = [];
  1849. };
  1850. jasmine.Runner.prototype.execute = function() {
  1851. var self = this;
  1852. if (self.env.reporter.reportRunnerStarting) {
  1853. self.env.reporter.reportRunnerStarting(this);
  1854. }
  1855. self.queue.start(function () {
  1856. self.finishCallback();
  1857. });
  1858. };
  1859. jasmine.Runner.prototype.beforeEach = function(beforeEachFunction) {
  1860. beforeEachFunction.typeName = 'beforeEach';
  1861. this.before_.splice(0,0,beforeEachFunction);
  1862. };
  1863. jasmine.Runner.prototype.afterEach = function(afterEachFunction) {
  1864. afterEachFunction.typeName = 'afterEach';
  1865. this.after_.splice(0,0,afterEachFunction);
  1866. };
  1867. jasmine.Runner.prototype.finishCallback = function() {
  1868. this.env.reporter.reportRunnerResults(this);
  1869. };
  1870. jasmine.Runner.prototype.addSuite = function(suite) {
  1871. this.suites_.push(suite);
  1872. };
  1873. jasmine.Runner.prototype.add = function(block) {
  1874. if (block instanceof jasmine.Suite) {
  1875. this.addSuite(block);
  1876. }
  1877. this.queue.add(block);
  1878. };
  1879. jasmine.Runner.prototype.specs = function () {
  1880. var suites = this.suites();
  1881. var specs = [];
  1882. for (var i = 0; i < suites.length; i++) {
  1883. specs = specs.concat(suites[i].specs());
  1884. }
  1885. return specs;
  1886. };
  1887. jasmine.Runner.prototype.suites = function() {
  1888. return this.suites_;
  1889. };
  1890. jasmine.Runner.prototype.topLevelSuites = function() {
  1891. var topLevelSuites = [];
  1892. for (var i = 0; i < this.suites_.length; i++) {
  1893. if (!this.suites_[i].parentSuite) {
  1894. topLevelSuites.push(this.suites_[i]);
  1895. }
  1896. }
  1897. return topLevelSuites;
  1898. };
  1899. jasmine.Runner.prototype.results = function() {
  1900. return this.queue.results();
  1901. };
  1902. /**
  1903. * Internal representation of a Jasmine specification, or test.
  1904. *
  1905. * @constructor
  1906. * @param {jasmine.Env} env
  1907. * @param {jasmine.Suite} suite
  1908. * @param {String} description
  1909. */
  1910. jasmine.Spec = function(env, suite, description) {
  1911. if (!env) {
  1912. throw new Error('jasmine.Env() required');
  1913. }
  1914. if (!suite) {
  1915. throw new Error('jasmine.Suite() required');
  1916. }
  1917. var spec = this;
  1918. spec.id = env.nextSpecId ? env.nextSpecId() : null;
  1919. spec.env = env;
  1920. spec.suite = suite;
  1921. spec.description = description;
  1922. spec.queue = new jasmine.Queue(env);
  1923. spec.afterCallbacks = [];
  1924. spec.spies_ = [];
  1925. spec.results_ = new jasmine.NestedResults();
  1926. spec.results_.description = description;
  1927. spec.matchersClass = null;
  1928. };
  1929. jasmine.Spec.prototype.getFullName = function() {
  1930. return this.suite.getFullName() + ' ' + this.description + '.';
  1931. };
  1932. jasmine.Spec.prototype.results = function() {
  1933. return this.results_;
  1934. };
  1935. /**
  1936. * All parameters are pretty-printed and concatenated together, then written to the spec's output.
  1937. *
  1938. * Be careful not to leave calls to <code>jasmine.log</code> in production code.
  1939. */
  1940. jasmine.Spec.prototype.log = function() {
  1941. return this.results_.log(arguments);
  1942. };
  1943. jasmine.Spec.prototype.runs = function (func) {
  1944. var block = new jasmine.Block(this.env, func, this);
  1945. this.addToQueue(block);
  1946. return this;
  1947. };
  1948. jasmine.Spec.prototype.addToQueue = function (block) {
  1949. if (this.queue.isRunning()) {
  1950. this.queue.insertNext(block);
  1951. } else {
  1952. this.queue.add(block);
  1953. }
  1954. };
  1955. /**
  1956. * @param {jasmine.ExpectationResult} result
  1957. */
  1958. jasmine.Spec.prototype.addMatcherResult = function(result) {
  1959. this.results_.addResult(result);
  1960. };
  1961. jasmine.Spec.prototype.expect = function(actual) {
  1962. var positive = new (this.getMatchersClass_())(this.env, actual, this);
  1963. positive.not = new (this.getMatchersClass_())(this.env, actual, this, true);
  1964. return positive;
  1965. };
  1966. /**
  1967. * Waits a fixed time period before moving to the next block.
  1968. *
  1969. * @deprecated Use waitsFor() instead
  1970. * @param {Number} timeout milliseconds to wait
  1971. */
  1972. jasmine.Spec.prototype.waits = function(timeout) {
  1973. var waitsFunc = new jasmine.WaitsBlock(this.env, timeout, this);
  1974. this.addToQueue(waitsFunc);
  1975. return this;
  1976. };
  1977. /**
  1978. * Waits for the latchFunction to return true before proceeding to the next block.
  1979. *
  1980. * @param {Function} latchFunction
  1981. * @param {String} optional_timeoutMessage
  1982. * @param {Number} optional_timeout
  1983. */
  1984. jasmine.Spec.prototype.waitsFor = function(latchFunction, optional_timeoutMessage, optional_timeout) {
  1985. var latchFunction_ = null;
  1986. var optional_timeoutMessage_ = null;
  1987. var optional_timeout_ = null;
  1988. for (var i = 0; i < arguments.length; i++) {
  1989. var arg = arguments[i];
  1990. switch (typeof arg) {
  1991. case 'function':
  1992. latchFunction_ = arg;
  1993. break;
  1994. case 'string':
  1995. optional_timeoutMessage_ = arg;
  1996. break;
  1997. case 'number':
  1998. optional_timeout_ = arg;
  1999. break;
  2000. }
  2001. }
  2002. var waitsForFunc = new jasmine.WaitsForBlock(this.env, optional_timeout_, latchFunction_, optional_timeoutMessage_, this);
  2003. this.addToQueue(waitsForFunc);
  2004. return this;
  2005. };
  2006. jasmine.Spec.prototype.fail = function (e) {
  2007. var expectationResult = new jasmine.ExpectationResult({
  2008. passed: false,
  2009. message: e ? jasmine.util.formatException(e) : 'Exception',
  2010. trace: { stack: e.stack }
  2011. });
  2012. this.results_.addResult(expectationResult);
  2013. };
  2014. jasmine.Spec.prototype.getMatchersClass_ = function() {
  2015. return this.matchersClass || this.env.matchersClass;
  2016. };
  2017. jasmine.Spec.prototype.addMatchers = function(matchersPrototype) {
  2018. var parent = this.getMatchersClass_();
  2019. var newMatchersClass = function() {
  2020. parent.apply(this, arguments);
  2021. };
  2022. jasmine.util.inherit(newMatchersClass, parent);
  2023. jasmine.Matchers.wrapInto_(matchersPrototype, newMatchersClass);
  2024. this.matchersClass = newMatchersClass;
  2025. };
  2026. jasmine.Spec.prototype.finishCallback = function() {
  2027. this.env.reporter.reportSpecResults(this);
  2028. };
  2029. jasmine.Spec.prototype.finish = function(onComplete) {
  2030. this.removeAllSpies();
  2031. this.finishCallback();
  2032. if (onComplete) {
  2033. onComplete();
  2034. }
  2035. };
  2036. jasmine.Spec.prototype.after = function(doAfter) {
  2037. if (this.queue.isRunning()) {
  2038. this.queue.add(new jasmine.Block(this.env, doAfter, this), true);
  2039. } else {
  2040. this.afterCallbacks.unshift(doAfter);
  2041. }
  2042. };
  2043. jasmine.Spec.prototype.execute = function(onComplete) {
  2044. var spec = this;
  2045. if (!spec.env.specFilter(spec)) {
  2046. spec.results_.skipped = true;
  2047. spec.finish(onComplete);
  2048. return;
  2049. }
  2050. this.env.reporter.reportSpecStarting(this);
  2051. spec.env.currentSpec = spec;
  2052. spec.addBeforesAndAftersToQueue();
  2053. spec.queue.start(function () {
  2054. spec.finish(onComplete);
  2055. });
  2056. };
  2057. jasmine.Spec.prototype.addBeforesAndAftersToQueue = function() {
  2058. var runner = this.env.currentRunner();
  2059. var i;
  2060. for (var suite = this.suite; suite; suite = suite.parentSuite) {
  2061. for (i = 0; i < suite.before_.length; i++) {
  2062. this.queue.addBefore(new jasmine.Block(this.env, suite.before_[i], this));
  2063. }
  2064. }
  2065. for (i = 0; i < runner.before_.length; i++) {
  2066. this.queue.addBefore(new jasmine.Block(this.env, runner.before_[i], this));
  2067. }
  2068. for (i = 0; i < this.afterCallbacks.length; i++) {
  2069. this.queue.add(new jasmine.Block(this.env, this.afterCallbacks[i], this), true);
  2070. }
  2071. for (suite = this.suite; suite; suite = suite.parentSuite) {
  2072. for (i = 0; i < suite.after_.length; i++) {
  2073. this.queue.add(new jasmine.Block(this.env, suite.after_[i], this), true);
  2074. }
  2075. }
  2076. for (i = 0; i < runner.after_.length; i++) {
  2077. this.queue.add(new jasmine.Block(this.env, runner.after_[i], this), true);
  2078. }
  2079. };
  2080. jasmine.Spec.prototype.explodes = function() {
  2081. throw 'explodes function should not have been called';
  2082. };
  2083. jasmine.Spec.prototype.spyOn = function(obj, methodName, ignoreMethodDoesntExist) {
  2084. if (obj == jasmine.undefined) {
  2085. throw "spyOn could not find an object to spy upon for " + methodName + "()";
  2086. }
  2087. if (!ignoreMethodDoesntExist && obj[methodName] === jasmine.undefined) {
  2088. throw methodName + '() method does not exist';
  2089. }
  2090. if (!ignoreMethodDoesntExist && obj[methodName] && obj[methodName].isSpy) {
  2091. throw new Error(methodName + ' has already been spied upon');
  2092. }
  2093. var spyObj = jasmine.createSpy(methodName);
  2094. this.spies_.push(spyObj);
  2095. spyObj.baseObj = obj;
  2096. spyObj.methodName = methodName;
  2097. spyObj.originalValue = obj[methodName];
  2098. obj[methodName] = spyObj;
  2099. return spyObj;
  2100. };
  2101. jasmine.Spec.prototype.removeAllSpies = function() {
  2102. for (var i = 0; i < this.spies_.length; i++) {
  2103. var spy = this.spies_[i];
  2104. spy.baseObj[spy.methodName] = spy.originalValue;
  2105. }
  2106. this.spies_ = [];
  2107. };
  2108. /**
  2109. * Internal representation of a Jasmine suite.
  2110. *
  2111. * @constructor
  2112. * @param {jasmine.Env} env
  2113. * @param {String} description
  2114. * @param {Function} specDefinitions
  2115. * @param {jasmine.Suite} parentSuite
  2116. */
  2117. jasmine.Suite = function(env, description, specDefinitions, parentSuite) {
  2118. var self = this;
  2119. self.id = env.nextSuiteId ? env.nextSuiteId() : null;
  2120. self.description = description;
  2121. self.queue = new jasmine.Queue(env);
  2122. self.parentSuite = parentSuite;
  2123. self.env = env;
  2124. self.before_ = [];
  2125. self.after_ = [];
  2126. self.children_ = [];
  2127. self.suites_ = [];
  2128. self.specs_ = [];
  2129. };
  2130. jasmine.Suite.prototype.getFullName = function() {
  2131. var fullName = this.description;
  2132. for (var parentSuite = this.parentSuite; parentSuite; parentSuite = parentSuite.parentSuite) {
  2133. fullName = parentSuite.description + ' ' + fullName;
  2134. }
  2135. return fullName;
  2136. };
  2137. jasmine.Suite.prototype.finish = function(onComplete) {
  2138. this.env.reporter.reportSuiteResults(this);
  2139. this.finished = true;
  2140. if (typeof(onComplete) == 'function') {
  2141. onComplete();
  2142. }
  2143. };
  2144. jasmine.Suite.prototype.beforeEach = function(beforeEachFunction) {
  2145. beforeEachFunction.typeName = 'beforeEach';
  2146. this.before_.unshift(beforeEachFunction);
  2147. };
  2148. jasmine.Suite.prototype.afterEach = function(afterEachFunction) {
  2149. afterEachFunction.typeName = 'afterEach';
  2150. this.after_.unshift(afterEachFunction);
  2151. };
  2152. jasmine.Suite.prototype.results = function() {
  2153. return this.queue.results();
  2154. };
  2155. jasmine.Suite.prototype.add = function(suiteOrSpec) {
  2156. this.children_.push(suiteOrSpec);
  2157. if (suiteOrSpec instanceof jasmine.Suite) {
  2158. this.suites_.push(suiteOrSpec);
  2159. this.env.currentRunner().addSuite(suiteOrSpec);
  2160. } else {
  2161. this.specs_.push(suiteOrSpec);
  2162. }
  2163. this.queue.add(suiteOrSpec);
  2164. };
  2165. jasmine.Suite.prototype.specs = function() {
  2166. return this.specs_;
  2167. };
  2168. jasmine.Suite.prototype.suites = function() {
  2169. return this.suites_;
  2170. };
  2171. jasmine.Suite.prototype.children = function() {
  2172. return this.children_;
  2173. };
  2174. jasmine.Suite.prototype.execute = function(onComplete) {
  2175. var self = this;
  2176. this.queue.start(function () {
  2177. self.finish(onComplete);
  2178. });
  2179. };
  2180. jasmine.WaitsBlock = function(env, timeout, spec) {
  2181. this.timeout = timeout;
  2182. jasmine.Block.call(this, env, null, spec);
  2183. };
  2184. jasmine.util.inherit(jasmine.WaitsBlock, jasmine.Block);
  2185. jasmine.WaitsBlock.prototype.execute = function (onComplete) {
  2186. if (jasmine.VERBOSE) {
  2187. this.env.reporter.log('>> Jasmine waiting for ' + this.timeout + ' ms...');
  2188. }
  2189. this.env.setTimeout(function () {
  2190. onComplete();
  2191. }, this.timeout);
  2192. };
  2193. /**
  2194. * A block which waits for some condition to become true, with timeout.
  2195. *
  2196. * @constructor
  2197. * @extends jasmine.Block
  2198. * @param {jasmine.Env} env The Jasmine environment.
  2199. * @param {Number} timeout The maximum time in milliseconds to wait for the condition to become true.
  2200. * @param {Function} latchFunction A function which returns true when the desired condition has been met.
  2201. * @param {String} message The message to display if the desired condition hasn't been met within the given time period.
  2202. * @param {jasmine.Spec} spec The Jasmine spec.
  2203. */
  2204. jasmine.WaitsForBlock = function(env, timeout, latchFunction, message, spec) {
  2205. this.timeout = timeout || env.defaultTimeoutInterval;
  2206. this.latchFunction = latchFunction;
  2207. this.message = message;
  2208. this.totalTimeSpentWaitingForLatch = 0;
  2209. jasmine.Block.call(this, env, null, spec);
  2210. };
  2211. jasmine.util.inherit(jasmine.WaitsForBlock, jasmine.Block);
  2212. jasmine.WaitsForBlock.TIMEOUT_INCREMENT = 10;
  2213. jasmine.WaitsForBlock.prototype.execute = function(onComplete) {
  2214. if (jasmine.VERBOSE) {
  2215. this.env.reporter.log('>> Jasmine waiting for ' + (this.message || 'something to happen'));
  2216. }
  2217. var latchFunctionResult;
  2218. try {
  2219. latchFunctionResult = this.latchFunction.apply(this.spec);
  2220. } catch (e) {
  2221. this.spec.fail(e);
  2222. onComplete();
  2223. return;
  2224. }
  2225. if (latchFunctionResult) {
  2226. onComplete();
  2227. } else if (this.totalTimeSpentWaitingForLatch >= this.timeout) {
  2228. var message = 'timed out after ' + this.timeout + ' msec waiting for ' + (this.message || 'something to happen');
  2229. this.spec.fail({
  2230. name: 'timeout',
  2231. message: message
  2232. });
  2233. this.abort = true;
  2234. onComplete();
  2235. } else {
  2236. this.totalTimeSpentWaitingForLatch += jasmine.WaitsForBlock.TIMEOUT_INCREMENT;
  2237. var self = this;
  2238. this.env.setTimeout(function() {
  2239. self.execute(onComplete);
  2240. }, jasmine.WaitsForBlock.TIMEOUT_INCREMENT);
  2241. }
  2242. };
  2243. jasmine.version_= {
  2244. "major": 1,
  2245. "minor": 3,
  2246. "build": 1,
  2247. "revision": 1354556913
  2248. };