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