Merge branch 'map-object.1.6' of https://github.com/danheberden/jquery into danheberd...
[jquery.git] / test / unit / core.js
blobed1fb5918b4e1c2a45a0fbc11cfe3a97868ec363
1 module("core", { teardown: moduleTeardown });
3 test("Basic requirements", function() {
4         expect(7);
5         ok( Array.prototype.push, "Array.push()" );
6         ok( Function.prototype.apply, "Function.apply()" );
7         ok( document.getElementById, "getElementById" );
8         ok( document.getElementsByTagName, "getElementsByTagName" );
9         ok( RegExp, "RegExp" );
10         ok( jQuery, "jQuery" );
11         ok( $, "$" );
12 });
14 test("jQuery()", function() {
15         expect(25);
17         // Basic constructor's behavior
19         equals( jQuery().length, 0, "jQuery() === jQuery([])" );
20         equals( jQuery(undefined).length, 0, "jQuery(undefined) === jQuery([])" );
21         equals( jQuery(null).length, 0, "jQuery(null) === jQuery([])" );
22         equals( jQuery("").length, 0, "jQuery('') === jQuery([])" );
23         equals( jQuery("#").length, 0, "jQuery('#') === jQuery([])" );
25         var obj = jQuery("div");
26         equals( jQuery(obj).selector, "div", "jQuery(jQueryObj) == jQueryObj" );
28                 // can actually yield more than one, when iframes are included, the window is an array as well
29         equals( jQuery(window).length, 1, "Correct number of elements generated for jQuery(window)" );
32         var main = jQuery("#main");
33         same( jQuery("div p", main).get(), q("sndp", "en", "sap"), "Basic selector with jQuery object as context" );
36         // disabled since this test was doing nothing. i tried to fix it but i'm not sure
37         // what the expected behavior should even be. FF returns "\n" for the text node
38         // make sure this is handled
39         var crlfContainer = jQuery('<p>\r\n</p>');
40         var x = crlfContainer.contents().get(0).nodeValue;
41         equals( x, what???, "Check for \\r and \\n in jQuery()" );
44         /* // Disabled until we add this functionality in
45         var pass = true;
46         try {
47                 jQuery("<div>Testing</div>").appendTo(document.getElementById("iframe").contentDocument.body);
48         } catch(e){
49                 pass = false;
50         }
51         ok( pass, "jQuery('&lt;tag&gt;') needs optional document parameter to ease cross-frame DOM wrangling, see #968" );*/
53         var code = jQuery("<code/>");
54         equals( code.length, 1, "Correct number of elements generated for code" );
55         equals( code.parent().length, 0, "Make sure that the generated HTML has no parent." );
56         var img = jQuery("<img/>");
57         equals( img.length, 1, "Correct number of elements generated for img" );
58         equals( img.parent().length, 0, "Make sure that the generated HTML has no parent." );
59         var div = jQuery("<div/><hr/><code/><b/>");
60         equals( div.length, 4, "Correct number of elements generated for div hr code b" );
61         equals( div.parent().length, 0, "Make sure that the generated HTML has no parent." );
63         equals( jQuery([1,2,3]).get(1), 2, "Test passing an array to the factory" );
65         equals( jQuery(document.body).get(0), jQuery('body').get(0), "Test passing an html node to the factory" );
67         var exec = false;
69         var elem = jQuery("<div/>", {
70                 width: 10,
71                 css: { paddingLeft:1, paddingRight:1 },
72                 click: function(){ ok(exec, "Click executed."); },
73                 text: "test",
74                 "class": "test2",
75                 id: "test3"
76         });
78         equals( elem[0].style.width, '10px', 'jQuery() quick setter width');
79         equals( elem[0].style.paddingLeft, '1px', 'jQuery quick setter css');
80         equals( elem[0].style.paddingRight, '1px', 'jQuery quick setter css');
81         equals( elem[0].childNodes.length, 1, 'jQuery quick setter text');
82         equals( elem[0].firstChild.nodeValue, "test", 'jQuery quick setter text');
83         equals( elem[0].className, "test2", 'jQuery() quick setter class');
84         equals( elem[0].id, "test3", 'jQuery() quick setter id');
86         exec = true;
87         elem.click();
89         // manually clean up detached elements
90         elem.remove();
92         for ( var i = 0; i < 3; ++i ) {
93                 elem = jQuery("<input type='text' value='TEST' />");
94         }
95         equals( elem[0].defaultValue, "TEST", "Ensure cached nodes are cloned properly (Bug #6655)" );
97         // manually clean up detached elements
98         elem.remove();
99 });
101 test("selector state", function() {
102         expect(31);
104         var test;
106         test = jQuery(undefined);
107         equals( test.selector, "", "Empty jQuery Selector" );
108         equals( test.context, undefined, "Empty jQuery Context" );
110         test = jQuery(document);
111         equals( test.selector, "", "Document Selector" );
112         equals( test.context, document, "Document Context" );
114         test = jQuery(document.body);
115         equals( test.selector, "", "Body Selector" );
116         equals( test.context, document.body, "Body Context" );
118         test = jQuery("#main");
119         equals( test.selector, "#main", "#main Selector" );
120         equals( test.context, document, "#main Context" );
122         test = jQuery("#notfoundnono");
123         equals( test.selector, "#notfoundnono", "#notfoundnono Selector" );
124         equals( test.context, document, "#notfoundnono Context" );
126         test = jQuery("#main", document);
127         equals( test.selector, "#main", "#main Selector" );
128         equals( test.context, document, "#main Context" );
130         test = jQuery("#main", document.body);
131         equals( test.selector, "#main", "#main Selector" );
132         equals( test.context, document.body, "#main Context" );
134         // Test cloning
135         test = jQuery(test);
136         equals( test.selector, "#main", "#main Selector" );
137         equals( test.context, document.body, "#main Context" );
139         test = jQuery(document.body).find("#main");
140         equals( test.selector, "#main", "#main find Selector" );
141         equals( test.context, document.body, "#main find Context" );
143         test = jQuery("#main").filter("div");
144         equals( test.selector, "#main.filter(div)", "#main filter Selector" );
145         equals( test.context, document, "#main filter Context" );
147         test = jQuery("#main").not("div");
148         equals( test.selector, "#main.not(div)", "#main not Selector" );
149         equals( test.context, document, "#main not Context" );
151         test = jQuery("#main").filter("div").not("div");
152         equals( test.selector, "#main.filter(div).not(div)", "#main filter, not Selector" );
153         equals( test.context, document, "#main filter, not Context" );
155         test = jQuery("#main").filter("div").not("div").end();
156         equals( test.selector, "#main.filter(div)", "#main filter, not, end Selector" );
157         equals( test.context, document, "#main filter, not, end Context" );
159         test = jQuery("#main").parent("body");
160         equals( test.selector, "#main.parent(body)", "#main parent Selector" );
161         equals( test.context, document, "#main parent Context" );
163         test = jQuery("#main").eq(0);
164         equals( test.selector, "#main.slice(0,1)", "#main eq Selector" );
165         equals( test.context, document, "#main eq Context" );
167         var d = "<div />";
168         equals(
169                 jQuery(d).appendTo(jQuery(d)).selector,
170                 jQuery(d).appendTo(d).selector,
171                 "manipulation methods make same selector for jQuery objects"
172         );
175 test( "globalEval", function() {
177         expect( 3 );
179         jQuery.globalEval( "var globalEvalTest = true;" );
180         ok( window.globalEvalTest, "Test variable declarations are global" );
182         window.globalEvalTest = false;
184         jQuery.globalEval( "globalEvalTest = true;" );
185         ok( window.globalEvalTest, "Test variable assignments are global" );
187         window.globalEvalTest = false;
189         jQuery.globalEval( "this.globalEvalTest = true;" );
190         ok( window.globalEvalTest, "Test context (this) is the window object" );
192         window.globalEvalTest = undefined;
195 if ( !isLocal ) {
196 test("browser", function() {
197         stop();
199         jQuery.get("data/ua.txt", function(data){
200                 var uas = data.split("\n");
201                 expect( (uas.length - 1) * 2 );
203                 jQuery.each(uas, function(){
204                         var parts = this.split("\t");
205                         if ( parts[2] ) {
206                                 var ua = jQuery.uaMatch( parts[2] );
207                                 equals( ua.browser, parts[0], "Checking browser for " + parts[2] );
208                                 equals( ua.version, parts[1], "Checking version string for " + parts[2] );
209                         }
210                 });
212                 start();
213         });
217 test("noConflict", function() {
218         expect(7);
220         var $$ = jQuery;
222         equals( jQuery, jQuery.noConflict(), "noConflict returned the jQuery object" );
223         equals( jQuery, $$, "Make sure jQuery wasn't touched." );
224         equals( $, original$, "Make sure $ was reverted." );
226         jQuery = $ = $$;
228         equals( jQuery.noConflict(true), $$, "noConflict returned the jQuery object" );
229         equals( jQuery, originaljQuery, "Make sure jQuery was reverted." );
230         equals( $, original$, "Make sure $ was reverted." );
231         ok( $$("#main").html("test"), "Make sure that jQuery still works." );
233         jQuery = $$;
236 test("trim", function() {
237         expect(9);
239         var nbsp = String.fromCharCode(160);
241         equals( jQuery.trim("hello  "), "hello", "trailing space" );
242         equals( jQuery.trim("  hello"), "hello", "leading space" );
243         equals( jQuery.trim("  hello   "), "hello", "space on both sides" );
244         equals( jQuery.trim("  " + nbsp + "hello  " + nbsp + " "), "hello", "&nbsp;" );
246         equals( jQuery.trim(), "", "Nothing in." );
247         equals( jQuery.trim( undefined ), "", "Undefined" );
248         equals( jQuery.trim( null ), "", "Null" );
249         equals( jQuery.trim( 5 ), "5", "Number" );
250         equals( jQuery.trim( false ), "false", "Boolean" );
253 test("type", function() {
254         expect(23);
256         equals( jQuery.type(null), "null", "null" );
257         equals( jQuery.type(undefined), "undefined", "undefined" );
258         equals( jQuery.type(true), "boolean", "Boolean" );
259         equals( jQuery.type(false), "boolean", "Boolean" );
260         equals( jQuery.type(Boolean(true)), "boolean", "Boolean" );
261         equals( jQuery.type(0), "number", "Number" );
262         equals( jQuery.type(1), "number", "Number" );
263         equals( jQuery.type(Number(1)), "number", "Number" );
264         equals( jQuery.type(""), "string", "String" );
265         equals( jQuery.type("a"), "string", "String" );
266         equals( jQuery.type(String("a")), "string", "String" );
267         equals( jQuery.type({}), "object", "Object" );
268         equals( jQuery.type(/foo/), "regexp", "RegExp" );
269         equals( jQuery.type(new RegExp("asdf")), "regexp", "RegExp" );
270         equals( jQuery.type([1]), "array", "Array" );
271         equals( jQuery.type(new Date()), "date", "Date" );
272         equals( jQuery.type(new Function("return;")), "function", "Function" );
273         equals( jQuery.type(function(){}), "function", "Function" );
274         equals( jQuery.type(window), "object", "Window" );
275         equals( jQuery.type(document), "object", "Document" );
276         equals( jQuery.type(document.body), "object", "Element" );
277         equals( jQuery.type(document.createTextNode("foo")), "object", "TextNode" );
278         equals( jQuery.type(document.getElementsByTagName("*")), "object", "NodeList" );
281 test("isPlainObject", function() {
282         expect(14);
284         stop();
286         // The use case that we want to match
287         ok(jQuery.isPlainObject({}), "{}");
289         // Not objects shouldn't be matched
290         ok(!jQuery.isPlainObject(""), "string");
291         ok(!jQuery.isPlainObject(0) && !jQuery.isPlainObject(1), "number");
292         ok(!jQuery.isPlainObject(true) && !jQuery.isPlainObject(false), "boolean");
293         ok(!jQuery.isPlainObject(null), "null");
294         ok(!jQuery.isPlainObject(undefined), "undefined");
296         // Arrays shouldn't be matched
297         ok(!jQuery.isPlainObject([]), "array");
299         // Instantiated objects shouldn't be matched
300         ok(!jQuery.isPlainObject(new Date), "new Date");
302         var fn = function(){};
304         // Functions shouldn't be matched
305         ok(!jQuery.isPlainObject(fn), "fn");
307         // Again, instantiated objects shouldn't be matched
308         ok(!jQuery.isPlainObject(new fn), "new fn (no methods)");
310         // Makes the function a little more realistic
311         // (and harder to detect, incidentally)
312         fn.prototype = {someMethod: function(){}};
314         // Again, instantiated objects shouldn't be matched
315         ok(!jQuery.isPlainObject(new fn), "new fn");
317         // DOM Element
318         ok(!jQuery.isPlainObject(document.createElement("div")), "DOM Element");
320         // Window
321         ok(!jQuery.isPlainObject(window), "window");
323         try {
324                 var iframe = document.createElement("iframe");
325                 document.body.appendChild(iframe);
327                 window.iframeDone = function(otherObject){
328                         // Objects from other windows should be matched
329                         ok(jQuery.isPlainObject(new otherObject), "new otherObject");
330                         document.body.removeChild( iframe );
331                         start();
332                 };
334                 var doc = iframe.contentDocument || iframe.contentWindow.document;
335                 doc.open();
336                 doc.write("<body onload='window.parent.iframeDone(Object);'>");
337                 doc.close();
338         } catch(e) {
339                 document.body.removeChild( iframe );
341                 ok(true, "new otherObject - iframes not supported");
342                 start();
343         }
346 test("isFunction", function() {
347         expect(19);
349         // Make sure that false values return false
350         ok( !jQuery.isFunction(), "No Value" );
351         ok( !jQuery.isFunction( null ), "null Value" );
352         ok( !jQuery.isFunction( undefined ), "undefined Value" );
353         ok( !jQuery.isFunction( "" ), "Empty String Value" );
354         ok( !jQuery.isFunction( 0 ), "0 Value" );
356         // Check built-ins
357         // Safari uses "(Internal Function)"
358         ok( jQuery.isFunction(String), "String Function("+String+")" );
359         ok( jQuery.isFunction(Array), "Array Function("+Array+")" );
360         ok( jQuery.isFunction(Object), "Object Function("+Object+")" );
361         ok( jQuery.isFunction(Function), "Function Function("+Function+")" );
363         // When stringified, this could be misinterpreted
364         var mystr = "function";
365         ok( !jQuery.isFunction(mystr), "Function String" );
367         // When stringified, this could be misinterpreted
368         var myarr = [ "function" ];
369         ok( !jQuery.isFunction(myarr), "Function Array" );
371         // When stringified, this could be misinterpreted
372         var myfunction = { "function": "test" };
373         ok( !jQuery.isFunction(myfunction), "Function Object" );
375         // Make sure normal functions still work
376         var fn = function(){};
377         ok( jQuery.isFunction(fn), "Normal Function" );
379         var obj = document.createElement("object");
381         // Firefox says this is a function
382         ok( !jQuery.isFunction(obj), "Object Element" );
384         // IE says this is an object
385         // Since 1.3, this isn't supported (#2968)
386         //ok( jQuery.isFunction(obj.getAttribute), "getAttribute Function" );
388         var nodes = document.body.childNodes;
390         // Safari says this is a function
391         ok( !jQuery.isFunction(nodes), "childNodes Property" );
393         var first = document.body.firstChild;
395         // Normal elements are reported ok everywhere
396         ok( !jQuery.isFunction(first), "A normal DOM Element" );
398         var input = document.createElement("input");
399         input.type = "text";
400         document.body.appendChild( input );
402         // IE says this is an object
403         // Since 1.3, this isn't supported (#2968)
404         //ok( jQuery.isFunction(input.focus), "A default function property" );
406         document.body.removeChild( input );
408         var a = document.createElement("a");
409         a.href = "some-function";
410         document.body.appendChild( a );
412         // This serializes with the word 'function' in it
413         ok( !jQuery.isFunction(a), "Anchor Element" );
415         document.body.removeChild( a );
417         // Recursive function calls have lengths and array-like properties
418         function callme(callback){
419                 function fn(response){
420                         callback(response);
421                 }
423                 ok( jQuery.isFunction(fn), "Recursive Function Call" );
425                 fn({ some: "data" });
426         };
428         callme(function(){
429                 callme(function(){});
430         });
433 test("isXMLDoc - HTML", function() {
434         expect(4);
436         ok( !jQuery.isXMLDoc( document ), "HTML document" );
437         ok( !jQuery.isXMLDoc( document.documentElement ), "HTML documentElement" );
438         ok( !jQuery.isXMLDoc( document.body ), "HTML Body Element" );
440         var iframe = document.createElement("iframe");
441         document.body.appendChild( iframe );
443         try {
444                 var body = jQuery(iframe).contents()[0];
446                 try {
447                         ok( !jQuery.isXMLDoc( body ), "Iframe body element" );
448                 } catch(e) {
449                         ok( false, "Iframe body element exception" );
450                 }
452         } catch(e) {
453                 ok( true, "Iframe body element - iframe not working correctly" );
454         }
456         document.body.removeChild( iframe );
459 if ( !isLocal ) {
460 test("isXMLDoc - XML", function() {
461         expect(3);
462         stop();
463         jQuery.get('data/dashboard.xml', function(xml) {
464                 ok( jQuery.isXMLDoc( xml ), "XML document" );
465                 ok( jQuery.isXMLDoc( xml.documentElement ), "XML documentElement" );
466                 ok( jQuery.isXMLDoc( jQuery("tab", xml)[0] ), "XML Tab Element" );
467                 start();
468         });
472 test("isWindow", function() {
473         expect( 12 );
475         ok( jQuery.isWindow(window), "window" );
476         ok( !jQuery.isWindow(), "empty" );
477         ok( !jQuery.isWindow(null), "null" );
478         ok( !jQuery.isWindow(undefined), "undefined" );
479         ok( !jQuery.isWindow(document), "document" );
480         ok( !jQuery.isWindow(document.documentElement), "documentElement" );
481         ok( !jQuery.isWindow(""), "string" );
482         ok( !jQuery.isWindow(1), "number" );
483         ok( !jQuery.isWindow(true), "boolean" );
484         ok( !jQuery.isWindow({}), "object" );
485         // HMMM
486         // ok( !jQuery.isWindow({ setInterval: function(){} }), "fake window" );
487         ok( !jQuery.isWindow(/window/), "regexp" );
488         ok( !jQuery.isWindow(function(){}), "function" );
491 test("jQuery('html')", function() {
492         expect(18);
494         QUnit.reset();
495         jQuery.foo = false;
496         var s = jQuery("<script>jQuery.foo='test';</script>")[0];
497         ok( s, "Creating a script" );
498         ok( !jQuery.foo, "Make sure the script wasn't executed prematurely" );
499         jQuery("body").append("<script>jQuery.foo='test';</script>");
500         ok( jQuery.foo, "Executing a scripts contents in the right context" );
502         // Test multi-line HTML
503         var div = jQuery("<div>\r\nsome text\n<p>some p</p>\nmore text\r\n</div>")[0];
504         equals( div.nodeName.toUpperCase(), "DIV", "Make sure we're getting a div." );
505         equals( div.firstChild.nodeType, 3, "Text node." );
506         equals( div.lastChild.nodeType, 3, "Text node." );
507         equals( div.childNodes[1].nodeType, 1, "Paragraph." );
508         equals( div.childNodes[1].firstChild.nodeType, 3, "Paragraph text." );
510         QUnit.reset();
511         ok( jQuery("<link rel='stylesheet'/>")[0], "Creating a link" );
513         ok( !jQuery("<script/>")[0].parentNode, "Create a script" );
515         ok( jQuery("<input/>").attr("type", "hidden"), "Create an input and set the type." );
517         var j = jQuery("<span>hi</span> there <!-- mon ami -->");
518         ok( j.length >= 2, "Check node,textnode,comment creation (some browsers delete comments)" );
520         ok( !jQuery("<option>test</option>")[0].selected, "Make sure that options are auto-selected #2050" );
522         ok( jQuery("<div></div>")[0], "Create a div with closing tag." );
523         ok( jQuery("<table></table>")[0], "Create a table with closing tag." );
525         // Test very large html string #7990
526         var i;
527         var li = '<li>very large html string</li>';
528         var html = ['<ul>'];
529         for ( i = 0; i < 50000; i += 1 ) {
530                 html.push(li);
531         }
532         html.push('</ul>');
533         html = jQuery(html.join(''))[0];
534         equals( html.nodeName.toUpperCase(), 'UL');
535         equals( html.firstChild.nodeName.toUpperCase(), 'LI');
536         equals( html.childNodes.length, 50000 );
539 test("jQuery('html', context)", function() {
540         expect(1);
542         var $div = jQuery("<div/>")[0];
543         var $span = jQuery("<span/>", $div);
544         equals($span.length, 1, "Verify a span created with a div context works, #1763");
547 if ( !isLocal ) {
548 test("jQuery(selector, xml).text(str) - Loaded via XML document", function() {
549         expect(2);
550         stop();
551         jQuery.get('data/dashboard.xml', function(xml) {
552                 // tests for #1419 where IE was a problem
553                 var tab = jQuery("tab", xml).eq(0);
554                 equals( tab.text(), "blabla", "Verify initial text correct" );
555                 tab.text("newtext");
556                 equals( tab.text(), "newtext", "Verify new text correct" );
557                 start();
558         });
562 test("end()", function() {
563         expect(3);
564         equals( 'Yahoo', jQuery('#yahoo').parent().end().text(), 'Check for end' );
565         ok( jQuery('#yahoo').end(), 'Check for end with nothing to end' );
567         var x = jQuery('#yahoo');
568         x.parent();
569         equals( 'Yahoo', jQuery('#yahoo').text(), 'Check for non-destructive behaviour' );
572 test("length", function() {
573         expect(1);
574         equals( jQuery("#main p").length, 6, "Get Number of Elements Found" );
577 test("size()", function() {
578         expect(1);
579         equals( jQuery("#main p").size(), 6, "Get Number of Elements Found" );
582 test("get()", function() {
583         expect(1);
584         same( jQuery("#main p").get(), q("firstp","ap","sndp","en","sap","first"), "Get All Elements" );
587 test("toArray()", function() {
588         expect(1);
589         same( jQuery("#main p").toArray(),
590                 q("firstp","ap","sndp","en","sap","first"),
591                 "Convert jQuery object to an Array" )
594 test("get(Number)", function() {
595         expect(2);
596         equals( jQuery("#main p").get(0), document.getElementById("firstp"), "Get A Single Element" );
597         strictEqual( jQuery("#firstp").get(1), undefined, "Try get with index larger elements count" );
600 test("get(-Number)",function() {
601         expect(2);
602         equals( jQuery("p").get(-1), document.getElementById("first"), "Get a single element with negative index" );
603         strictEqual( jQuery("#firstp").get(-2), undefined, "Try get with index negative index larger then elements count" );
606 test("each(Function)", function() {
607         expect(1);
608         var div = jQuery("div");
609         div.each(function(){this.foo = 'zoo';});
610         var pass = true;
611         for ( var i = 0; i < div.size(); i++ ) {
612                 if ( div.get(i).foo != "zoo" ) pass = false;
613         }
614         ok( pass, "Execute a function, Relative" );
617 test("slice()", function() {
618         expect(7);
620         var $links = jQuery("#ap a");
622         same( $links.slice(1,2).get(), q("groups"), "slice(1,2)" );
623         same( $links.slice(1).get(), q("groups", "anchor1", "mark"), "slice(1)" );
624         same( $links.slice(0,3).get(), q("google", "groups", "anchor1"), "slice(0,3)" );
625         same( $links.slice(-1).get(), q("mark"), "slice(-1)" );
627         same( $links.eq(1).get(), q("groups"), "eq(1)" );
628         same( $links.eq('2').get(), q("anchor1"), "eq('2')" );
629         same( $links.eq(-1).get(), q("mark"), "eq(-1)" );
632 test("first()/last()", function() {
633         expect(4);
635         var $links = jQuery("#ap a"), $none = jQuery("asdf");
637         same( $links.first().get(), q("google"), "first()" );
638         same( $links.last().get(), q("mark"), "last()" );
640         same( $none.first().get(), [], "first() none" );
641         same( $none.last().get(), [], "last() none" );
644 test("map()", function() {
645         expect(7);
647         same(
648                 jQuery("#ap").map(function(){
649                         return jQuery(this).find("a").get();
650                 }).get(),
651                 q("google", "groups", "anchor1", "mark"),
652                 "Array Map"
653         );
655         same(
656                 jQuery("#ap > a").map(function(){
657                         return this.parentNode;
658                 }).get(),
659                 q("ap","ap","ap"),
660                 "Single Map"
661         );
663         //for #2616
664         var keys = jQuery.map( {a:1,b:2}, function( v, k ){
665                 return k;
666         });
667         equals( keys.join(""), "ab", "Map the keys from a hash to an array" );
669         var values = jQuery.map( {a:1,b:2}, function( v, k ){
670                 return v;
671         });
672         equals( values.join(""), "12", "Map the values from a hash to an array" );
674         // object with length prop
675         var values = jQuery.map( {a:1,b:2, length:3}, function( v, k ){
676                 return v;
677         });
678         equals( values.join(""), "123", "Map the values from a hash with a length property to an array" );
680         var scripts = document.getElementsByTagName("script");
681         var mapped = jQuery.map( scripts, function( v, k ){
682                 return v;
683         });
684         equals( mapped.length, scripts.length, "Map an array(-like) to a hash" );
686         var flat = jQuery.map( Array(4), function( v, k ){
687                 return k % 2 ? k : [k,k,k];//try mixing array and regular returns
688         });
689         equals( flat.join(""), "00012223", "try the new flatten technique(#2616)" );
692 test("jQuery.merge()", function() {
693         expect(8);
695         var parse = jQuery.merge;
697         same( parse([],[]), [], "Empty arrays" );
699         same( parse([1],[2]), [1,2], "Basic" );
700         same( parse([1,2],[3,4]), [1,2,3,4], "Basic" );
702         same( parse([1,2],[]), [1,2], "Second empty" );
703         same( parse([],[1,2]), [1,2], "First empty" );
705         // Fixed at [5998], #3641
706         same( parse([-2,-1], [0,1,2]), [-2,-1,0,1,2], "Second array including a zero (falsy)");
708         // After fixing #5527
709         same( parse([], [null, undefined]), [null, undefined], "Second array including null and undefined values");
710         same( parse({length:0}, [1,2]), {length:2, 0:1, 1:2}, "First array like");
713 test("jQuery.extend(Object, Object)", function() {
714         expect(28);
716         var settings = { xnumber1: 5, xnumber2: 7, xstring1: "peter", xstring2: "pan" },
717                 options = { xnumber2: 1, xstring2: "x", xxx: "newstring" },
718                 optionsCopy = { xnumber2: 1, xstring2: "x", xxx: "newstring" },
719                 merged = { xnumber1: 5, xnumber2: 1, xstring1: "peter", xstring2: "x", xxx: "newstring" },
720                 deep1 = { foo: { bar: true } },
721                 deep1copy = { foo: { bar: true } },
722                 deep2 = { foo: { baz: true }, foo2: document },
723                 deep2copy = { foo: { baz: true }, foo2: document },
724                 deepmerged = { foo: { bar: true, baz: true }, foo2: document },
725                 arr = [1, 2, 3],
726                 nestedarray = { arr: arr };
728         jQuery.extend(settings, options);
729         same( settings, merged, "Check if extended: settings must be extended" );
730         same( options, optionsCopy, "Check if not modified: options must not be modified" );
732         jQuery.extend(settings, null, options);
733         same( settings, merged, "Check if extended: settings must be extended" );
734         same( options, optionsCopy, "Check if not modified: options must not be modified" );
736         jQuery.extend(true, deep1, deep2);
737         same( deep1.foo, deepmerged.foo, "Check if foo: settings must be extended" );
738         same( deep2.foo, deep2copy.foo, "Check if not deep2: options must not be modified" );
739         equals( deep1.foo2, document, "Make sure that a deep clone was not attempted on the document" );
741         ok( jQuery.extend(true, {}, nestedarray).arr !== arr, "Deep extend of object must clone child array" );
743         // #5991
744         ok( jQuery.isArray( jQuery.extend(true, { arr: {} }, nestedarray).arr ), "Cloned array heve to be an Array" );
745         ok( jQuery.isPlainObject( jQuery.extend(true, { arr: arr }, { arr: {} }).arr ), "Cloned object heve to be an plain object" );
747         var empty = {};
748         var optionsWithLength = { foo: { length: -1 } };
749         jQuery.extend(true, empty, optionsWithLength);
750         same( empty.foo, optionsWithLength.foo, "The length property must copy correctly" );
752         empty = {};
753         var optionsWithDate = { foo: { date: new Date } };
754         jQuery.extend(true, empty, optionsWithDate);
755         same( empty.foo, optionsWithDate.foo, "Dates copy correctly" );
757         var myKlass = function() {};
758         var customObject = new myKlass();
759         var optionsWithCustomObject = { foo: { date: customObject } };
760         empty = {};
761         jQuery.extend(true, empty, optionsWithCustomObject);
762         ok( empty.foo && empty.foo.date === customObject, "Custom objects copy correctly (no methods)" );
764         // Makes the class a little more realistic
765         myKlass.prototype = { someMethod: function(){} };
766         empty = {};
767         jQuery.extend(true, empty, optionsWithCustomObject);
768         ok( empty.foo && empty.foo.date === customObject, "Custom objects copy correctly" );
770         var ret = jQuery.extend(true, { foo: 4 }, { foo: new Number(5) } );
771         ok( ret.foo == 5, "Wrapped numbers copy correctly" );
773         var nullUndef;
774         nullUndef = jQuery.extend({}, options, { xnumber2: null });
775         ok( nullUndef.xnumber2 === null, "Check to make sure null values are copied");
777         nullUndef = jQuery.extend({}, options, { xnumber2: undefined });
778         ok( nullUndef.xnumber2 === options.xnumber2, "Check to make sure undefined values are not copied");
780         nullUndef = jQuery.extend({}, options, { xnumber0: null });
781         ok( nullUndef.xnumber0 === null, "Check to make sure null values are inserted");
783         var target = {};
784         var recursive = { foo:target, bar:5 };
785         jQuery.extend(true, target, recursive);
786         same( target, { bar:5 }, "Check to make sure a recursive obj doesn't go never-ending loop by not copying it over" );
788         var ret = jQuery.extend(true, { foo: [] }, { foo: [0] } ); // 1907
789         equals( ret.foo.length, 1, "Check to make sure a value with coersion 'false' copies over when necessary to fix #1907" );
791         var ret = jQuery.extend(true, { foo: "1,2,3" }, { foo: [1, 2, 3] } );
792         ok( typeof ret.foo != "string", "Check to make sure values equal with coersion (but not actually equal) overwrite correctly" );
794         var ret = jQuery.extend(true, { foo:"bar" }, { foo:null } );
795         ok( typeof ret.foo !== 'undefined', "Make sure a null value doesn't crash with deep extend, for #1908" );
797         var obj = { foo:null };
798         jQuery.extend(true, obj, { foo:"notnull" } );
799         equals( obj.foo, "notnull", "Make sure a null value can be overwritten" );
801         function func() {}
802         jQuery.extend(func, { key: "value" } );
803         equals( func.key, "value", "Verify a function can be extended" );
805         var defaults = { xnumber1: 5, xnumber2: 7, xstring1: "peter", xstring2: "pan" },
806                 defaultsCopy = { xnumber1: 5, xnumber2: 7, xstring1: "peter", xstring2: "pan" },
807                 options1 = { xnumber2: 1, xstring2: "x" },
808                 options1Copy = { xnumber2: 1, xstring2: "x" },
809                 options2 = { xstring2: "xx", xxx: "newstringx" },
810                 options2Copy = { xstring2: "xx", xxx: "newstringx" },
811                 merged2 = { xnumber1: 5, xnumber2: 1, xstring1: "peter", xstring2: "xx", xxx: "newstringx" };
813         var settings = jQuery.extend({}, defaults, options1, options2);
814         same( settings, merged2, "Check if extended: settings must be extended" );
815         same( defaults, defaultsCopy, "Check if not modified: options1 must not be modified" );
816         same( options1, options1Copy, "Check if not modified: options1 must not be modified" );
817         same( options2, options2Copy, "Check if not modified: options2 must not be modified" );
820 test("jQuery.each(Object,Function)", function() {
821         expect(13);
822         jQuery.each( [0,1,2], function(i, n){
823                 equals( i, n, "Check array iteration" );
824         });
826         jQuery.each( [5,6,7], function(i, n){
827                 equals( i, n - 5, "Check array iteration" );
828         });
830         jQuery.each( { name: "name", lang: "lang" }, function(i, n){
831                 equals( i, n, "Check object iteration" );
832         });
834         var total = 0;
835         jQuery.each([1,2,3], function(i,v){ total += v; });
836         equals( total, 6, "Looping over an array" );
837         total = 0;
838         jQuery.each([1,2,3], function(i,v){ total += v; if ( i == 1 ) return false; });
839         equals( total, 3, "Looping over an array, with break" );
840         total = 0;
841         jQuery.each({"a":1,"b":2,"c":3}, function(i,v){ total += v; });
842         equals( total, 6, "Looping over an object" );
843         total = 0;
844         jQuery.each({"a":3,"b":3,"c":3}, function(i,v){ total += v; return false; });
845         equals( total, 3, "Looping over an object, with break" );
847         var f = function(){};
848         f.foo = 'bar';
849         jQuery.each(f, function(i){
850                 f[i] = 'baz';
851         });
852         equals( "baz", f.foo, "Loop over a function" );
855 test("jQuery.makeArray", function(){
856         expect(17);
858         equals( jQuery.makeArray(jQuery('html>*'))[0].nodeName.toUpperCase(), "HEAD", "Pass makeArray a jQuery object" );
860         equals( jQuery.makeArray(document.getElementsByName("PWD")).slice(0,1)[0].name, "PWD", "Pass makeArray a nodelist" );
862         equals( (function(){ return jQuery.makeArray(arguments); })(1,2).join(""), "12", "Pass makeArray an arguments array" );
864         equals( jQuery.makeArray([1,2,3]).join(""), "123", "Pass makeArray a real array" );
866         equals( jQuery.makeArray().length, 0, "Pass nothing to makeArray and expect an empty array" );
868         equals( jQuery.makeArray( 0 )[0], 0 , "Pass makeArray a number" );
870         equals( jQuery.makeArray( "foo" )[0], "foo", "Pass makeArray a string" );
872         equals( jQuery.makeArray( true )[0].constructor, Boolean, "Pass makeArray a boolean" );
874         equals( jQuery.makeArray( document.createElement("div") )[0].nodeName.toUpperCase(), "DIV", "Pass makeArray a single node" );
876         equals( jQuery.makeArray( {length:2, 0:"a", 1:"b"} ).join(""), "ab", "Pass makeArray an array like map (with length)" );
878         ok( !!jQuery.makeArray( document.documentElement.childNodes ).slice(0,1)[0].nodeName, "Pass makeArray a childNodes array" );
880         // function, is tricky as it has length
881         equals( jQuery.makeArray( function(){ return 1;} )[0](), 1, "Pass makeArray a function" );
883         //window, also has length
884         equals( jQuery.makeArray(window)[0], window, "Pass makeArray the window" );
886         equals( jQuery.makeArray(/a/)[0].constructor, RegExp, "Pass makeArray a regex" );
888         ok( jQuery.makeArray(document.getElementById('form')).length >= 13, "Pass makeArray a form (treat as elements)" );
890         // For #5610
891         same( jQuery.makeArray({'length': '0'}), [], "Make sure object is coerced properly.");
892         same( jQuery.makeArray({'length': '5'}), [], "Make sure object is coerced properly.");
895 test("jQuery.isEmptyObject", function(){
896         expect(2);
898         equals(true, jQuery.isEmptyObject({}), "isEmptyObject on empty object literal" );
899         equals(false, jQuery.isEmptyObject({a:1}), "isEmptyObject on non-empty object literal" );
901         // What about this ?
902         // equals(true, jQuery.isEmptyObject(null), "isEmptyObject on null" );
905 test("jQuery.proxy", function(){
906         expect(4);
908         var test = function(){ equals( this, thisObject, "Make sure that scope is set properly." ); };
909         var thisObject = { foo: "bar", method: test };
911         // Make sure normal works
912         test.call( thisObject );
914         // Basic scoping
915         jQuery.proxy( test, thisObject )();
917         // Make sure it doesn't freak out
918         equals( jQuery.proxy( null, thisObject ), undefined, "Make sure no function was returned." );
920         // Use the string shortcut
921         jQuery.proxy( thisObject, "method" )();
924 test("jQuery.parseJSON", function(){
925         expect(8);
927         equals( jQuery.parseJSON(), null, "Nothing in, null out." );
928         equals( jQuery.parseJSON( null ), null, "Nothing in, null out." );
929         equals( jQuery.parseJSON( "" ), null, "Nothing in, null out." );
931         same( jQuery.parseJSON("{}"), {}, "Plain object parsing." );
932         same( jQuery.parseJSON('{"test":1}'), {"test":1}, "Plain object parsing." );
934         same( jQuery.parseJSON('\n{"test":1}'), {"test":1}, "Make sure leading whitespaces are handled." );
936         try {
937                 jQuery.parseJSON("{a:1}");
938                 ok( false, "Test malformed JSON string." );
939         } catch( e ) {
940                 ok( true, "Test malformed JSON string." );
941         }
943         try {
944                 jQuery.parseJSON("{'a':1}");
945                 ok( false, "Test malformed JSON string." );
946         } catch( e ) {
947                 ok( true, "Test malformed JSON string." );
948         }
951 test("jQuery.sub() - Static Methods", function(){
952     expect(18);
953     var Subclass = jQuery.sub();
954     Subclass.extend({
955         topLevelMethod: function() {return this.debug;},
956         debug: false,
957         config: {
958             locale: 'en_US'
959         },
960         setup: function(config) {
961             this.extend(true, this.config, config);
962         }
963     });
964     Subclass.fn.extend({subClassMethod: function() { return this;}});
966     //Test Simple Subclass
967     ok(Subclass.topLevelMethod() === false, 'Subclass.topLevelMethod thought debug was true');
968     ok(Subclass.config.locale == 'en_US', Subclass.config.locale + ' is wrong!');
969     same(Subclass.config.test, undefined, 'Subclass.config.test is set incorrectly');
970     equal(jQuery.ajax, Subclass.ajax, 'The subclass failed to get all top level methods');
972     //Create a SubSubclass
973     var SubSubclass = Subclass.sub();
975     //Make Sure the SubSubclass inherited properly
976     ok(SubSubclass.topLevelMethod() === false, 'SubSubclass.topLevelMethod thought debug was true');
977     ok(SubSubclass.config.locale == 'en_US', SubSubclass.config.locale + ' is wrong!');
978     same(SubSubclass.config.test, undefined, 'SubSubclass.config.test is set incorrectly');
979     equal(jQuery.ajax, SubSubclass.ajax, 'The subsubclass failed to get all top level methods');
981     //Modify The Subclass and test the Modifications
982     SubSubclass.fn.extend({subSubClassMethod: function() { return this;}});
983     SubSubclass.setup({locale: 'es_MX', test: 'worked'});
984     SubSubclass.debug = true;
985     SubSubclass.ajax = function() {return false;};
986     ok(SubSubclass.topLevelMethod(), 'SubSubclass.topLevelMethod thought debug was false');
987     same(SubSubclass(document).subClassMethod, Subclass.fn.subClassMethod, 'Methods Differ!');
988     ok(SubSubclass.config.locale == 'es_MX', SubSubclass.config.locale + ' is wrong!');
989     ok(SubSubclass.config.test == 'worked', 'SubSubclass.config.test is set incorrectly');
990     notEqual(jQuery.ajax, SubSubclass.ajax, 'The subsubclass failed to get all top level methods');
992     //This shows that the modifications to the SubSubClass did not bubble back up to it's superclass
993     ok(Subclass.topLevelMethod() === false, 'Subclass.topLevelMethod thought debug was true');
994     ok(Subclass.config.locale == 'en_US', Subclass.config.locale + ' is wrong!');
995     same(Subclass.config.test, undefined, 'Subclass.config.test is set incorrectly');
996     same(Subclass(document).subSubClassMethod, undefined, 'subSubClassMethod set incorrectly');
997     equal(jQuery.ajax, Subclass.ajax, 'The subclass failed to get all top level methods');
1000 test("jQuery.sub() - .fn Methods", function(){
1001         expect(378);
1003         var Subclass = jQuery.sub(),
1004                         SubclassSubclass = Subclass.sub(),
1005                         jQueryDocument = jQuery(document),
1006                         selectors, contexts, methods, method, arg, description;
1008         jQueryDocument.toString = function(){ return 'jQueryDocument'; };
1010         Subclass.fn.subclassMethod = function(){};
1011         SubclassSubclass.fn.subclassSubclassMethod = function(){};
1013         selectors = [
1014                 'body',
1015                 'html, body',
1016                 '<div></div>'
1017         ];
1019         methods = [ // all methods that return a new jQuery instance
1020                 ['eq', 1],
1021                 ['add', document],
1022                 ['end'],
1023                 ['has'],
1024                 ['closest', 'div'],
1025                 ['filter', document],
1026                 ['find', 'div']
1027         ];
1029         contexts = [undefined, document, jQueryDocument];
1031         jQuery.each(selectors, function(i, selector){
1033                 jQuery.each(methods, function(){
1034                         method = this[0];
1035                         arg = this[1];
1037                         jQuery.each(contexts, function(i, context){
1039                                 description = '("'+selector+'", '+context+').'+method+'('+(arg||'')+')';
1041                                 same(
1042                                         jQuery(selector, context)[method](arg).subclassMethod, undefined,
1043                                         'jQuery'+description+' doesnt have Subclass methods'
1044                                 );
1045                                 same(
1046                                         jQuery(selector, context)[method](arg).subclassSubclassMethod, undefined,
1047                                         'jQuery'+description+' doesnt have SubclassSubclass methods'
1048                                 );
1049                                 same(
1050                                         Subclass(selector, context)[method](arg).subclassMethod, Subclass.fn.subclassMethod,
1051                                         'Subclass'+description+' has Subclass methods'
1052                                 );
1053                                 same(
1054                                         Subclass(selector, context)[method](arg).subclassSubclassMethod, undefined,
1055                                         'Subclass'+description+' doesnt have SubclassSubclass methods'
1056                                 );
1057                                 same(
1058                                         SubclassSubclass(selector, context)[method](arg).subclassMethod, Subclass.fn.subclassMethod,
1059                                         'SubclassSubclass'+description+' has Subclass methods'
1060                                 );
1061                                 same(
1062                                         SubclassSubclass(selector, context)[method](arg).subclassSubclassMethod, SubclassSubclass.fn.subclassSubclassMethod,
1063                                         'SubclassSubclass'+description+' has SubclassSubclass methods'
1064                                 );
1066                         });
1067                 });
1068         });