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