core.js 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332
  1. module("core", { teardown: moduleTeardown });
  2. test("Unit Testing Environment", function () {
  3. expect(2);
  4. ok( hasPHP, "Running in an environment with PHP support. The AJAX tests only run if the environment supports PHP!" );
  5. ok( !isLocal, "Unit tests are not ran from file:// (especially in Chrome. If you must test from file:// with Chrome, run it with the --allow-file-access-from-files flag!)" );
  6. });
  7. test("Basic requirements", function() {
  8. expect(7);
  9. ok( Array.prototype.push, "Array.push()" );
  10. ok( Function.prototype.apply, "Function.apply()" );
  11. ok( document.getElementById, "getElementById" );
  12. ok( document.getElementsByTagName, "getElementsByTagName" );
  13. ok( RegExp, "RegExp" );
  14. ok( jQuery, "jQuery" );
  15. ok( $, "$" );
  16. });
  17. testIframeWithCallback( "Conditional compilation compatibility (#13274)", "core/cc_on.html", function( cc_on, errors, $ ) {
  18. expect( 3 );
  19. ok( true, "JScript conditional compilation " + ( cc_on ? "supported" : "not supported" ) );
  20. deepEqual( errors, [], "No errors" );
  21. ok( $(), "jQuery executes" );
  22. });
  23. test("jQuery()", function() {
  24. var elem, i,
  25. obj = jQuery("div"),
  26. main = jQuery("#qunit-fixture"),
  27. code = jQuery("<code/>"),
  28. img = jQuery("<img/>"),
  29. div = jQuery("<div/><hr/><code/><b/>"),
  30. exec = false,
  31. lng = "",
  32. expected = 21,
  33. attrObj = {
  34. "text": "test",
  35. "class": "test2",
  36. "id": "test3"
  37. };
  38. // The $(html, props) signature can stealth-call any $.fn method, check for a
  39. // few here but beware of modular builds where these methods may be excluded.
  40. if ( jQuery.fn.click ) {
  41. expected++;
  42. attrObj["click"] = function() { ok( exec, "Click executed." ); };
  43. }
  44. if ( jQuery.fn.width ) {
  45. expected++;
  46. attrObj["width"] = 10;
  47. }
  48. if ( jQuery.fn.offset ) {
  49. expected++;
  50. attrObj["offset"] = { "top": 1, "left": 1 };
  51. }
  52. if ( jQuery.fn.css ) {
  53. expected += 2;
  54. attrObj["css"] = { "paddingLeft": 1, "paddingRight": 1 };
  55. }
  56. if ( jQuery.fn.attr ) {
  57. expected++;
  58. attrObj.attr = { "desired": "very" };
  59. }
  60. expect( expected );
  61. // Basic constructor's behavior
  62. equal( jQuery().length, 0, "jQuery() === jQuery([])" );
  63. equal( jQuery(undefined).length, 0, "jQuery(undefined) === jQuery([])" );
  64. equal( jQuery(null).length, 0, "jQuery(null) === jQuery([])" );
  65. equal( jQuery("").length, 0, "jQuery('') === jQuery([])" );
  66. equal( jQuery("#").length, 0, "jQuery('#') === jQuery([])" );
  67. equal( jQuery(obj).selector, "div", "jQuery(jQueryObj) == jQueryObj" );
  68. // can actually yield more than one, when iframes are included, the window is an array as well
  69. equal( jQuery(window).length, 1, "Correct number of elements generated for jQuery(window)" );
  70. deepEqual( jQuery("div p", main).get(), q("sndp", "en", "sap"), "Basic selector with jQuery object as context" );
  71. /*
  72. // disabled since this test was doing nothing. i tried to fix it but i'm not sure
  73. // what the expected behavior should even be. FF returns "\n" for the text node
  74. // make sure this is handled
  75. var crlfContainer = jQuery('<p>\r\n</p>');
  76. var x = crlfContainer.contents().get(0).nodeValue;
  77. equal( x, what???, "Check for \\r and \\n in jQuery()" );
  78. */
  79. /* // Disabled until we add this functionality in
  80. var pass = true;
  81. try {
  82. jQuery("<div>Testing</div>").appendTo(document.getElementById("iframe").contentDocument.body);
  83. } catch(e){
  84. pass = false;
  85. }
  86. ok( pass, "jQuery('&lt;tag&gt;') needs optional document parameter to ease cross-frame DOM wrangling, see #968" );*/
  87. equal( code.length, 1, "Correct number of elements generated for code" );
  88. equal( code.parent().length, 0, "Make sure that the generated HTML has no parent." );
  89. equal( img.length, 1, "Correct number of elements generated for img" );
  90. equal( img.parent().length, 0, "Make sure that the generated HTML has no parent." );
  91. equal( div.length, 4, "Correct number of elements generated for div hr code b" );
  92. equal( div.parent().length, 0, "Make sure that the generated HTML has no parent." );
  93. equal( jQuery([1,2,3]).get(1), 2, "Test passing an array to the factory" );
  94. equal( jQuery(document.body).get(0), jQuery("body").get(0), "Test passing an html node to the factory" );
  95. elem = jQuery("<div/>", attrObj );
  96. if ( jQuery.fn.width ) {
  97. equal( elem[0].style.width, "10px", "jQuery() quick setter width");
  98. }
  99. if ( jQuery.fn.offset ) {
  100. equal( elem[0].style.top, "1px", "jQuery() quick setter offset");
  101. }
  102. if ( jQuery.fn.css ) {
  103. equal( elem[0].style.paddingLeft, "1px", "jQuery quick setter css");
  104. equal( elem[0].style.paddingRight, "1px", "jQuery quick setter css");
  105. }
  106. if ( jQuery.fn.attr ) {
  107. equal( elem[0].getAttribute("desired"), "very", "jQuery quick setter attr");
  108. }
  109. equal( elem[0].childNodes.length, 1, "jQuery quick setter text");
  110. equal( elem[0].firstChild.nodeValue, "test", "jQuery quick setter text");
  111. equal( elem[0].className, "test2", "jQuery() quick setter class");
  112. equal( elem[0].id, "test3", "jQuery() quick setter id");
  113. exec = true;
  114. elem.trigger("click");
  115. // manually clean up detached elements
  116. elem.remove();
  117. for ( i = 0; i < 3; ++i ) {
  118. elem = jQuery("<input type='text' value='TEST' />");
  119. }
  120. equal( elem[0].defaultValue, "TEST", "Ensure cached nodes are cloned properly (Bug #6655)" );
  121. // manually clean up detached elements
  122. elem.remove();
  123. for ( i = 0; i < 128; i++ ) {
  124. lng += "12345678";
  125. }
  126. });
  127. test( "selector state", function() {
  128. expect( 18 );
  129. var test;
  130. test = jQuery( undefined );
  131. equal( test.selector, "", "Empty jQuery Selector" );
  132. equal( test.context, undefined, "Empty jQuery Context" );
  133. test = jQuery( document );
  134. equal( test.selector, "", "Document Selector" );
  135. equal( test.context, document, "Document Context" );
  136. test = jQuery( document.body );
  137. equal( test.selector, "", "Body Selector" );
  138. equal( test.context, document.body, "Body Context" );
  139. test = jQuery("#qunit-fixture");
  140. equal( test.selector, "#qunit-fixture", "#qunit-fixture Selector" );
  141. equal( test.context, document, "#qunit-fixture Context" );
  142. test = jQuery("#notfoundnono");
  143. equal( test.selector, "#notfoundnono", "#notfoundnono Selector" );
  144. equal( test.context, document, "#notfoundnono Context" );
  145. test = jQuery( "#qunit-fixture", document );
  146. equal( test.selector, "#qunit-fixture", "#qunit-fixture Selector" );
  147. equal( test.context, document, "#qunit-fixture Context" );
  148. test = jQuery( "#qunit-fixture", document.body );
  149. equal( test.selector, "#qunit-fixture", "#qunit-fixture Selector" );
  150. equal( test.context, document.body, "#qunit-fixture Context" );
  151. // Test cloning
  152. test = jQuery( test );
  153. equal( test.selector, "#qunit-fixture", "#qunit-fixture Selector" );
  154. equal( test.context, document.body, "#qunit-fixture Context" );
  155. test = jQuery( document.body ).find("#qunit-fixture");
  156. equal( test.selector, "#qunit-fixture", "#qunit-fixture find Selector" );
  157. equal( test.context, document.body, "#qunit-fixture find Context" );
  158. });
  159. test( "globalEval", function() {
  160. expect( 3 );
  161. Globals.register("globalEvalTest");
  162. jQuery.globalEval("globalEvalTest = 1;");
  163. equal( window.globalEvalTest, 1, "Test variable assignments are global" );
  164. jQuery.globalEval("var globalEvalTest = 2;");
  165. equal( window.globalEvalTest, 2, "Test variable declarations are global" );
  166. jQuery.globalEval("this.globalEvalTest = 3;");
  167. equal( window.globalEvalTest, 3, "Test context (this) is the window object" );
  168. });
  169. test("noConflict", function() {
  170. expect(7);
  171. var $$ = jQuery;
  172. strictEqual( jQuery, jQuery.noConflict(), "noConflict returned the jQuery object" );
  173. strictEqual( window["jQuery"], $$, "Make sure jQuery wasn't touched." );
  174. strictEqual( window["$"], original$, "Make sure $ was reverted." );
  175. jQuery = $ = $$;
  176. strictEqual( jQuery.noConflict(true), $$, "noConflict returned the jQuery object" );
  177. strictEqual( window["jQuery"], originaljQuery, "Make sure jQuery was reverted." );
  178. strictEqual( window["$"], original$, "Make sure $ was reverted." );
  179. ok( $$().pushStack([]), "Make sure that jQuery still works." );
  180. window["jQuery"] = jQuery = $$;
  181. });
  182. test("trim", function() {
  183. expect(13);
  184. var nbsp = String.fromCharCode(160);
  185. equal( jQuery.trim("hello "), "hello", "trailing space" );
  186. equal( jQuery.trim(" hello"), "hello", "leading space" );
  187. equal( jQuery.trim(" hello "), "hello", "space on both sides" );
  188. equal( jQuery.trim(" " + nbsp + "hello " + nbsp + " "), "hello", "&nbsp;" );
  189. equal( jQuery.trim(), "", "Nothing in." );
  190. equal( jQuery.trim( undefined ), "", "Undefined" );
  191. equal( jQuery.trim( null ), "", "Null" );
  192. equal( jQuery.trim( 5 ), "5", "Number" );
  193. equal( jQuery.trim( false ), "false", "Boolean" );
  194. equal( jQuery.trim(" "), "", "space should be trimmed" );
  195. equal( jQuery.trim("ipad\xA0"), "ipad", "nbsp should be trimmed" );
  196. equal( jQuery.trim("\uFEFF"), "", "zwsp should be trimmed" );
  197. equal( jQuery.trim("\uFEFF \xA0! | \uFEFF"), "! |", "leading/trailing should be trimmed" );
  198. });
  199. test("type", function() {
  200. expect( 28 );
  201. equal( jQuery.type(null), "null", "null" );
  202. equal( jQuery.type(undefined), "undefined", "undefined" );
  203. equal( jQuery.type(true), "boolean", "Boolean" );
  204. equal( jQuery.type(false), "boolean", "Boolean" );
  205. equal( jQuery.type(Boolean(true)), "boolean", "Boolean" );
  206. equal( jQuery.type(0), "number", "Number" );
  207. equal( jQuery.type(1), "number", "Number" );
  208. equal( jQuery.type(Number(1)), "number", "Number" );
  209. equal( jQuery.type(""), "string", "String" );
  210. equal( jQuery.type("a"), "string", "String" );
  211. equal( jQuery.type(String("a")), "string", "String" );
  212. equal( jQuery.type({}), "object", "Object" );
  213. equal( jQuery.type(/foo/), "regexp", "RegExp" );
  214. equal( jQuery.type(new RegExp("asdf")), "regexp", "RegExp" );
  215. equal( jQuery.type([1]), "array", "Array" );
  216. equal( jQuery.type(new Date()), "date", "Date" );
  217. equal( jQuery.type(new Function("return;")), "function", "Function" );
  218. equal( jQuery.type(function(){}), "function", "Function" );
  219. equal( jQuery.type(new Error()), "error", "Error" );
  220. equal( jQuery.type(window), "object", "Window" );
  221. equal( jQuery.type(document), "object", "Document" );
  222. equal( jQuery.type(document.body), "object", "Element" );
  223. equal( jQuery.type(document.createTextNode("foo")), "object", "TextNode" );
  224. equal( jQuery.type(document.getElementsByTagName("*")), "object", "NodeList" );
  225. // Avoid Lint complaints
  226. var MyString = String;
  227. var MyNumber = Number;
  228. var MyBoolean = Boolean;
  229. var MyObject = Object;
  230. equal( jQuery.type(new MyBoolean(true)), "boolean", "Boolean" );
  231. equal( jQuery.type(new MyNumber(1)), "number", "Number" );
  232. equal( jQuery.type(new MyString("a")), "string", "String" );
  233. equal( jQuery.type(new MyObject()), "object", "Object" );
  234. });
  235. asyncTest("isPlainObject", function() {
  236. expect(15);
  237. var pass, iframe, doc,
  238. fn = function() {};
  239. // The use case that we want to match
  240. ok( jQuery.isPlainObject({}), "{}" );
  241. // Not objects shouldn't be matched
  242. ok( !jQuery.isPlainObject(""), "string" );
  243. ok( !jQuery.isPlainObject(0) && !jQuery.isPlainObject(1), "number" );
  244. ok( !jQuery.isPlainObject(true) && !jQuery.isPlainObject(false), "boolean" );
  245. ok( !jQuery.isPlainObject(null), "null" );
  246. ok( !jQuery.isPlainObject(undefined), "undefined" );
  247. // Arrays shouldn't be matched
  248. ok( !jQuery.isPlainObject([]), "array" );
  249. // Instantiated objects shouldn't be matched
  250. ok( !jQuery.isPlainObject(new Date()), "new Date" );
  251. // Functions shouldn't be matched
  252. ok( !jQuery.isPlainObject(fn), "fn" );
  253. // Again, instantiated objects shouldn't be matched
  254. ok( !jQuery.isPlainObject(new fn()), "new fn (no methods)" );
  255. // Makes the function a little more realistic
  256. // (and harder to detect, incidentally)
  257. fn.prototype["someMethod"] = function(){};
  258. // Again, instantiated objects shouldn't be matched
  259. ok( !jQuery.isPlainObject(new fn()), "new fn" );
  260. // DOM Element
  261. ok( !jQuery.isPlainObject( document.createElement("div") ), "DOM Element" );
  262. // Window
  263. ok( !jQuery.isPlainObject( window ), "window" );
  264. pass = false;
  265. try {
  266. jQuery.isPlainObject( window.location );
  267. pass = true;
  268. } catch ( e ) {}
  269. ok( pass, "Does not throw exceptions on host objects" );
  270. // Objects from other windows should be matched
  271. window.iframeCallback = function( otherObject, detail ) {
  272. window.iframeCallback = undefined;
  273. iframe.parentNode.removeChild( iframe );
  274. ok( jQuery.isPlainObject(new otherObject()), "new otherObject" + ( detail ? " - " + detail : "" ) );
  275. start();
  276. };
  277. try {
  278. iframe = jQuery("#qunit-fixture")[0].appendChild( document.createElement("iframe") );
  279. doc = iframe.contentDocument || iframe.contentWindow.document;
  280. doc.open();
  281. doc.write("<body onload='window.parent.iframeCallback(Object);'>");
  282. doc.close();
  283. } catch(e) {
  284. window.iframeDone( Object, "iframes not supported" );
  285. }
  286. });
  287. test("isFunction", function() {
  288. expect(19);
  289. // Make sure that false values return false
  290. ok( !jQuery.isFunction(), "No Value" );
  291. ok( !jQuery.isFunction( null ), "null Value" );
  292. ok( !jQuery.isFunction( undefined ), "undefined Value" );
  293. ok( !jQuery.isFunction( "" ), "Empty String Value" );
  294. ok( !jQuery.isFunction( 0 ), "0 Value" );
  295. // Check built-ins
  296. // Safari uses "(Internal Function)"
  297. ok( jQuery.isFunction(String), "String Function("+String+")" );
  298. ok( jQuery.isFunction(Array), "Array Function("+Array+")" );
  299. ok( jQuery.isFunction(Object), "Object Function("+Object+")" );
  300. ok( jQuery.isFunction(Function), "Function Function("+Function+")" );
  301. // When stringified, this could be misinterpreted
  302. var mystr = "function";
  303. ok( !jQuery.isFunction(mystr), "Function String" );
  304. // When stringified, this could be misinterpreted
  305. var myarr = [ "function" ];
  306. ok( !jQuery.isFunction(myarr), "Function Array" );
  307. // When stringified, this could be misinterpreted
  308. var myfunction = { "function": "test" };
  309. ok( !jQuery.isFunction(myfunction), "Function Object" );
  310. // Make sure normal functions still work
  311. var fn = function(){};
  312. ok( jQuery.isFunction(fn), "Normal Function" );
  313. var obj = document.createElement("object");
  314. // Firefox says this is a function
  315. ok( !jQuery.isFunction(obj), "Object Element" );
  316. // IE says this is an object
  317. // Since 1.3, this isn't supported (#2968)
  318. //ok( jQuery.isFunction(obj.getAttribute), "getAttribute Function" );
  319. var nodes = document.body.childNodes;
  320. // Safari says this is a function
  321. ok( !jQuery.isFunction(nodes), "childNodes Property" );
  322. var first = document.body.firstChild;
  323. // Normal elements are reported ok everywhere
  324. ok( !jQuery.isFunction(first), "A normal DOM Element" );
  325. var input = document.createElement("input");
  326. input.type = "text";
  327. document.body.appendChild( input );
  328. // IE says this is an object
  329. // Since 1.3, this isn't supported (#2968)
  330. //ok( jQuery.isFunction(input.focus), "A default function property" );
  331. document.body.removeChild( input );
  332. var a = document.createElement("a");
  333. a.href = "some-function";
  334. document.body.appendChild( a );
  335. // This serializes with the word 'function' in it
  336. ok( !jQuery.isFunction(a), "Anchor Element" );
  337. document.body.removeChild( a );
  338. // Recursive function calls have lengths and array-like properties
  339. function callme(callback){
  340. function fn(response){
  341. callback(response);
  342. }
  343. ok( jQuery.isFunction(fn), "Recursive Function Call" );
  344. fn({ some: "data" });
  345. }
  346. callme(function(){
  347. callme(function(){});
  348. });
  349. });
  350. test( "isNumeric", function() {
  351. expect( 36 );
  352. var t = jQuery.isNumeric,
  353. Traditionalists = /** @constructor */ function(n) {
  354. this.value = n;
  355. this.toString = function(){
  356. return String(this.value);
  357. };
  358. },
  359. answer = new Traditionalists( "42" ),
  360. rong = new Traditionalists( "Devo" );
  361. ok( t("-10"), "Negative integer string");
  362. ok( t("0"), "Zero string");
  363. ok( t("5"), "Positive integer string");
  364. ok( t(-16), "Negative integer number");
  365. ok( t(0), "Zero integer number");
  366. ok( t(32), "Positive integer number");
  367. ok( t("040"), "Octal integer literal string");
  368. // OctalIntegerLiteral has been deprecated since ES3/1999
  369. // It doesn't pass lint, so disabling until a solution can be found
  370. //ok( t(0144), "Octal integer literal");
  371. ok( t("0xFF"), "Hexadecimal integer literal string");
  372. ok( t(0xFFF), "Hexadecimal integer literal");
  373. ok( t("-1.6"), "Negative floating point string");
  374. ok( t("4.536"), "Positive floating point string");
  375. ok( t(-2.6), "Negative floating point number");
  376. ok( t(3.1415), "Positive floating point number");
  377. ok( t(8e5), "Exponential notation");
  378. ok( t("123e-2"), "Exponential notation string");
  379. ok( t(answer), "Custom .toString returning number");
  380. equal( t(""), false, "Empty string");
  381. equal( t(" "), false, "Whitespace characters string");
  382. equal( t("\t\t"), false, "Tab characters string");
  383. equal( t("abcdefghijklm1234567890"), false, "Alphanumeric character string");
  384. equal( t("xabcdefx"), false, "Non-numeric character string");
  385. equal( t(true), false, "Boolean true literal");
  386. equal( t(false), false, "Boolean false literal");
  387. equal( t("bcfed5.2"), false, "Number with preceding non-numeric characters");
  388. equal( t("7.2acdgs"), false, "Number with trailling non-numeric characters");
  389. equal( t(undefined), false, "Undefined value");
  390. equal( t(null), false, "Null value");
  391. equal( t(NaN), false, "NaN value");
  392. equal( t(Infinity), false, "Infinity primitive");
  393. equal( t(Number.POSITIVE_INFINITY), false, "Positive Infinity");
  394. equal( t(Number.NEGATIVE_INFINITY), false, "Negative Infinity");
  395. equal( t(rong), false, "Custom .toString returning non-number");
  396. equal( t({}), false, "Empty object");
  397. equal( t(function(){} ), false, "Instance of a function");
  398. equal( t( new Date() ), false, "Instance of a Date");
  399. equal( t(function(){} ), false, "Instance of a function");
  400. });
  401. test("isXMLDoc - HTML", function() {
  402. expect(4);
  403. ok( !jQuery.isXMLDoc( document ), "HTML document" );
  404. ok( !jQuery.isXMLDoc( document.documentElement ), "HTML documentElement" );
  405. ok( !jQuery.isXMLDoc( document.body ), "HTML Body Element" );
  406. var iframe = document.createElement("iframe");
  407. document.body.appendChild( iframe );
  408. try {
  409. var body = jQuery(iframe).contents()[0];
  410. try {
  411. ok( !jQuery.isXMLDoc( body ), "Iframe body element" );
  412. } catch(e) {
  413. ok( false, "Iframe body element exception" );
  414. }
  415. } catch(e) {
  416. ok( true, "Iframe body element - iframe not working correctly" );
  417. }
  418. document.body.removeChild( iframe );
  419. });
  420. test("XSS via location.hash", function() {
  421. expect(1);
  422. stop();
  423. jQuery["_check9521"] = function(x){
  424. ok( x, "script called from #id-like selector with inline handler" );
  425. jQuery("#check9521").remove();
  426. delete jQuery["_check9521"];
  427. start();
  428. };
  429. try {
  430. // This throws an error because it's processed like an id
  431. jQuery( "#<img id='check9521' src='no-such-.gif' onerror='jQuery._check9521(false)'>" ).appendTo("#qunit-fixture");
  432. } catch (err) {
  433. jQuery["_check9521"](true);
  434. }
  435. });
  436. test("isXMLDoc - XML", function() {
  437. expect(3);
  438. var xml = createDashboardXML();
  439. ok( jQuery.isXMLDoc( xml ), "XML document" );
  440. ok( jQuery.isXMLDoc( xml.documentElement ), "XML documentElement" );
  441. ok( jQuery.isXMLDoc( jQuery("tab", xml)[0] ), "XML Tab Element" );
  442. });
  443. test("isWindow", function() {
  444. expect( 14 );
  445. ok( jQuery.isWindow(window), "window" );
  446. ok( jQuery.isWindow(document.getElementsByTagName("iframe")[0].contentWindow), "iframe.contentWindow" );
  447. ok( !jQuery.isWindow(), "empty" );
  448. ok( !jQuery.isWindow(null), "null" );
  449. ok( !jQuery.isWindow(undefined), "undefined" );
  450. ok( !jQuery.isWindow(document), "document" );
  451. ok( !jQuery.isWindow(document.documentElement), "documentElement" );
  452. ok( !jQuery.isWindow(""), "string" );
  453. ok( !jQuery.isWindow(1), "number" );
  454. ok( !jQuery.isWindow(true), "boolean" );
  455. ok( !jQuery.isWindow({}), "object" );
  456. ok( !jQuery.isWindow({ setInterval: function(){} }), "fake window" );
  457. ok( !jQuery.isWindow(/window/), "regexp" );
  458. ok( !jQuery.isWindow(function(){}), "function" );
  459. });
  460. test("jQuery('html')", function() {
  461. expect( 15 );
  462. QUnit.reset();
  463. jQuery["foo"] = false;
  464. var s = jQuery("<script>jQuery.foo='test';</script>")[0];
  465. ok( s, "Creating a script" );
  466. ok( !jQuery["foo"], "Make sure the script wasn't executed prematurely" );
  467. jQuery("body").append("<script>jQuery.foo='test';</script>");
  468. ok( jQuery["foo"], "Executing a scripts contents in the right context" );
  469. // Test multi-line HTML
  470. var div = jQuery("<div>\r\nsome text\n<p>some p</p>\nmore text\r\n</div>")[0];
  471. equal( div.nodeName.toUpperCase(), "DIV", "Make sure we're getting a div." );
  472. equal( div.firstChild.nodeType, 3, "Text node." );
  473. equal( div.lastChild.nodeType, 3, "Text node." );
  474. equal( div.childNodes[1].nodeType, 1, "Paragraph." );
  475. equal( div.childNodes[1].firstChild.nodeType, 3, "Paragraph text." );
  476. QUnit.reset();
  477. ok( jQuery("<link rel='stylesheet'/>")[0], "Creating a link" );
  478. ok( !jQuery("<script/>")[0].parentNode, "Create a script" );
  479. ok( jQuery("<input/>").attr("type", "hidden"), "Create an input and set the type." );
  480. var j = jQuery("<span>hi</span> there <!-- mon ami -->");
  481. ok( j.length >= 2, "Check node,textnode,comment creation (some browsers delete comments)" );
  482. ok( !jQuery("<option>test</option>")[0].selected, "Make sure that options are auto-selected #2050" );
  483. ok( jQuery("<div></div>")[0], "Create a div with closing tag." );
  484. ok( jQuery("<table></table>")[0], "Create a table with closing tag." );
  485. // equal( jQuery("element[attribute='<div></div>']").length, 0, "When html is within brackets, do not recognize as html." );
  486. // equal( jQuery("element[attribute=<div></div>]").length, 0, "When html is within brackets, do not recognize as html." );
  487. // equal( jQuery("element:not(<div></div>)").length, 0, "When html is within parens, do not recognize as html." );
  488. // equal( jQuery("\\<div\\>").length, 0, "Ignore escaped html characters" );
  489. });
  490. test("jQuery('massive html #7990')", function() {
  491. expect( 3 );
  492. var i;
  493. var li = "<li>very very very very large html string</li>";
  494. var html = ["<ul>"];
  495. for ( i = 0; i < 30000; i += 1 ) {
  496. html[html.length] = li;
  497. }
  498. html[html.length] = "</ul>";
  499. html = jQuery(html.join(""))[0];
  500. equal( html.nodeName.toLowerCase(), "ul");
  501. equal( html.firstChild.nodeName.toLowerCase(), "li");
  502. equal( html.childNodes.length, 30000 );
  503. });
  504. test("jQuery('html', context)", function() {
  505. expect(1);
  506. var $div = jQuery("<div/>")[0];
  507. var $span = jQuery("<span/>", $div);
  508. equal($span.length, 1, "Verify a span created with a div context works, #1763");
  509. });
  510. test("jQuery(selector, xml).text(str) - Loaded via XML document", function() {
  511. expect(2);
  512. var xml = createDashboardXML();
  513. // tests for #1419 where IE was a problem
  514. var tab = jQuery("tab", xml).eq(0);
  515. equal( tab.text(), "blabla", "Verify initial text correct" );
  516. tab.text("newtext");
  517. equal( tab.text(), "newtext", "Verify new text correct" );
  518. });
  519. test("end()", function() {
  520. expect(3);
  521. equal( "Yahoo", jQuery("#yahoo").parent().end().text(), "Check for end" );
  522. ok( jQuery("#yahoo").end(), "Check for end with nothing to end" );
  523. var x = jQuery("#yahoo");
  524. x.parent();
  525. equal( "Yahoo", jQuery("#yahoo").text(), "Check for non-destructive behaviour" );
  526. });
  527. test("length", function() {
  528. expect(1);
  529. equal( jQuery("#qunit-fixture p").length, 6, "Get Number of Elements Found" );
  530. });
  531. test("size()", function() {
  532. expect(1);
  533. equal( jQuery("#qunit-fixture p").size(), 6, "Get Number of Elements Found" );
  534. });
  535. test("get()", function() {
  536. expect(1);
  537. deepEqual( jQuery("#qunit-fixture p").get(), q("firstp","ap","sndp","en","sap","first"), "Get All Elements" );
  538. });
  539. test("toArray()", function() {
  540. expect(1);
  541. deepEqual( jQuery("#qunit-fixture p").toArray(),
  542. q("firstp","ap","sndp","en","sap","first"),
  543. "Convert jQuery object to an Array" );
  544. });
  545. test("inArray()", function() {
  546. expect(19);
  547. var selections = {
  548. p: q("firstp", "sap", "ap", "first"),
  549. em: q("siblingnext", "siblingfirst"),
  550. div: q("qunit-testrunner-toolbar", "nothiddendiv", "nothiddendivchild", "foo"),
  551. a: q("mark", "groups", "google", "simon1"),
  552. empty: []
  553. },
  554. tests = {
  555. p: { elem: jQuery("#ap")[0], index: 2 },
  556. em: { elem: jQuery("#siblingfirst")[0], index: 1 },
  557. div: { elem: jQuery("#nothiddendiv")[0], index: 1 },
  558. a: { elem: jQuery("#simon1")[0], index: 3 }
  559. },
  560. falseTests = {
  561. p: jQuery("#liveSpan1")[0],
  562. em: jQuery("#nothiddendiv")[0],
  563. empty: ""
  564. };
  565. jQuery.each( tests, function( key, obj ) {
  566. equal( jQuery.inArray( obj.elem, selections[ key ] ), obj.index, "elem is in the array of selections of its tag" );
  567. // Third argument (fromIndex)
  568. equal( !!~jQuery.inArray( obj.elem, selections[ key ], 5 ), false, "elem is NOT in the array of selections given a starting index greater than its position" );
  569. equal( !!~jQuery.inArray( obj.elem, selections[ key ], 1 ), true, "elem is in the array of selections given a starting index less than or equal to its position" );
  570. equal( !!~jQuery.inArray( obj.elem, selections[ key ], -3 ), true, "elem is in the array of selections given a negative index" );
  571. });
  572. jQuery.each( falseTests, function( key, elem ) {
  573. equal( !!~jQuery.inArray( elem, selections[ key ] ), false, "elem is NOT in the array of selections" );
  574. });
  575. });
  576. test("get(Number)", function() {
  577. expect(2);
  578. equal( jQuery("#qunit-fixture p").get(0), document.getElementById("firstp"), "Get A Single Element" );
  579. strictEqual( jQuery("#firstp").get(1), undefined, "Try get with index larger elements count" );
  580. });
  581. test("get(-Number)",function() {
  582. expect(2);
  583. equal( jQuery("p").get(-1), document.getElementById("first"), "Get a single element with negative index" );
  584. strictEqual( jQuery("#firstp").get(-2), undefined, "Try get with index negative index larger then elements count" );
  585. });
  586. test("each(Function)", function() {
  587. expect(1);
  588. var div = jQuery("div");
  589. div.each(function(){this.foo = "zoo";});
  590. var pass = true;
  591. for ( var i = 0; i < div.size(); i++ ) {
  592. if ( div.get(i).foo != "zoo" ) {
  593. pass = false;
  594. }
  595. }
  596. ok( pass, "Execute a function, Relative" );
  597. });
  598. test("slice()", function() {
  599. expect(7);
  600. var $links = jQuery("#ap a");
  601. deepEqual( $links.slice(1,2).get(), q("groups"), "slice(1,2)" );
  602. deepEqual( $links.slice(1).get(), q("groups", "anchor1", "mark"), "slice(1)" );
  603. deepEqual( $links.slice(0,3).get(), q("google", "groups", "anchor1"), "slice(0,3)" );
  604. deepEqual( $links.slice(-1).get(), q("mark"), "slice(-1)" );
  605. deepEqual( $links.eq(1).get(), q("groups"), "eq(1)" );
  606. deepEqual( $links.eq("2").get(), q("anchor1"), "eq('2')" );
  607. deepEqual( $links.eq(-1).get(), q("mark"), "eq(-1)" );
  608. });
  609. test("first()/last()", function() {
  610. expect(4);
  611. var $links = jQuery("#ap a"), $none = jQuery("asdf");
  612. deepEqual( $links.first().get(), q("google"), "first()" );
  613. deepEqual( $links.last().get(), q("mark"), "last()" );
  614. deepEqual( $none.first().get(), [], "first() none" );
  615. deepEqual( $none.last().get(), [], "last() none" );
  616. });
  617. test("map()", function() {
  618. expect( 2 );
  619. deepEqual(
  620. jQuery("#ap").map(function() {
  621. return jQuery( this ).find("a").get();
  622. }).get(),
  623. q( "google", "groups", "anchor1", "mark" ),
  624. "Array Map"
  625. );
  626. deepEqual(
  627. jQuery("#ap > a").map(function() {
  628. return this.parentNode;
  629. }).get(),
  630. q( "ap","ap","ap" ),
  631. "Single Map"
  632. );
  633. });
  634. test("jQuery.map", function() {
  635. expect( 25 );
  636. var i, label, result, callback;
  637. result = jQuery.map( [ 3, 4, 5 ], function( v, k ) {
  638. return k;
  639. });
  640. equal( result.join(""), "012", "Map the keys from an array" );
  641. result = jQuery.map( [ 3, 4, 5 ], function( v, k ) {
  642. return v;
  643. });
  644. equal( result.join(""), "345", "Map the values from an array" );
  645. result = jQuery.map( { a: 1, b: 2 }, function( v, k ) {
  646. return k;
  647. });
  648. equal( result.join(""), "ab", "Map the keys from an object" );
  649. result = jQuery.map( { a: 1, b: 2 }, function( v, k ) {
  650. return v;
  651. });
  652. equal( result.join(""), "12", "Map the values from an object" );
  653. result = jQuery.map( [ "a", undefined, null, "b" ], function( v, k ) {
  654. return v;
  655. });
  656. equal( result.join(""), "ab", "Array iteration does not include undefined/null results" );
  657. result = jQuery.map( { a: "a", b: undefined, c: null, d: "b" }, function( v, k ) {
  658. return v;
  659. });
  660. equal( result.join(""), "ab", "Object iteration does not include undefined/null results" );
  661. result = {
  662. Zero: function() {},
  663. One: function( a ) {},
  664. Two: function( a, b ) {}
  665. };
  666. callback = function( v, k ) {
  667. equal( k, "foo", label + "-argument function treated like object" );
  668. };
  669. for ( i in result ) {
  670. label = i;
  671. result[ i ].foo = "bar";
  672. jQuery.map( result[ i ], callback );
  673. }
  674. result = {
  675. "undefined": undefined,
  676. "null": null,
  677. "false": false,
  678. "true": true,
  679. "empty string": "",
  680. "nonempty string": "string",
  681. "string \"0\"": "0",
  682. "negative": -1,
  683. "excess": 1
  684. };
  685. callback = function( v, k ) {
  686. equal( k, "length", "Object with " + label + " length treated like object" );
  687. };
  688. for ( i in result ) {
  689. label = i;
  690. jQuery.map( { length: result[ i ] }, callback );
  691. }
  692. result = {
  693. "sparse Array": Array( 4 ),
  694. "length: 1 plain object": { length: 1, "0": true },
  695. "length: 2 plain object": { length: 2, "0": true, "1": true },
  696. NodeList: document.getElementsByTagName("html")
  697. };
  698. callback = function( v, k ) {
  699. if ( result[ label ] ) {
  700. delete result[ label ];
  701. equal( k, "0", label + " treated like array" );
  702. }
  703. };
  704. for ( i in result ) {
  705. label = i;
  706. jQuery.map( result[ i ], callback );
  707. }
  708. result = false;
  709. jQuery.map( { length: 0 }, function( v, k ) {
  710. result = true;
  711. });
  712. ok( !result, "length: 0 plain object treated like array" );
  713. result = false;
  714. jQuery.map( document.getElementsByTagName("asdf"), function( v, k ) {
  715. result = true;
  716. });
  717. ok( !result, "empty NodeList treated like array" );
  718. result = jQuery.map( Array(4), function( v, k ){
  719. return k % 2 ? k : [k,k,k];
  720. });
  721. equal( result.join(""), "00012223", "Array results flattened (#2616)" );
  722. });
  723. test("jQuery.merge()", function() {
  724. expect(8);
  725. deepEqual( jQuery.merge([],[]), [], "Empty arrays" );
  726. deepEqual( jQuery.merge([ 1 ],[ 2 ]), [ 1, 2 ], "Basic" );
  727. deepEqual( jQuery.merge([ 1, 2 ], [ 3, 4 ]), [ 1, 2, 3, 4 ], "Basic" );
  728. deepEqual( jQuery.merge([ 1, 2 ],[]), [ 1, 2 ], "Second empty" );
  729. deepEqual( jQuery.merge([],[ 1, 2 ]), [ 1, 2 ], "First empty" );
  730. // Fixed at [5998], #3641
  731. deepEqual( jQuery.merge([ -2, -1 ], [ 0, 1, 2 ]), [ -2, -1 , 0, 1, 2 ],
  732. "Second array including a zero (falsy)");
  733. // After fixing #5527
  734. deepEqual( jQuery.merge([], [ null, undefined ]), [ null, undefined ],
  735. "Second array including null and undefined values");
  736. deepEqual( jQuery.merge({ length: 0 }, [ 1, 2 ] ), { length: 2, 0: 1, 1: 2},
  737. "First array like");
  738. });
  739. test("jQuery.extend(Object, Object)", function() {
  740. expect(28);
  741. var settings = { "xnumber1": 5, "xnumber2": 7, "xstring1": "peter", "xstring2": "pan" },
  742. options = { "xnumber2": 1, "xstring2": "x", "xxx": "newstring" },
  743. optionsCopy = { "xnumber2": 1, "xstring2": "x", "xxx": "newstring" },
  744. merged = { "xnumber1": 5, "xnumber2": 1, "xstring1": "peter", "xstring2": "x", "xxx": "newstring" },
  745. deep1 = { "foo": { "bar": true } },
  746. deep1copy = { "foo": { "bar": true } },
  747. deep2 = { "foo": { "baz": true }, "foo2": document },
  748. deep2copy = { "foo": { "baz": true }, "foo2": document },
  749. deepmerged = { "foo": { "bar": true, "baz": true }, "foo2": document },
  750. arr = [1, 2, 3],
  751. nestedarray = { "arr": arr };
  752. jQuery.extend(settings, options);
  753. deepEqual( settings, merged, "Check if extended: settings must be extended" );
  754. deepEqual( options, optionsCopy, "Check if not modified: options must not be modified" );
  755. jQuery.extend(settings, null, options);
  756. deepEqual( settings, merged, "Check if extended: settings must be extended" );
  757. deepEqual( options, optionsCopy, "Check if not modified: options must not be modified" );
  758. jQuery.extend(true, deep1, deep2);
  759. deepEqual( deep1["foo"], deepmerged["foo"], "Check if foo: settings must be extended" );
  760. deepEqual( deep2["foo"], deep2copy["foo"], "Check if not deep2: options must not be modified" );
  761. equal( deep1["foo2"], document, "Make sure that a deep clone was not attempted on the document" );
  762. ok( jQuery.extend(true, {}, nestedarray)["arr"] !== arr, "Deep extend of object must clone child array" );
  763. // #5991
  764. ok( jQuery.isArray( jQuery.extend(true, { "arr": {} }, nestedarray)["arr"] ), "Cloned array heve to be an Array" );
  765. ok( jQuery.isPlainObject( jQuery.extend(true, { "arr": arr }, { "arr": {} })["arr"] ), "Cloned object heve to be an plain object" );
  766. var empty = {};
  767. var optionsWithLength = { "foo": { "length": -1 } };
  768. jQuery.extend(true, empty, optionsWithLength);
  769. deepEqual( empty["foo"], optionsWithLength["foo"], "The length property must copy correctly" );
  770. empty = {};
  771. var optionsWithDate = { "foo": { "date": new Date() } };
  772. jQuery.extend(true, empty, optionsWithDate);
  773. deepEqual( empty["foo"], optionsWithDate["foo"], "Dates copy correctly" );
  774. /** @constructor */
  775. var myKlass = function() {};
  776. var customObject = new myKlass();
  777. var optionsWithCustomObject = { "foo": { "date": customObject } };
  778. empty = {};
  779. jQuery.extend(true, empty, optionsWithCustomObject);
  780. ok( empty["foo"] && empty["foo"]["date"] === customObject, "Custom objects copy correctly (no methods)" );
  781. // Makes the class a little more realistic
  782. myKlass.prototype = { "someMethod": function(){} };
  783. empty = {};
  784. jQuery.extend(true, empty, optionsWithCustomObject);
  785. ok( empty["foo"] && empty["foo"]["date"] === customObject, "Custom objects copy correctly" );
  786. var MyNumber = Number;
  787. var ret = jQuery.extend(true, { "foo": 4 }, { "foo": new MyNumber(5) } );
  788. ok( ret.foo == 5, "Wrapped numbers copy correctly" );
  789. var nullUndef;
  790. nullUndef = jQuery.extend({}, options, { "xnumber2": null });
  791. ok( nullUndef["xnumber2"] === null, "Check to make sure null values are copied");
  792. nullUndef = jQuery.extend({}, options, { "xnumber2": undefined });
  793. ok( nullUndef["xnumber2"] === options["xnumber2"], "Check to make sure undefined values are not copied");
  794. nullUndef = jQuery.extend({}, options, { "xnumber0": null });
  795. ok( nullUndef["xnumber0"] === null, "Check to make sure null values are inserted");
  796. var target = {};
  797. var recursive = { foo:target, bar:5 };
  798. jQuery.extend(true, target, recursive);
  799. deepEqual( target, { bar:5 }, "Check to make sure a recursive obj doesn't go never-ending loop by not copying it over" );
  800. ret = jQuery.extend(true, { foo: [] }, { foo: [0] } ); // 1907
  801. equal( ret.foo.length, 1, "Check to make sure a value with coersion 'false' copies over when necessary to fix #1907" );
  802. ret = jQuery.extend(true, { foo: "1,2,3" }, { foo: [1, 2, 3] } );
  803. ok( typeof ret.foo != "string", "Check to make sure values equal with coersion (but not actually equal) overwrite correctly" );
  804. ret = jQuery.extend(true, { foo:"bar" }, { foo:null } );
  805. ok( typeof ret.foo !== "undefined", "Make sure a null value doesn't crash with deep extend, for #1908" );
  806. var obj = { foo:null };
  807. jQuery.extend(true, obj, { foo:"notnull" } );
  808. equal( obj.foo, "notnull", "Make sure a null value can be overwritten" );
  809. function func() {}
  810. jQuery.extend(func, { key: "value" } );
  811. equal( func.key, "value", "Verify a function can be extended" );
  812. var defaults = { xnumber1: 5, xnumber2: 7, xstring1: "peter", xstring2: "pan" },
  813. defaultsCopy = { xnumber1: 5, xnumber2: 7, xstring1: "peter", xstring2: "pan" },
  814. options1 = { xnumber2: 1, xstring2: "x" },
  815. options1Copy = { xnumber2: 1, xstring2: "x" },
  816. options2 = { xstring2: "xx", xxx: "newstringx" },
  817. options2Copy = { xstring2: "xx", xxx: "newstringx" },
  818. merged2 = { xnumber1: 5, xnumber2: 1, xstring1: "peter", xstring2: "xx", xxx: "newstringx" };
  819. settings = jQuery.extend({}, defaults, options1, options2);
  820. deepEqual( settings, merged2, "Check if extended: settings must be extended" );
  821. deepEqual( defaults, defaultsCopy, "Check if not modified: options1 must not be modified" );
  822. deepEqual( options1, options1Copy, "Check if not modified: options1 must not be modified" );
  823. deepEqual( options2, options2Copy, "Check if not modified: options2 must not be modified" );
  824. });
  825. test("jQuery.each(Object,Function)", function() {
  826. expect( 23 );
  827. var i, label, seen, callback;
  828. seen = {};
  829. jQuery.each( [ 3, 4, 5 ], function( k, v ) {
  830. seen[ k ] = v;
  831. });
  832. deepEqual( seen, { "0": 3, "1": 4, "2": 5 }, "Array iteration" );
  833. seen = {};
  834. jQuery.each( { name: "name", lang: "lang" }, function( k, v ) {
  835. seen[ k ] = v;
  836. });
  837. deepEqual( seen, { name: "name", lang: "lang" }, "Object iteration" );
  838. seen = [];
  839. jQuery.each( [ 1, 2, 3 ], function( k, v ) {
  840. seen.push( v );
  841. if ( k === 1 ) {
  842. return false;
  843. }
  844. });
  845. deepEqual( seen, [ 1, 2 ] , "Broken array iteration" );
  846. seen = [];
  847. jQuery.each( {"a": 1, "b": 2,"c": 3 }, function( k, v ) {
  848. seen.push( v );
  849. return false;
  850. });
  851. deepEqual( seen, [ 1 ], "Broken object iteration" );
  852. seen = {
  853. Zero: function() {},
  854. One: function( a ) {},
  855. Two: function( a, b ) {}
  856. };
  857. callback = function( k, v ) {
  858. equal( k, "foo", label + "-argument function treated like object" );
  859. };
  860. for ( i in seen ) {
  861. label = i;
  862. seen[ i ].foo = "bar";
  863. jQuery.each( seen[ i ], callback );
  864. }
  865. seen = {
  866. "undefined": undefined,
  867. "null": null,
  868. "false": false,
  869. "true": true,
  870. "empty string": "",
  871. "nonempty string": "string",
  872. "string \"0\"": "0",
  873. "negative": -1,
  874. "excess": 1
  875. };
  876. callback = function( k, v ) {
  877. equal( k, "length", "Object with " + label + " length treated like object" );
  878. };
  879. for ( i in seen ) {
  880. label = i;
  881. jQuery.each( { length: seen[ i ] }, callback );
  882. }
  883. seen = {
  884. "sparse Array": Array( 4 ),
  885. "length: 1 plain object": { length: 1, "0": true },
  886. "length: 2 plain object": { length: 2, "0": true, "1": true },
  887. NodeList: document.getElementsByTagName("html")
  888. };
  889. callback = function( k, v ) {
  890. if ( seen[ label ] ) {
  891. delete seen[ label ];
  892. equal( k, "0", label + " treated like array" );
  893. return false;
  894. }
  895. };
  896. for ( i in seen ) {
  897. label = i;
  898. jQuery.each( seen[ i ], callback );
  899. }
  900. seen = false;
  901. jQuery.each( { length: 0 }, function( k, v ) {
  902. seen = true;
  903. });
  904. ok( !seen, "length: 0 plain object treated like array" );
  905. seen = false;
  906. jQuery.each( document.getElementsByTagName("asdf"), function( k, v ) {
  907. seen = true;
  908. });
  909. ok( !seen, "empty NodeList treated like array" );
  910. i = 0;
  911. jQuery.each( document.styleSheets, function() {
  912. i++;
  913. });
  914. equal( i, 2, "Iteration over document.styleSheets" );
  915. });
  916. test("jQuery.makeArray", function(){
  917. expect(15);
  918. equal( jQuery.makeArray(jQuery("html>*"))[0].nodeName.toUpperCase(), "HEAD", "Pass makeArray a jQuery object" );
  919. equal( jQuery.makeArray(document.getElementsByName("PWD")).slice(0,1)[0].name, "PWD", "Pass makeArray a nodelist" );
  920. equal( (function(arg1, arg2){ return jQuery.makeArray(arguments); })(1,2).join(""), "12", "Pass makeArray an arguments array" );
  921. equal( jQuery.makeArray([1,2,3]).join(""), "123", "Pass makeArray a real array" );
  922. equal( jQuery.makeArray().length, 0, "Pass nothing to makeArray and expect an empty array" );
  923. equal( jQuery.makeArray( 0 )[0], 0 , "Pass makeArray a number" );
  924. equal( jQuery.makeArray( "foo" )[0], "foo", "Pass makeArray a string" );
  925. equal( jQuery.makeArray( true )[0].constructor, Boolean, "Pass makeArray a boolean" );
  926. equal( jQuery.makeArray( document.createElement("div") )[0].nodeName.toUpperCase(), "DIV", "Pass makeArray a single node" );
  927. equal( jQuery.makeArray( {length:2, 0:"a", 1:"b"} ).join(""), "ab", "Pass makeArray an array like map (with length)" );
  928. ok( !!jQuery.makeArray( document.documentElement.childNodes ).slice(0,1)[0].nodeName, "Pass makeArray a childNodes array" );
  929. // function, is tricky as it has length
  930. equal( jQuery.makeArray( function(){ return 1;} )[0](), 1, "Pass makeArray a function" );
  931. //window, also has length
  932. equal( jQuery.makeArray(window)[0], window, "Pass makeArray the window" );
  933. equal( jQuery.makeArray(/a/)[0].constructor, RegExp, "Pass makeArray a regex" );
  934. // Some nodes inherit traits of nodelists
  935. ok( jQuery.makeArray(document.getElementById("form")).length >= 13,
  936. "Pass makeArray a form (treat as elements)" );
  937. });
  938. test("jQuery.inArray", function(){
  939. expect(3);
  940. equal( jQuery.inArray( 0, false ), -1 , "Search in 'false' as array returns -1 and doesn't throw exception" );
  941. equal( jQuery.inArray( 0, null ), -1 , "Search in 'null' as array returns -1 and doesn't throw exception" );
  942. equal( jQuery.inArray( 0, undefined ), -1 , "Search in 'undefined' as array returns -1 and doesn't throw exception" );
  943. });
  944. test("jQuery.isEmptyObject", function(){
  945. expect(2);
  946. equal(true, jQuery.isEmptyObject({}), "isEmptyObject on empty object literal" );
  947. equal(false, jQuery.isEmptyObject({a:1}), "isEmptyObject on non-empty object literal" );
  948. // What about this ?
  949. // equal(true, jQuery.isEmptyObject(null), "isEmptyObject on null" );
  950. });
  951. test("jQuery.proxy", function(){
  952. expect( 9 );
  953. var test = function(){ equal( this, thisObject, "Make sure that scope is set properly." ); };
  954. var thisObject = { foo: "bar", method: test };
  955. // Make sure normal works
  956. test.call( thisObject );
  957. // Basic scoping
  958. jQuery.proxy( test, thisObject )();
  959. // Another take on it
  960. jQuery.proxy( thisObject, "method" )();
  961. // Make sure it doesn't freak out
  962. equal( jQuery.proxy( null, thisObject ), undefined, "Make sure no function was returned." );
  963. // Partial application
  964. var test2 = function( a ){ equal( a, "pre-applied", "Ensure arguments can be pre-applied." ); };
  965. jQuery.proxy( test2, null, "pre-applied" )();
  966. // Partial application w/ normal arguments
  967. var test3 = function( a, b ){ equal( b, "normal", "Ensure arguments can be pre-applied and passed as usual." ); };
  968. jQuery.proxy( test3, null, "pre-applied" )( "normal" );
  969. // Test old syntax
  970. var test4 = { "meth": function( a ){ equal( a, "boom", "Ensure old syntax works." ); } };
  971. jQuery.proxy( test4, "meth" )( "boom" );
  972. // jQuery 1.9 improved currying with `this` object
  973. var fn = function() {
  974. equal( Array.prototype.join.call( arguments, "," ), "arg1,arg2,arg3", "args passed" );
  975. equal( this.foo, "bar", "this-object passed" );
  976. };
  977. var cb = jQuery.proxy( fn, null, "arg1", "arg2" );
  978. cb.call( thisObject, "arg3" );
  979. });
  980. test("jQuery.parseHTML", function() {
  981. expect( 17 );
  982. var html, nodes;
  983. equal( jQuery.parseHTML(), null, "Nothing in, null out." );
  984. equal( jQuery.parseHTML( null ), null, "Null in, null out." );
  985. equal( jQuery.parseHTML( "" ), null, "Empty string in, null out." );
  986. raises(function() {
  987. jQuery.parseHTML( "<div></div>", document.getElementById("form") );
  988. }, "Passing an element as the context raises an exception (context should be a document)");
  989. nodes = jQuery.parseHTML( jQuery("body")[0].innerHTML );
  990. ok( nodes.length > 4, "Parse a large html string" );
  991. equal( jQuery.type( nodes ), "array", "parseHTML returns an array rather than a nodelist" );
  992. html = "<script>undefined()</script>";
  993. equal( jQuery.parseHTML( html ).length, 0, "Ignore scripts by default" );
  994. equal( jQuery.parseHTML( html, true )[0].nodeName.toLowerCase(), "script", "Preserve scripts when requested" );
  995. html += "<div></div>";
  996. equal( jQuery.parseHTML( html )[0].nodeName.toLowerCase(), "div", "Preserve non-script nodes" );
  997. equal( jQuery.parseHTML( html, true )[0].nodeName.toLowerCase(), "script", "Preserve script position");
  998. equal( jQuery.parseHTML("text")[0].nodeType, 3, "Parsing text returns a text node" );
  999. equal( jQuery.parseHTML( "\t<div></div>" )[0].nodeValue, "\t", "Preserve leading whitespace" );
  1000. equal( jQuery.parseHTML(" <div/> ")[0].nodeType, 3, "Leading spaces are treated as text nodes (#11290)" );
  1001. html = jQuery.parseHTML( "<div>test div</div>" );
  1002. equal( html[ 0 ].parentNode.nodeType, 11, "parentNode should be documentFragment" );
  1003. equal( html[ 0 ].innerHTML, "test div", "Content should be preserved" );
  1004. equal( jQuery.parseHTML("<span><span>").length, 1, "Incorrect html-strings should not break anything" );
  1005. equal( jQuery.parseHTML("<td><td>")[ 1 ].parentNode.nodeType, 11, "parentNode should be documentFragment" );
  1006. });
  1007. test("jQuery.parseJSON", function(){
  1008. expect( 9 );
  1009. equal( jQuery.parseJSON( null ), null, "Actual null returns null" );
  1010. equal( jQuery.isEmptyObject( jQuery.parseJSON("{}") ), true, "Empty object returns empty object" );
  1011. deepEqual( jQuery.parseJSON("{\"test\":1}"), { "test": 1 }, "Plain object parses" );
  1012. deepEqual( jQuery.parseJSON("\n{\"test\":1}"), { "test": 1 }, "Leading whitespaces are ignored." );
  1013. raises(function() {
  1014. jQuery.parseJSON();
  1015. }, null, "Undefined raises an error" );
  1016. raises( function() {
  1017. jQuery.parseJSON( "" );
  1018. }, null, "Empty string raises an error" );
  1019. raises(function() {
  1020. jQuery.parseJSON("''");
  1021. }, null, "Single-quoted string raises an error" );
  1022. raises(function() {
  1023. jQuery.parseJSON("{a:1}");
  1024. }, null, "Unquoted property raises an error" );
  1025. raises(function() {
  1026. jQuery.parseJSON("{'a':1}");
  1027. }, null, "Single-quoted property raises an error" );
  1028. });
  1029. test("jQuery.parseXML", 8, function(){
  1030. var xml, tmp;
  1031. try {
  1032. xml = jQuery.parseXML( "<p>A <b>well-formed</b> xml string</p>" );
  1033. tmp = xml.getElementsByTagName( "p" )[ 0 ];
  1034. ok( !!tmp, "<p> present in document" );
  1035. tmp = tmp.getElementsByTagName( "b" )[ 0 ];
  1036. ok( !!tmp, "<b> present in document" );
  1037. strictEqual( tmp.childNodes[ 0 ].nodeValue, "well-formed", "<b> text is as expected" );
  1038. } catch (e) {
  1039. strictEqual( e, undefined, "unexpected error" );
  1040. }
  1041. try {
  1042. xml = jQuery.parseXML( "<p>Not a <<b>well-formed</b> xml string</p>" );
  1043. ok( false, "invalid xml not detected" );
  1044. } catch( e ) {
  1045. strictEqual( e.message, "Invalid XML: <p>Not a <<b>well-formed</b> xml string</p>", "invalid xml detected" );
  1046. }
  1047. try {
  1048. xml = jQuery.parseXML( "" );
  1049. strictEqual( xml, null, "empty string => null document" );
  1050. xml = jQuery.parseXML();
  1051. strictEqual( xml, null, "undefined string => null document" );
  1052. xml = jQuery.parseXML( null );
  1053. strictEqual( xml, null, "null string => null document" );
  1054. xml = jQuery.parseXML( true );
  1055. strictEqual( xml, null, "non-string => null document" );
  1056. } catch( e ) {
  1057. ok( false, "empty input throws exception" );
  1058. }
  1059. });
  1060. test("jQuery.camelCase()", function() {
  1061. var tests = {
  1062. "foo-bar": "fooBar",
  1063. "foo-bar-baz": "fooBarBaz",
  1064. "girl-u-want": "girlUWant",
  1065. "the-4th-dimension": "the4thDimension",
  1066. "-o-tannenbaum": "OTannenbaum",
  1067. "-moz-illa": "MozIlla",
  1068. "-ms-take": "msTake"
  1069. };
  1070. expect(7);
  1071. jQuery.each( tests, function( key, val ) {
  1072. equal( jQuery.camelCase( key ), val, "Converts: " + key + " => " + val );
  1073. });
  1074. });