core.js 47 KB

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