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