jasmine.js 67 KB

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