Made jQuery.type more consistent with host objects.
[jquery.git] / test / unit / core.js
1 module("core");
2
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 });
13
14 test("jQuery()", function() {
15         expect(23);
16
17         // Basic constructor's behavior
18
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
24         var obj = jQuery("div")
25         equals( jQuery(obj).selector, "div", "jQuery(jQueryObj) == jQueryObj" );
26
27                 // can actually yield more than one, when iframes are included, the window is an array as well
28         equals( jQuery(window).length, 1, "Correct number of elements generated for jQuery(window)" );
29
30
31         var main = jQuery("#main");
32         same( jQuery("div p", main).get(), q("sndp", "en", "sap"), "Basic selector with jQuery object as context" );
33
34 /*
35         // disabled since this test was doing nothing. i tried to fix it but i'm not sure
36         // what the expected behavior should even be. FF returns "\n" for the text node
37         // make sure this is handled
38         var crlfContainer = jQuery('<p>\r\n</p>');
39         var x = crlfContainer.contents().get(0).nodeValue;
40         equals( x, what???, "Check for \\r and \\n in jQuery()" );
41 */
42
43         /* // Disabled until we add this functionality in
44         var pass = true;
45         try {
46                 jQuery("<div>Testing</div>").appendTo(document.getElementById("iframe").contentDocument.body);
47         } catch(e){
48                 pass = false;
49         }
50         ok( pass, "jQuery('&lt;tag&gt;') needs optional document parameter to ease cross-frame DOM wrangling, see #968" );*/
51
52         var code = jQuery("<code/>");
53         equals( code.length, 1, "Correct number of elements generated for code" );
54         equals( code.parent().length, 0, "Make sure that the generated HTML has no parent." );
55         var img = jQuery("<img/>");
56         equals( img.length, 1, "Correct number of elements generated for img" );
57         equals( img.parent().length, 0, "Make sure that the generated HTML has no parent." );
58         var div = jQuery("<div/><hr/><code/><b/>");
59         equals( div.length, 4, "Correct number of elements generated for div hr code b" );
60         equals( div.parent().length, 0, "Make sure that the generated HTML has no parent." );
61
62         equals( jQuery([1,2,3]).get(1), 2, "Test passing an array to the factory" );
63
64         equals( jQuery(document.body).get(0), jQuery('body').get(0), "Test passing an html node to the factory" );
65
66         var exec = false;
67
68         var elem = jQuery("<div/>", {
69                 width: 10,
70                 css: { paddingLeft:1, paddingRight:1 },
71                 click: function(){ ok(exec, "Click executed."); },
72                 text: "test",
73                 "class": "test2",
74                 id: "test3"
75         });
76
77         equals( elem[0].style.width, '10px', 'jQuery() quick setter width');
78         equals( elem[0].style.paddingLeft, '1px', 'jQuery quick setter css');
79         equals( elem[0].style.paddingRight, '1px', 'jQuery quick setter css');
80         equals( elem[0].childNodes.length, 1, 'jQuery quick setter text');
81         equals( elem[0].firstChild.nodeValue, "test", 'jQuery quick setter text');
82         equals( elem[0].className, "test2", 'jQuery() quick setter class');
83         equals( elem[0].id, "test3", 'jQuery() quick setter id');
84
85         exec = true;
86         elem.click();
87 });
88
89 test("selector state", function() {
90         expect(31);
91
92         var test;
93
94         test = jQuery(undefined);
95         equals( test.selector, "", "Empty jQuery Selector" );
96         equals( test.context, undefined, "Empty jQuery Context" );
97
98         test = jQuery(document);
99         equals( test.selector, "", "Document Selector" );
100         equals( test.context, document, "Document Context" );
101
102         test = jQuery(document.body);
103         equals( test.selector, "", "Body Selector" );
104         equals( test.context, document.body, "Body Context" );
105
106         test = jQuery("#main");
107         equals( test.selector, "#main", "#main Selector" );
108         equals( test.context, document, "#main Context" );
109
110         test = jQuery("#notfoundnono");
111         equals( test.selector, "#notfoundnono", "#notfoundnono Selector" );
112         equals( test.context, document, "#notfoundnono Context" );
113
114         test = jQuery("#main", document);
115         equals( test.selector, "#main", "#main Selector" );
116         equals( test.context, document, "#main Context" );
117
118         test = jQuery("#main", document.body);
119         equals( test.selector, "#main", "#main Selector" );
120         equals( test.context, document.body, "#main Context" );
121
122         // Test cloning
123         test = jQuery(test);
124         equals( test.selector, "#main", "#main Selector" );
125         equals( test.context, document.body, "#main Context" );
126
127         test = jQuery(document.body).find("#main");
128         equals( test.selector, "#main", "#main find Selector" );
129         equals( test.context, document.body, "#main find Context" );
130
131         test = jQuery("#main").filter("div");
132         equals( test.selector, "#main.filter(div)", "#main filter Selector" );
133         equals( test.context, document, "#main filter Context" );
134
135         test = jQuery("#main").not("div");
136         equals( test.selector, "#main.not(div)", "#main not Selector" );
137         equals( test.context, document, "#main not Context" );
138
139         test = jQuery("#main").filter("div").not("div");
140         equals( test.selector, "#main.filter(div).not(div)", "#main filter, not Selector" );
141         equals( test.context, document, "#main filter, not Context" );
142
143         test = jQuery("#main").filter("div").not("div").end();
144         equals( test.selector, "#main.filter(div)", "#main filter, not, end Selector" );
145         equals( test.context, document, "#main filter, not, end Context" );
146
147         test = jQuery("#main").parent("body");
148         equals( test.selector, "#main.parent(body)", "#main parent Selector" );
149         equals( test.context, document, "#main parent Context" );
150
151         test = jQuery("#main").eq(0);
152         equals( test.selector, "#main.slice(0,1)", "#main eq Selector" );
153         equals( test.context, document, "#main eq Context" );
154         
155         var d = "<div />";
156         equals(
157                 jQuery(d).appendTo(jQuery(d)).selector,
158                 jQuery(d).appendTo(d).selector,
159                 "manipulation methods make same selector for jQuery objects"
160         );
161 });
162
163 if ( !isLocal ) {
164 test("browser", function() {
165         stop();
166
167         jQuery.get("data/ua.txt", function(data){
168                 var uas = data.split("\n");
169                 expect( (uas.length - 1) * 2 );
170
171                 jQuery.each(uas, function(){
172                         var parts = this.split("\t");
173                         if ( parts[2] ) {
174                                 var ua = jQuery.uaMatch( parts[2] );
175                                 equals( ua.browser, parts[0], "Checking browser for " + parts[2] );
176                                 equals( ua.version, parts[1], "Checking version string for " + parts[2] );
177                         }
178                 });
179
180                 start();
181         });
182 });
183 }
184
185 test("noConflict", function() {
186         expect(7);
187
188         var $$ = jQuery;
189
190         equals( jQuery, jQuery.noConflict(), "noConflict returned the jQuery object" );
191         equals( jQuery, $$, "Make sure jQuery wasn't touched." );
192         equals( $, original$, "Make sure $ was reverted." );
193
194         jQuery = $ = $$;
195
196         equals( jQuery.noConflict(true), $$, "noConflict returned the jQuery object" );
197         equals( jQuery, originaljQuery, "Make sure jQuery was reverted." );
198         equals( $, original$, "Make sure $ was reverted." );
199         ok( $$("#main").html("test"), "Make sure that jQuery still works." );
200
201         jQuery = $$;
202 });
203
204 test("trim", function() {
205         expect(9);
206
207         var nbsp = String.fromCharCode(160);
208
209         equals( jQuery.trim("hello  "), "hello", "trailing space" );
210         equals( jQuery.trim("  hello"), "hello", "leading space" );
211         equals( jQuery.trim("  hello   "), "hello", "space on both sides" );
212         equals( jQuery.trim("  " + nbsp + "hello  " + nbsp + " "), "hello", "&nbsp;" );
213
214         equals( jQuery.trim(), "", "Nothing in." );
215         equals( jQuery.trim( undefined ), "", "Undefined" );
216         equals( jQuery.trim( null ), "", "Null" );
217         equals( jQuery.trim( 5 ), "5", "Number" );
218         equals( jQuery.trim( false ), "false", "Boolean" );
219 });
220
221 test("type", function() {
222         expect(22);
223
224         equals( jQuery.type(null), "null", "null" );
225         equals( jQuery.type(undefined), "undefined", "undefined" );
226         equals( jQuery.type(true), "boolean", "Boolean" );
227         equals( jQuery.type(false), "boolean", "Boolean" );
228         equals( jQuery.type(Boolean(true)), "boolean", "Boolean" );
229         equals( jQuery.type(0), "number", "Number" );
230         equals( jQuery.type(1), "number", "Number" );
231         equals( jQuery.type(Number(1)), "number", "Number" );
232         equals( jQuery.type(""), "string", "String" );
233         equals( jQuery.type("a"), "string", "String" );
234         equals( jQuery.type(String("a")), "string", "String" );
235         equals( jQuery.type({}), "object", "Object" );
236         equals( jQuery.type(/foo/), "regexp", "RegExp" );
237         equals( jQuery.type(new RegExp("asdf")), "regexp", "RegExp" );
238         equals( jQuery.type([1]), "array", "Array" );
239         equals( jQuery.type(new Date()), "date", "Date" );
240         equals( jQuery.type(new Function("return;")), "function", "Function" );
241         equals( jQuery.type(function(){}), "function", "Function" );
242         equals( jQuery.type(window), "object", "Window" );
243         equals( jQuery.type(document.body), "object", "Element" );
244         equals( jQuery.type(document.createTextNode("foo")), "object", "TextNode" );
245         equals( jQuery.type(document.getElementsByTagName("*")), "object", "NodeList" );
246 });
247
248 test("isPlainObject", function() {
249         expect(14);
250
251         stop();
252
253         // The use case that we want to match
254         ok(jQuery.isPlainObject({}), "{}");
255         
256         // Not objects shouldn't be matched
257         ok(!jQuery.isPlainObject(""), "string");
258         ok(!jQuery.isPlainObject(0) && !jQuery.isPlainObject(1), "number");
259         ok(!jQuery.isPlainObject(true) && !jQuery.isPlainObject(false), "boolean");
260         ok(!jQuery.isPlainObject(null), "null");
261         ok(!jQuery.isPlainObject(undefined), "undefined");
262         
263         // Arrays shouldn't be matched
264         ok(!jQuery.isPlainObject([]), "array");
265  
266         // Instantiated objects shouldn't be matched
267         ok(!jQuery.isPlainObject(new Date), "new Date");
268  
269         var fn = function(){};
270  
271         // Functions shouldn't be matched
272         ok(!jQuery.isPlainObject(fn), "fn");
273  
274         // Again, instantiated objects shouldn't be matched
275         ok(!jQuery.isPlainObject(new fn), "new fn (no methods)");
276  
277         // Makes the function a little more realistic
278         // (and harder to detect, incidentally)
279         fn.prototype = {someMethod: function(){}};
280  
281         // Again, instantiated objects shouldn't be matched
282         ok(!jQuery.isPlainObject(new fn), "new fn");
283
284         // DOM Element
285         ok(!jQuery.isPlainObject(document.createElement("div")), "DOM Element");
286         
287         // Window
288         ok(!jQuery.isPlainObject(window), "window");
289
290         try {
291                 var iframe = document.createElement("iframe");
292                 document.body.appendChild(iframe);
293
294                 window.iframeDone = function(otherObject){
295                         // Objects from other windows should be matched
296                         ok(jQuery.isPlainObject(new otherObject), "new otherObject");
297                         document.body.removeChild( iframe );
298                         start();
299                 };
300  
301                 var doc = iframe.contentDocument || iframe.contentWindow.document;
302                 doc.open();
303                 doc.write("<body onload='window.parent.iframeDone(Object);'>");
304                 doc.close();
305         } catch(e) {
306                 document.body.removeChild( iframe );
307
308                 ok(true, "new otherObject - iframes not supported");
309                 start();
310         }
311 });
312
313 test("isFunction", function() {
314         expect(19);
315
316         // Make sure that false values return false
317         ok( !jQuery.isFunction(), "No Value" );
318         ok( !jQuery.isFunction( null ), "null Value" );
319         ok( !jQuery.isFunction( undefined ), "undefined Value" );
320         ok( !jQuery.isFunction( "" ), "Empty String Value" );
321         ok( !jQuery.isFunction( 0 ), "0 Value" );
322
323         // Check built-ins
324         // Safari uses "(Internal Function)"
325         ok( jQuery.isFunction(String), "String Function("+String+")" );
326         ok( jQuery.isFunction(Array), "Array Function("+Array+")" );
327         ok( jQuery.isFunction(Object), "Object Function("+Object+")" );
328         ok( jQuery.isFunction(Function), "Function Function("+Function+")" );
329
330         // When stringified, this could be misinterpreted
331         var mystr = "function";
332         ok( !jQuery.isFunction(mystr), "Function String" );
333
334         // When stringified, this could be misinterpreted
335         var myarr = [ "function" ];
336         ok( !jQuery.isFunction(myarr), "Function Array" );
337
338         // When stringified, this could be misinterpreted
339         var myfunction = { "function": "test" };
340         ok( !jQuery.isFunction(myfunction), "Function Object" );
341
342         // Make sure normal functions still work
343         var fn = function(){};
344         ok( jQuery.isFunction(fn), "Normal Function" );
345
346         var obj = document.createElement("object");
347
348         // Firefox says this is a function
349         ok( !jQuery.isFunction(obj), "Object Element" );
350
351         // IE says this is an object
352         // Since 1.3, this isn't supported (#2968)
353         //ok( jQuery.isFunction(obj.getAttribute), "getAttribute Function" );
354
355         var nodes = document.body.childNodes;
356
357         // Safari says this is a function
358         ok( !jQuery.isFunction(nodes), "childNodes Property" );
359
360         var first = document.body.firstChild;
361
362         // Normal elements are reported ok everywhere
363         ok( !jQuery.isFunction(first), "A normal DOM Element" );
364
365         var input = document.createElement("input");
366         input.type = "text";
367         document.body.appendChild( input );
368
369         // IE says this is an object
370         // Since 1.3, this isn't supported (#2968)
371         //ok( jQuery.isFunction(input.focus), "A default function property" );
372
373         document.body.removeChild( input );
374
375         var a = document.createElement("a");
376         a.href = "some-function";
377         document.body.appendChild( a );
378
379         // This serializes with the word 'function' in it
380         ok( !jQuery.isFunction(a), "Anchor Element" );
381
382         document.body.removeChild( a );
383
384         // Recursive function calls have lengths and array-like properties
385         function callme(callback){
386                 function fn(response){
387                         callback(response);
388                 }
389
390                 ok( jQuery.isFunction(fn), "Recursive Function Call" );
391
392                 fn({ some: "data" });
393         };
394
395         callme(function(){
396                 callme(function(){});
397         });
398 });
399
400 test("isXMLDoc - HTML", function() {
401         expect(4);
402
403         ok( !jQuery.isXMLDoc( document ), "HTML document" );
404         ok( !jQuery.isXMLDoc( document.documentElement ), "HTML documentElement" );
405         ok( !jQuery.isXMLDoc( document.body ), "HTML Body Element" );
406
407         var iframe = document.createElement("iframe");
408         document.body.appendChild( iframe );
409
410         try {
411                 var body = jQuery(iframe).contents()[0];
412
413                 try {
414                         ok( !jQuery.isXMLDoc( body ), "Iframe body element" );
415                 } catch(e) {
416                         ok( false, "Iframe body element exception" );
417                 }
418
419         } catch(e) {
420                 ok( true, "Iframe body element - iframe not working correctly" );
421         }
422
423         document.body.removeChild( iframe );
424 });
425
426 if ( !isLocal ) {
427 test("isXMLDoc - XML", function() {
428         expect(3);
429         stop();
430         jQuery.get('data/dashboard.xml', function(xml) {
431                 ok( jQuery.isXMLDoc( xml ), "XML document" );
432                 ok( jQuery.isXMLDoc( xml.documentElement ), "XML documentElement" );
433                 ok( jQuery.isXMLDoc( jQuery("tab", xml)[0] ), "XML Tab Element" );
434                 start();
435         });
436 });
437 }
438
439 test("isWindow", function() {
440         expect( 12 );
441
442         ok( jQuery.isWindow(window), "window" );
443         ok( !jQuery.isWindow(), "empty" );
444         ok( !jQuery.isWindow(null), "null" );
445         ok( !jQuery.isWindow(undefined), "undefined" );
446         ok( !jQuery.isWindow(document), "document" );
447         ok( !jQuery.isWindow(document.documentElement), "documentElement" );
448         ok( !jQuery.isWindow(""), "string" );
449         ok( !jQuery.isWindow(1), "number" );
450         ok( !jQuery.isWindow(true), "boolean" );
451         ok( !jQuery.isWindow({}), "object" );
452         // HMMM
453         // ok( !jQuery.isWindow({ setInterval: function(){} }), "fake window" );
454         ok( !jQuery.isWindow(/window/), "regexp" );
455         ok( !jQuery.isWindow(function(){}), "function" );
456 });
457
458 test("jQuery('html')", function() {
459         expect(15);
460
461         QUnit.reset();
462         jQuery.foo = false;
463         var s = jQuery("<script>jQuery.foo='test';</script>")[0];
464         ok( s, "Creating a script" );
465         ok( !jQuery.foo, "Make sure the script wasn't executed prematurely" );
466         jQuery("body").append("<script>jQuery.foo='test';</script>");
467         ok( jQuery.foo, "Executing a scripts contents in the right context" );
468
469         // Test multi-line HTML
470         var div = jQuery("<div>\r\nsome text\n<p>some p</p>\nmore text\r\n</div>")[0];
471         equals( div.nodeName.toUpperCase(), "DIV", "Make sure we're getting a div." );
472         equals( div.firstChild.nodeType, 3, "Text node." );
473         equals( div.lastChild.nodeType, 3, "Text node." );
474         equals( div.childNodes[1].nodeType, 1, "Paragraph." );
475         equals( div.childNodes[1].firstChild.nodeType, 3, "Paragraph text." );
476
477         QUnit.reset();
478         ok( jQuery("<link rel='stylesheet'/>")[0], "Creating a link" );
479
480         ok( !jQuery("<script/>")[0].parentNode, "Create a script" );
481
482         ok( jQuery("<input/>").attr("type", "hidden"), "Create an input and set the type." );
483
484         var j = jQuery("<span>hi</span> there <!-- mon ami -->");
485         ok( j.length >= 2, "Check node,textnode,comment creation (some browsers delete comments)" );
486
487         ok( !jQuery("<option>test</option>")[0].selected, "Make sure that options are auto-selected #2050" );
488
489         ok( jQuery("<div></div>")[0], "Create a div with closing tag." );
490         ok( jQuery("<table></table>")[0], "Create a table with closing tag." );
491 });
492
493 test("jQuery('html', context)", function() {
494         expect(1);
495
496         var $div = jQuery("<div/>")[0];
497         var $span = jQuery("<span/>", $div);
498         equals($span.length, 1, "Verify a span created with a div context works, #1763");
499 });
500
501 if ( !isLocal ) {
502 test("jQuery(selector, xml).text(str) - Loaded via XML document", function() {
503         expect(2);
504         stop();
505         jQuery.get('data/dashboard.xml', function(xml) {
506                 // tests for #1419 where IE was a problem
507                 var tab = jQuery("tab", xml).eq(0);
508                 equals( tab.text(), "blabla", "Verify initial text correct" );
509                 tab.text("newtext");
510                 equals( tab.text(), "newtext", "Verify new text correct" );
511                 start();
512         });
513 });
514 }
515
516 test("end()", function() {
517         expect(3);
518         equals( 'Yahoo', jQuery('#yahoo').parent().end().text(), 'Check for end' );
519         ok( jQuery('#yahoo').end(), 'Check for end with nothing to end' );
520
521         var x = jQuery('#yahoo');
522         x.parent();
523         equals( 'Yahoo', jQuery('#yahoo').text(), 'Check for non-destructive behaviour' );
524 });
525
526 test("length", function() {
527         expect(1);
528         equals( jQuery("p").length, 6, "Get Number of Elements Found" );
529 });
530
531 test("size()", function() {
532         expect(1);
533         equals( jQuery("p").size(), 6, "Get Number of Elements Found" );
534 });
535
536 test("get()", function() {
537         expect(1);
538         same( jQuery("p").get(), q("firstp","ap","sndp","en","sap","first"), "Get All Elements" );
539 });
540
541 test("toArray()", function() {
542         expect(1);
543         same( jQuery("p").toArray(),
544                 q("firstp","ap","sndp","en","sap","first"),
545                 "Convert jQuery object to an Array" )
546 })
547
548 test("get(Number)", function() {
549         expect(1);
550         equals( jQuery("p").get(0), document.getElementById("firstp"), "Get A Single Element" );
551 });
552
553 test("get(-Number)",function() {
554         expect(1);
555         equals( jQuery("p").get(-1),
556                 document.getElementById("first"),
557                 "Get a single element with negative index" )
558 })
559
560 test("each(Function)", function() {
561         expect(1);
562         var div = jQuery("div");
563         div.each(function(){this.foo = 'zoo';});
564         var pass = true;
565         for ( var i = 0; i < div.size(); i++ ) {
566                 if ( div.get(i).foo != "zoo" ) pass = false;
567         }
568         ok( pass, "Execute a function, Relative" );
569 });
570
571 test("slice()", function() {
572         expect(7);
573
574         var $links = jQuery("#ap a");
575
576         same( $links.slice(1,2).get(), q("groups"), "slice(1,2)" );
577         same( $links.slice(1).get(), q("groups", "anchor1", "mark"), "slice(1)" );
578         same( $links.slice(0,3).get(), q("google", "groups", "anchor1"), "slice(0,3)" );
579         same( $links.slice(-1).get(), q("mark"), "slice(-1)" );
580
581         same( $links.eq(1).get(), q("groups"), "eq(1)" );
582         same( $links.eq('2').get(), q("anchor1"), "eq('2')" );
583         same( $links.eq(-1).get(), q("mark"), "eq(-1)" );
584 });
585
586 test("first()/last()", function() {
587         expect(4);
588
589         var $links = jQuery("#ap a"), $none = jQuery("asdf");
590
591         same( $links.first().get(), q("google"), "first()" );
592         same( $links.last().get(), q("mark"), "last()" );
593
594         same( $none.first().get(), [], "first() none" );
595         same( $none.last().get(), [], "last() none" );
596 });
597
598 test("map()", function() {
599         expect(2);//expect(6);
600
601         same(
602                 jQuery("#ap").map(function(){
603                         return jQuery(this).find("a").get();
604                 }).get(),
605                 q("google", "groups", "anchor1", "mark"),
606                 "Array Map"
607         );
608
609         same(
610                 jQuery("#ap > a").map(function(){
611                         return this.parentNode;
612                 }).get(),
613                 q("ap","ap","ap"),
614                 "Single Map"
615         );
616
617         return;//these haven't been accepted yet
618
619         //for #2616
620         var keys = jQuery.map( {a:1,b:2}, function( v, k ){
621                 return k;
622         }, [ ] );
623
624         equals( keys.join(""), "ab", "Map the keys from a hash to an array" );
625
626         var values = jQuery.map( {a:1,b:2}, function( v, k ){
627                 return v;
628         }, [ ] );
629
630         equals( values.join(""), "12", "Map the values from a hash to an array" );
631
632         var scripts = document.getElementsByTagName("script");
633         var mapped = jQuery.map( scripts, function( v, k ){
634                 return v;
635         }, {length:0} );
636
637         equals( mapped.length, scripts.length, "Map an array(-like) to a hash" );
638
639         var flat = jQuery.map( Array(4), function( v, k ){
640                 return k % 2 ? k : [k,k,k];//try mixing array and regular returns
641         });
642
643         equals( flat.join(""), "00012223", "try the new flatten technique(#2616)" );
644 });
645
646 test("jQuery.merge()", function() {
647         expect(8);
648
649         var parse = jQuery.merge;
650
651         same( parse([],[]), [], "Empty arrays" );
652
653         same( parse([1],[2]), [1,2], "Basic" );
654         same( parse([1,2],[3,4]), [1,2,3,4], "Basic" );
655
656         same( parse([1,2],[]), [1,2], "Second empty" );
657         same( parse([],[1,2]), [1,2], "First empty" );
658
659         // Fixed at [5998], #3641
660         same( parse([-2,-1], [0,1,2]), [-2,-1,0,1,2], "Second array including a zero (falsy)");
661         
662         // After fixing #5527
663         same( parse([], [null, undefined]), [null, undefined], "Second array including null and undefined values");
664         same( parse({length:0}, [1,2]), {length:2, 0:1, 1:2}, "First array like");
665 });
666
667 test("jQuery.extend(Object, Object)", function() {
668         expect(28);
669
670         var settings = { xnumber1: 5, xnumber2: 7, xstring1: "peter", xstring2: "pan" },
671                 options = { xnumber2: 1, xstring2: "x", xxx: "newstring" },
672                 optionsCopy = { xnumber2: 1, xstring2: "x", xxx: "newstring" },
673                 merged = { xnumber1: 5, xnumber2: 1, xstring1: "peter", xstring2: "x", xxx: "newstring" },
674                 deep1 = { foo: { bar: true } },
675                 deep1copy = { foo: { bar: true } },
676                 deep2 = { foo: { baz: true }, foo2: document },
677                 deep2copy = { foo: { baz: true }, foo2: document },
678                 deepmerged = { foo: { bar: true, baz: true }, foo2: document },
679                 arr = [1, 2, 3],
680                 nestedarray = { arr: arr };
681
682         jQuery.extend(settings, options);
683         same( settings, merged, "Check if extended: settings must be extended" );
684         same( options, optionsCopy, "Check if not modified: options must not be modified" );
685
686         jQuery.extend(settings, null, options);
687         same( settings, merged, "Check if extended: settings must be extended" );
688         same( options, optionsCopy, "Check if not modified: options must not be modified" );
689
690         jQuery.extend(true, deep1, deep2);
691         same( deep1.foo, deepmerged.foo, "Check if foo: settings must be extended" );
692         same( deep2.foo, deep2copy.foo, "Check if not deep2: options must not be modified" );
693         equals( deep1.foo2, document, "Make sure that a deep clone was not attempted on the document" );
694
695         ok( jQuery.extend(true, {}, nestedarray).arr !== arr, "Deep extend of object must clone child array" );
696         
697         // #5991
698         ok( jQuery.isArray( jQuery.extend(true, { arr: {} }, nestedarray).arr ), "Cloned array heve to be an Array" );
699         ok( jQuery.isPlainObject( jQuery.extend(true, { arr: arr }, { arr: {} }).arr ), "Cloned object heve to be an plain object" );
700
701         var empty = {};
702         var optionsWithLength = { foo: { length: -1 } };
703         jQuery.extend(true, empty, optionsWithLength);
704         same( empty.foo, optionsWithLength.foo, "The length property must copy correctly" );
705
706         empty = {};
707         var optionsWithDate = { foo: { date: new Date } };
708         jQuery.extend(true, empty, optionsWithDate);
709         same( empty.foo, optionsWithDate.foo, "Dates copy correctly" );
710
711         var myKlass = function() {};
712         var customObject = new myKlass();
713         var optionsWithCustomObject = { foo: { date: customObject } };
714         empty = {};
715         jQuery.extend(true, empty, optionsWithCustomObject);
716         ok( empty.foo && empty.foo.date === customObject, "Custom objects copy correctly (no methods)" );
717         
718         // Makes the class a little more realistic
719         myKlass.prototype = { someMethod: function(){} };
720         empty = {};
721         jQuery.extend(true, empty, optionsWithCustomObject);
722         ok( empty.foo && empty.foo.date === customObject, "Custom objects copy correctly" );
723         
724         var ret = jQuery.extend(true, { foo: 4 }, { foo: new Number(5) } );
725         ok( ret.foo == 5, "Wrapped numbers copy correctly" );
726
727         var nullUndef;
728         nullUndef = jQuery.extend({}, options, { xnumber2: null });
729         ok( nullUndef.xnumber2 === null, "Check to make sure null values are copied");
730
731         nullUndef = jQuery.extend({}, options, { xnumber2: undefined });
732         ok( nullUndef.xnumber2 === options.xnumber2, "Check to make sure undefined values are not copied");
733
734         nullUndef = jQuery.extend({}, options, { xnumber0: null });
735         ok( nullUndef.xnumber0 === null, "Check to make sure null values are inserted");
736
737         var target = {};
738         var recursive = { foo:target, bar:5 };
739         jQuery.extend(true, target, recursive);
740         same( target, { bar:5 }, "Check to make sure a recursive obj doesn't go never-ending loop by not copying it over" );
741
742         var ret = jQuery.extend(true, { foo: [] }, { foo: [0] } ); // 1907
743         equals( ret.foo.length, 1, "Check to make sure a value with coersion 'false' copies over when necessary to fix #1907" );
744
745         var ret = jQuery.extend(true, { foo: "1,2,3" }, { foo: [1, 2, 3] } );
746         ok( typeof ret.foo != "string", "Check to make sure values equal with coersion (but not actually equal) overwrite correctly" );
747
748         var ret = jQuery.extend(true, { foo:"bar" }, { foo:null } );
749         ok( typeof ret.foo !== 'undefined', "Make sure a null value doesn't crash with deep extend, for #1908" );
750
751         var obj = { foo:null };
752         jQuery.extend(true, obj, { foo:"notnull" } );
753         equals( obj.foo, "notnull", "Make sure a null value can be overwritten" );
754
755         function func() {}
756         jQuery.extend(func, { key: "value" } );
757         equals( func.key, "value", "Verify a function can be extended" );
758
759         var defaults = { xnumber1: 5, xnumber2: 7, xstring1: "peter", xstring2: "pan" },
760                 defaultsCopy = { xnumber1: 5, xnumber2: 7, xstring1: "peter", xstring2: "pan" },
761                 options1 = { xnumber2: 1, xstring2: "x" },
762                 options1Copy = { xnumber2: 1, xstring2: "x" },
763                 options2 = { xstring2: "xx", xxx: "newstringx" },
764                 options2Copy = { xstring2: "xx", xxx: "newstringx" },
765                 merged2 = { xnumber1: 5, xnumber2: 1, xstring1: "peter", xstring2: "xx", xxx: "newstringx" };
766
767         var settings = jQuery.extend({}, defaults, options1, options2);
768         same( settings, merged2, "Check if extended: settings must be extended" );
769         same( defaults, defaultsCopy, "Check if not modified: options1 must not be modified" );
770         same( options1, options1Copy, "Check if not modified: options1 must not be modified" );
771         same( options2, options2Copy, "Check if not modified: options2 must not be modified" );
772 });
773
774 test("jQuery.each(Object,Function)", function() {
775         expect(13);
776         jQuery.each( [0,1,2], function(i, n){
777                 equals( i, n, "Check array iteration" );
778         });
779
780         jQuery.each( [5,6,7], function(i, n){
781                 equals( i, n - 5, "Check array iteration" );
782         });
783
784         jQuery.each( { name: "name", lang: "lang" }, function(i, n){
785                 equals( i, n, "Check object iteration" );
786         });
787
788         var total = 0;
789         jQuery.each([1,2,3], function(i,v){ total += v; });
790         equals( total, 6, "Looping over an array" );
791         total = 0;
792         jQuery.each([1,2,3], function(i,v){ total += v; if ( i == 1 ) return false; });
793         equals( total, 3, "Looping over an array, with break" );
794         total = 0;
795         jQuery.each({"a":1,"b":2,"c":3}, function(i,v){ total += v; });
796         equals( total, 6, "Looping over an object" );
797         total = 0;
798         jQuery.each({"a":3,"b":3,"c":3}, function(i,v){ total += v; return false; });
799         equals( total, 3, "Looping over an object, with break" );
800
801         var f = function(){};
802         f.foo = 'bar';
803         jQuery.each(f, function(i){
804                 f[i] = 'baz';
805         });
806         equals( "baz", f.foo, "Loop over a function" );
807 });
808
809 test("jQuery.makeArray", function(){
810         expect(17);
811
812         equals( jQuery.makeArray(jQuery('html>*'))[0].nodeName.toUpperCase(), "HEAD", "Pass makeArray a jQuery object" );
813
814         equals( jQuery.makeArray(document.getElementsByName("PWD")).slice(0,1)[0].name, "PWD", "Pass makeArray a nodelist" );
815
816         equals( (function(){ return jQuery.makeArray(arguments); })(1,2).join(""), "12", "Pass makeArray an arguments array" );
817
818         equals( jQuery.makeArray([1,2,3]).join(""), "123", "Pass makeArray a real array" );
819
820         equals( jQuery.makeArray().length, 0, "Pass nothing to makeArray and expect an empty array" );
821
822         equals( jQuery.makeArray( 0 )[0], 0 , "Pass makeArray a number" );
823
824         equals( jQuery.makeArray( "foo" )[0], "foo", "Pass makeArray a string" );
825
826         equals( jQuery.makeArray( true )[0].constructor, Boolean, "Pass makeArray a boolean" );
827
828         equals( jQuery.makeArray( document.createElement("div") )[0].nodeName.toUpperCase(), "DIV", "Pass makeArray a single node" );
829
830         equals( jQuery.makeArray( {length:2, 0:"a", 1:"b"} ).join(""), "ab", "Pass makeArray an array like map (with length)" );
831
832         ok( !!jQuery.makeArray( document.documentElement.childNodes ).slice(0,1)[0].nodeName, "Pass makeArray a childNodes array" );
833
834         // function, is tricky as it has length
835         equals( jQuery.makeArray( function(){ return 1;} )[0](), 1, "Pass makeArray a function" );
836
837         //window, also has length
838         equals( jQuery.makeArray(window)[0], window, "Pass makeArray the window" );
839
840         equals( jQuery.makeArray(/a/)[0].constructor, RegExp, "Pass makeArray a regex" );
841
842         ok( jQuery.makeArray(document.getElementById('form')).length >= 13, "Pass makeArray a form (treat as elements)" );
843
844         // For #5610
845         same( jQuery.makeArray({'length': '0'}), [], "Make sure object is coerced properly.");
846         same( jQuery.makeArray({'length': '5'}), [], "Make sure object is coerced properly.");
847 });
848
849 test("jQuery.isEmptyObject", function(){
850         expect(2);
851         
852         equals(true, jQuery.isEmptyObject({}), "isEmptyObject on empty object literal" );
853         equals(false, jQuery.isEmptyObject({a:1}), "isEmptyObject on non-empty object literal" );
854         
855         // What about this ?
856         // equals(true, jQuery.isEmptyObject(null), "isEmptyObject on null" );
857 });
858
859 test("jQuery.proxy", function(){
860         expect(4);
861
862         var test = function(){ equals( this, thisObject, "Make sure that scope is set properly." ); };
863         var thisObject = { foo: "bar", method: test };
864
865         // Make sure normal works
866         test.call( thisObject );
867
868         // Basic scoping
869         jQuery.proxy( test, thisObject )();
870
871         // Make sure it doesn't freak out
872         equals( jQuery.proxy( null, thisObject ), undefined, "Make sure no function was returned." );
873
874         // Use the string shortcut
875         jQuery.proxy( thisObject, "method" )();
876 });
877
878 test("jQuery.parseJSON", function(){
879         expect(8);
880         
881         equals( jQuery.parseJSON(), null, "Nothing in, null out." );
882         equals( jQuery.parseJSON( null ), null, "Nothing in, null out." );
883         equals( jQuery.parseJSON( "" ), null, "Nothing in, null out." );
884         
885         same( jQuery.parseJSON("{}"), {}, "Plain object parsing." );
886         same( jQuery.parseJSON('{"test":1}'), {"test":1}, "Plain object parsing." );
887
888         same( jQuery.parseJSON('\n{"test":1}'), {"test":1}, "Make sure leading whitespaces are handled." );
889         
890         try {
891                 jQuery.parseJSON("{a:1}");
892                 ok( false, "Test malformed JSON string." );
893         } catch( e ) {
894                 ok( true, "Test malformed JSON string." );
895         }
896         
897         try {
898                 jQuery.parseJSON("{'a':1}");
899                 ok( false, "Test malformed JSON string." );
900         } catch( e ) {
901                 ok( true, "Test malformed JSON string." );
902         }
903 });