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