3 test("Basic requirements", function() {
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" );
14 test("jQuery()", function() {
17 // Basic constructor's behavior
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([])" );
24 var obj = jQuery("div");
25 equals( jQuery(obj).selector, "div", "jQuery(jQueryObj) == jQueryObj" );
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)" );
31 var main = jQuery("#main");
32 same( jQuery("div p", main).get(), q("sndp", "en", "sap"), "Basic selector with jQuery object as context" );
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()" );
43 /* // Disabled until we add this functionality in
46 jQuery("<div>Testing</div>").appendTo(document.getElementById("iframe").contentDocument.body);
50 ok( pass, "jQuery('<tag>') needs optional document parameter to ease cross-frame DOM wrangling, see #968" );*/
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." );
62 equals( jQuery([1,2,3]).get(1), 2, "Test passing an array to the factory" );
64 equals( jQuery(document.body).get(0), jQuery('body').get(0), "Test passing an html node to the factory" );
68 var elem = jQuery("<div/>", {
70 css: { paddingLeft:1, paddingRight:1 },
71 click: function(){ ok(exec, "Click executed."); },
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');
88 for ( var i = 0; i < 3; ++i ) {
89 elem = jQuery("<input type='text' value='TEST' />");
91 equals( elem[0].defaultValue, "TEST", "Ensure cached nodes are cloned properly (Bug #6655)" );
94 test("selector state", function() {
99 test = jQuery(undefined);
100 equals( test.selector, "", "Empty jQuery Selector" );
101 equals( test.context, undefined, "Empty jQuery Context" );
103 test = jQuery(document);
104 equals( test.selector, "", "Document Selector" );
105 equals( test.context, document, "Document Context" );
107 test = jQuery(document.body);
108 equals( test.selector, "", "Body Selector" );
109 equals( test.context, document.body, "Body Context" );
111 test = jQuery("#main");
112 equals( test.selector, "#main", "#main Selector" );
113 equals( test.context, document, "#main Context" );
115 test = jQuery("#notfoundnono");
116 equals( test.selector, "#notfoundnono", "#notfoundnono Selector" );
117 equals( test.context, document, "#notfoundnono Context" );
119 test = jQuery("#main", document);
120 equals( test.selector, "#main", "#main Selector" );
121 equals( test.context, document, "#main Context" );
123 test = jQuery("#main", document.body);
124 equals( test.selector, "#main", "#main Selector" );
125 equals( test.context, document.body, "#main Context" );
129 equals( test.selector, "#main", "#main Selector" );
130 equals( test.context, document.body, "#main Context" );
132 test = jQuery(document.body).find("#main");
133 equals( test.selector, "#main", "#main find Selector" );
134 equals( test.context, document.body, "#main find Context" );
136 test = jQuery("#main").filter("div");
137 equals( test.selector, "#main.filter(div)", "#main filter Selector" );
138 equals( test.context, document, "#main filter Context" );
140 test = jQuery("#main").not("div");
141 equals( test.selector, "#main.not(div)", "#main not Selector" );
142 equals( test.context, document, "#main not Context" );
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" );
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" );
152 test = jQuery("#main").parent("body");
153 equals( test.selector, "#main.parent(body)", "#main parent Selector" );
154 equals( test.context, document, "#main parent Context" );
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" );
162 jQuery(d).appendTo(jQuery(d)).selector,
163 jQuery(d).appendTo(d).selector,
164 "manipulation methods make same selector for jQuery objects"
169 test("browser", function() {
172 jQuery.get("data/ua.txt", function(data){
173 var uas = data.split("\n");
174 expect( (uas.length - 1) * 2 );
176 jQuery.each(uas, function(){
177 var parts = this.split("\t");
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] );
190 test("noConflict", function() {
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." );
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." );
209 test("trim", function() {
212 var nbsp = String.fromCharCode(160);
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", " " );
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" );
226 test("type", function() {
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" );
254 test("isPlainObject", function() {
259 // The use case that we want to match
260 ok(jQuery.isPlainObject({}), "{}");
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");
269 // Arrays shouldn't be matched
270 ok(!jQuery.isPlainObject([]), "array");
272 // Instantiated objects shouldn't be matched
273 ok(!jQuery.isPlainObject(new Date), "new Date");
275 var fn = function(){};
277 // Functions shouldn't be matched
278 ok(!jQuery.isPlainObject(fn), "fn");
280 // Again, instantiated objects shouldn't be matched
281 ok(!jQuery.isPlainObject(new fn), "new fn (no methods)");
283 // Makes the function a little more realistic
284 // (and harder to detect, incidentally)
285 fn.prototype = {someMethod: function(){}};
287 // Again, instantiated objects shouldn't be matched
288 ok(!jQuery.isPlainObject(new fn), "new fn");
291 ok(!jQuery.isPlainObject(document.createElement("div")), "DOM Element");
294 ok(!jQuery.isPlainObject(window), "window");
297 var iframe = document.createElement("iframe");
298 document.body.appendChild(iframe);
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 );
307 var doc = iframe.contentDocument || iframe.contentWindow.document;
309 doc.write("<body onload='window.parent.iframeDone(Object);'>");
312 document.body.removeChild( iframe );
314 ok(true, "new otherObject - iframes not supported");
319 test("isFunction", function() {
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" );
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+")" );
336 // When stringified, this could be misinterpreted
337 var mystr = "function";
338 ok( !jQuery.isFunction(mystr), "Function String" );
340 // When stringified, this could be misinterpreted
341 var myarr = [ "function" ];
342 ok( !jQuery.isFunction(myarr), "Function Array" );
344 // When stringified, this could be misinterpreted
345 var myfunction = { "function": "test" };
346 ok( !jQuery.isFunction(myfunction), "Function Object" );
348 // Make sure normal functions still work
349 var fn = function(){};
350 ok( jQuery.isFunction(fn), "Normal Function" );
352 var obj = document.createElement("object");
354 // Firefox says this is a function
355 ok( !jQuery.isFunction(obj), "Object Element" );
357 // IE says this is an object
358 // Since 1.3, this isn't supported (#2968)
359 //ok( jQuery.isFunction(obj.getAttribute), "getAttribute Function" );
361 var nodes = document.body.childNodes;
363 // Safari says this is a function
364 ok( !jQuery.isFunction(nodes), "childNodes Property" );
366 var first = document.body.firstChild;
368 // Normal elements are reported ok everywhere
369 ok( !jQuery.isFunction(first), "A normal DOM Element" );
371 var input = document.createElement("input");
373 document.body.appendChild( input );
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" );
379 document.body.removeChild( input );
381 var a = document.createElement("a");
382 a.href = "some-function";
383 document.body.appendChild( a );
385 // This serializes with the word 'function' in it
386 ok( !jQuery.isFunction(a), "Anchor Element" );
388 document.body.removeChild( a );
390 // Recursive function calls have lengths and array-like properties
391 function callme(callback){
392 function fn(response){
396 ok( jQuery.isFunction(fn), "Recursive Function Call" );
398 fn({ some: "data" });
402 callme(function(){});
406 test("isXMLDoc - HTML", function() {
409 ok( !jQuery.isXMLDoc( document ), "HTML document" );
410 ok( !jQuery.isXMLDoc( document.documentElement ), "HTML documentElement" );
411 ok( !jQuery.isXMLDoc( document.body ), "HTML Body Element" );
413 var iframe = document.createElement("iframe");
414 document.body.appendChild( iframe );
417 var body = jQuery(iframe).contents()[0];
420 ok( !jQuery.isXMLDoc( body ), "Iframe body element" );
422 ok( false, "Iframe body element exception" );
426 ok( true, "Iframe body element - iframe not working correctly" );
429 document.body.removeChild( iframe );
433 test("isXMLDoc - XML", function() {
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" );
445 test("isWindow", function() {
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" );
459 // ok( !jQuery.isWindow({ setInterval: function(){} }), "fake window" );
460 ok( !jQuery.isWindow(/window/), "regexp" );
461 ok( !jQuery.isWindow(function(){}), "function" );
464 test("jQuery('html')", function() {
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" );
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." );
484 ok( jQuery("<link rel='stylesheet'/>")[0], "Creating a link" );
486 ok( !jQuery("<script/>")[0].parentNode, "Create a script" );
488 ok( jQuery("<input/>").attr("type", "hidden"), "Create an input and set the type." );
490 var j = jQuery("<span>hi</span> there <!-- mon ami -->");
491 ok( j.length >= 2, "Check node,textnode,comment creation (some browsers delete comments)" );
493 ok( !jQuery("<option>test</option>")[0].selected, "Make sure that options are auto-selected #2050" );
495 ok( jQuery("<div></div>")[0], "Create a div with closing tag." );
496 ok( jQuery("<table></table>")[0], "Create a table with closing tag." );
499 test("jQuery('html', context)", function() {
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");
508 test("jQuery(selector, xml).text(str) - Loaded via XML document", function() {
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" );
516 equals( tab.text(), "newtext", "Verify new text correct" );
522 test("end()", function() {
524 equals( 'Yahoo', jQuery('#yahoo').parent().end().text(), 'Check for end' );
525 ok( jQuery('#yahoo').end(), 'Check for end with nothing to end' );
527 var x = jQuery('#yahoo');
529 equals( 'Yahoo', jQuery('#yahoo').text(), 'Check for non-destructive behaviour' );
532 test("length", function() {
534 equals( jQuery("p").length, 6, "Get Number of Elements Found" );
537 test("size()", function() {
539 equals( jQuery("p").size(), 6, "Get Number of Elements Found" );
542 test("get()", function() {
544 same( jQuery("p").get(), q("firstp","ap","sndp","en","sap","first"), "Get All Elements" );
547 test("toArray()", function() {
549 same( jQuery("p").toArray(),
550 q("firstp","ap","sndp","en","sap","first"),
551 "Convert jQuery object to an Array" )
554 test("get(Number)", function() {
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" );
560 test("get(-Number)",function() {
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" );
566 test("each(Function)", function() {
568 var div = jQuery("div");
569 div.each(function(){this.foo = 'zoo';});
571 for ( var i = 0; i < div.size(); i++ ) {
572 if ( div.get(i).foo != "zoo" ) pass = false;
574 ok( pass, "Execute a function, Relative" );
577 test("slice()", function() {
580 var $links = jQuery("#ap a");
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)" );
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)" );
592 test("first()/last()", function() {
595 var $links = jQuery("#ap a"), $none = jQuery("asdf");
597 same( $links.first().get(), q("google"), "first()" );
598 same( $links.last().get(), q("mark"), "last()" );
600 same( $none.first().get(), [], "first() none" );
601 same( $none.last().get(), [], "last() none" );
604 test("map()", function() {
605 expect(2);//expect(6);
608 jQuery("#ap").map(function(){
609 return jQuery(this).find("a").get();
611 q("google", "groups", "anchor1", "mark"),
616 jQuery("#ap > a").map(function(){
617 return this.parentNode;
623 return;//these haven't been accepted yet
626 var keys = jQuery.map( {a:1,b:2}, function( v, k ){
630 equals( keys.join(""), "ab", "Map the keys from a hash to an array" );
632 var values = jQuery.map( {a:1,b:2}, function( v, k ){
636 equals( values.join(""), "12", "Map the values from a hash to an array" );
638 var scripts = document.getElementsByTagName("script");
639 var mapped = jQuery.map( scripts, function( v, k ){
643 equals( mapped.length, scripts.length, "Map an array(-like) to a hash" );
645 var flat = jQuery.map( Array(4), function( v, k ){
646 return k % 2 ? k : [k,k,k];//try mixing array and regular returns
649 equals( flat.join(""), "00012223", "try the new flatten technique(#2616)" );
652 test("jQuery.merge()", function() {
655 var parse = jQuery.merge;
657 same( parse([],[]), [], "Empty arrays" );
659 same( parse([1],[2]), [1,2], "Basic" );
660 same( parse([1,2],[3,4]), [1,2,3,4], "Basic" );
662 same( parse([1,2],[]), [1,2], "Second empty" );
663 same( parse([],[1,2]), [1,2], "First empty" );
665 // Fixed at [5998], #3641
666 same( parse([-2,-1], [0,1,2]), [-2,-1,0,1,2], "Second array including a zero (falsy)");
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");
673 test("jQuery.extend(Object, Object)", function() {
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 },
686 nestedarray = { arr: arr };
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" );
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" );
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" );
701 ok( jQuery.extend(true, {}, nestedarray).arr !== arr, "Deep extend of object must clone child array" );
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" );
708 var optionsWithLength = { foo: { length: -1 } };
709 jQuery.extend(true, empty, optionsWithLength);
710 same( empty.foo, optionsWithLength.foo, "The length property must copy correctly" );
713 var optionsWithDate = { foo: { date: new Date } };
714 jQuery.extend(true, empty, optionsWithDate);
715 same( empty.foo, optionsWithDate.foo, "Dates copy correctly" );
717 var myKlass = function() {};
718 var customObject = new myKlass();
719 var optionsWithCustomObject = { foo: { date: customObject } };
721 jQuery.extend(true, empty, optionsWithCustomObject);
722 ok( empty.foo && empty.foo.date === customObject, "Custom objects copy correctly (no methods)" );
724 // Makes the class a little more realistic
725 myKlass.prototype = { someMethod: function(){} };
727 jQuery.extend(true, empty, optionsWithCustomObject);
728 ok( empty.foo && empty.foo.date === customObject, "Custom objects copy correctly" );
730 var ret = jQuery.extend(true, { foo: 4 }, { foo: new Number(5) } );
731 ok( ret.foo == 5, "Wrapped numbers copy correctly" );
734 nullUndef = jQuery.extend({}, options, { xnumber2: null });
735 ok( nullUndef.xnumber2 === null, "Check to make sure null values are copied");
737 nullUndef = jQuery.extend({}, options, { xnumber2: undefined });
738 ok( nullUndef.xnumber2 === options.xnumber2, "Check to make sure undefined values are not copied");
740 nullUndef = jQuery.extend({}, options, { xnumber0: null });
741 ok( nullUndef.xnumber0 === null, "Check to make sure null values are inserted");
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" );
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" );
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" );
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" );
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" );
762 jQuery.extend(func, { key: "value" } );
763 equals( func.key, "value", "Verify a function can be extended" );
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" };
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" );
780 test("jQuery.each(Object,Function)", function() {
782 jQuery.each( [0,1,2], function(i, n){
783 equals( i, n, "Check array iteration" );
786 jQuery.each( [5,6,7], function(i, n){
787 equals( i, n - 5, "Check array iteration" );
790 jQuery.each( { name: "name", lang: "lang" }, function(i, n){
791 equals( i, n, "Check object iteration" );
795 jQuery.each([1,2,3], function(i,v){ total += v; });
796 equals( total, 6, "Looping over an array" );
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" );
801 jQuery.each({"a":1,"b":2,"c":3}, function(i,v){ total += v; });
802 equals( total, 6, "Looping over an object" );
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" );
807 var f = function(){};
809 jQuery.each(f, function(i){
812 equals( "baz", f.foo, "Loop over a function" );
815 test("jQuery.makeArray", function(){
818 equals( jQuery.makeArray(jQuery('html>*'))[0].nodeName.toUpperCase(), "HEAD", "Pass makeArray a jQuery object" );
820 equals( jQuery.makeArray(document.getElementsByName("PWD")).slice(0,1)[0].name, "PWD", "Pass makeArray a nodelist" );
822 equals( (function(){ return jQuery.makeArray(arguments); })(1,2).join(""), "12", "Pass makeArray an arguments array" );
824 equals( jQuery.makeArray([1,2,3]).join(""), "123", "Pass makeArray a real array" );
826 equals( jQuery.makeArray().length, 0, "Pass nothing to makeArray and expect an empty array" );
828 equals( jQuery.makeArray( 0 )[0], 0 , "Pass makeArray a number" );
830 equals( jQuery.makeArray( "foo" )[0], "foo", "Pass makeArray a string" );
832 equals( jQuery.makeArray( true )[0].constructor, Boolean, "Pass makeArray a boolean" );
834 equals( jQuery.makeArray( document.createElement("div") )[0].nodeName.toUpperCase(), "DIV", "Pass makeArray a single node" );
836 equals( jQuery.makeArray( {length:2, 0:"a", 1:"b"} ).join(""), "ab", "Pass makeArray an array like map (with length)" );
838 ok( !!jQuery.makeArray( document.documentElement.childNodes ).slice(0,1)[0].nodeName, "Pass makeArray a childNodes array" );
840 // function, is tricky as it has length
841 equals( jQuery.makeArray( function(){ return 1;} )[0](), 1, "Pass makeArray a function" );
843 //window, also has length
844 equals( jQuery.makeArray(window)[0], window, "Pass makeArray the window" );
846 equals( jQuery.makeArray(/a/)[0].constructor, RegExp, "Pass makeArray a regex" );
848 ok( jQuery.makeArray(document.getElementById('form')).length >= 13, "Pass makeArray a form (treat as elements)" );
851 same( jQuery.makeArray({'length': '0'}), [], "Make sure object is coerced properly.");
852 same( jQuery.makeArray({'length': '5'}), [], "Make sure object is coerced properly.");
855 test("jQuery.isEmptyObject", function(){
858 equals(true, jQuery.isEmptyObject({}), "isEmptyObject on empty object literal" );
859 equals(false, jQuery.isEmptyObject({a:1}), "isEmptyObject on non-empty object literal" );
862 // equals(true, jQuery.isEmptyObject(null), "isEmptyObject on null" );
865 test("jQuery.proxy", function(){
868 var test = function(){ equals( this, thisObject, "Make sure that scope is set properly." ); };
869 var thisObject = { foo: "bar", method: test };
871 // Make sure normal works
872 test.call( thisObject );
875 jQuery.proxy( test, thisObject )();
877 // Make sure it doesn't freak out
878 equals( jQuery.proxy( null, thisObject ), undefined, "Make sure no function was returned." );
880 // Use the string shortcut
881 jQuery.proxy( thisObject, "method" )();
884 test("jQuery.parseJSON", function(){
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." );
891 same( jQuery.parseJSON("{}"), {}, "Plain object parsing." );
892 same( jQuery.parseJSON('{"test":1}'), {"test":1}, "Plain object parsing." );
894 same( jQuery.parseJSON('\n{"test":1}'), {"test":1}, "Make sure leading whitespaces are handled." );
897 jQuery.parseJSON("{a:1}");
898 ok( false, "Test malformed JSON string." );
900 ok( true, "Test malformed JSON string." );
904 jQuery.parseJSON("{'a':1}");
905 ok( false, "Test malformed JSON string." );
907 ok( true, "Test malformed JSON string." );
911 test("jQuery._Deferred()", function() {
919 deferred = jQuery._Deferred();
923 deferred.done( function( value ) {
924 equals( value , "value" , "Test pre-resolve callback" );
928 deferred.resolve( "value" );
930 ok( test , "Test pre-resolve callbacks called right away" );
934 deferred.done( function( value ) {
935 equals( value , "value" , "Test post-resolve callback" );
939 ok( test , "Test post-resolve callbacks called right away" );
945 deferred.done( function() {
946 ok( false , "Cancel was ignored" );
950 ok( test , "Test cancel" );
952 deferred = jQuery._Deferred().resolve();
955 deferred.done( function() {
958 ok( true , "Test deferred do not cancel on exception" );
961 strictEqual( e , "Error" , "Test deferred propagates exceptions");
966 deferred = jQuery._Deferred().done( function() {
976 strictEqual( test , "AB" , "Test multiple done parameters" );
980 deferred.done( function() {
982 deferred.done( function() {
995 strictEqual( test , "ABC" , "Test done callbacks order" );
997 deferred = jQuery._Deferred();
999 deferred.fire( jQuery , [ document ] ).done( function( doc ) {
1000 ok( this === jQuery && arguments.length === 1 && doc === document , "Test fire context & args" );
1004 test("jQuery.Deferred()", function() {
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" );
1015 jQuery.Deferred().resolve().then( function() {
1016 ok( true , "Success on resolve" );
1018 ok( false , "Error on resolve" );
1021 jQuery.Deferred().reject().then( function() {
1022 ok( false , "Success on reject" );
1024 ok( true , "Error on reject" );
1027 ( new jQuery.Deferred( function( defer ) {
1028 strictEqual( this , defer , "Defer passed as this & first argument (new)" );
1029 this.resolve( "done" );
1030 }) ).then( function( value ) {
1031 strictEqual( value , "done" , "Passed function executed (new)" );
1034 ( new jQuery.Deferred() ).resolve().then( function() {
1035 ok( true , "Success on resolve (new)" );
1037 ok( false , "Error on resolve (new)" );
1040 ( new jQuery.Deferred() ).reject().then( function() {
1041 ok( false , "Success on reject (new)" );
1043 ok( true , "Error on reject (new)" );
1046 var tmp = jQuery.Deferred();
1048 strictEqual( tmp.promise() , tmp.promise() , "Test deferred always return same promise" );
1049 strictEqual( tmp.promise() , tmp.promise().promise() , "Test deferred's promise always return same promise as deferred" );
1052 test("jQuery.when()", function() {
1056 // Some other objects
1059 "an empty string": "",
1060 "a non-empty string": "some string",
1062 "a number other than zero": 1,
1066 "undefined": undefined,
1067 "a plain object": {}
1069 } , function( message , value ) {
1071 ok( jQuery.isFunction( jQuery.when( value ).then( function( resolveValue ) {
1072 strictEqual( resolveValue , value , "Test the promise was resolved with " + message );
1073 } ).promise ) , "Test " + message + " triggers the creation of a new Promise" );
1077 ok( jQuery.isFunction( jQuery.when().then( function( resolveValue ) {
1078 strictEqual( resolveValue , undefined , "Test the promise was resolved with no parameter" );
1079 } ).promise ) , "Test calling when with no parameter triggers the creation of a new Promise" );
1083 for( i = 1 ; i < 4 ; i++ ) {
1084 jQuery.when( cache || jQuery.Deferred( function() {
1086 }) ).then( function( value ) {
1087 strictEqual( value , 1 , "Function executed" + ( i > 1 ? " only once" : "" ) );
1090 ok( false , "Fail called" );
1095 test("jQuery.when() - joined", function() {
1099 jQuery.when( 1, 2, 3 ).done( function( a, b, c ) {
1100 strictEqual( a , 1 , "Test first param is first resolved value - non-observables" );
1101 strictEqual( b , 2 , "Test second param is second resolved value - non-observables" );
1102 strictEqual( c , 3 , "Test third param is third resolved value - non-observables" );
1103 }).fail( function() {
1104 ok( false , "Test the created deferred was resolved - non-observables");
1107 var successDeferred = jQuery.Deferred().resolve( 1 , 2 , 3 ),
1108 errorDeferred = jQuery.Deferred().reject( "error" , "errorParam" );
1110 jQuery.when( 1 , successDeferred , 3 ).done( function( a, b, c ) {
1111 strictEqual( a , 1 , "Test first param is first resolved value - resolved observable" );
1112 same( b , [ 1 , 2 , 3 ] , "Test second param is second resolved value - resolved observable" );
1113 strictEqual( c , 3 , "Test third param is third resolved value - resolved observable" );
1114 }).fail( function() {
1115 ok( false , "Test the created deferred was resolved - resolved observable");
1118 jQuery.when( 1 , errorDeferred , 3 ).done( function() {
1119 ok( false , "Test the created deferred was rejected - rejected observable");
1120 }).fail( function( error , errorParam ) {
1121 strictEqual( error , "error" , "Test first param is first rejected value - rejected observable" );
1122 strictEqual( errorParam , "errorParam" , "Test second param is second rejected value - rejected observable" );
1126 test("jQuery.subclass", function(){
1129 var Subclass = jQuery.subclass(),
1130 SubclassSubclass = Subclass.subclass(),
1131 jQueryDocument = jQuery(document),
1132 selectors, contexts, methods, method, arg, description;
1134 jQueryDocument.toString = function(){ return 'jQueryDocument'; };
1136 Subclass.fn.subclassMethod = function(){};
1137 SubclassSubclass.fn.subclassSubclassMethod = function(){};
1145 methods = [ // all methods that return a new jQuery instance
1151 ['filter', document],
1155 contexts = [undefined, document, jQueryDocument];
1157 jQuery.each(selectors, function(i, selector){
1159 jQuery.each(methods, function(){
1163 jQuery.each(contexts, function(i, context){
1165 description = '("'+selector+'", '+context+').'+method+'('+(arg||'')+')';
1168 jQuery(selector, context)[method](arg).subclassMethod, undefined,
1169 'jQuery'+description+' doesnt have Subclass methods'
1172 jQuery(selector, context)[method](arg).subclassSubclassMethod, undefined,
1173 'jQuery'+description+' doesnt have SubclassSubclass methods'
1176 Subclass(selector, context)[method](arg).subclassMethod, Subclass.fn.subclassMethod,
1177 'Subclass'+description+' has Subclass methods'
1180 Subclass(selector, context)[method](arg).subclassSubclassMethod, undefined,
1181 'Subclass'+description+' doesnt have SubclassSubclass methods'
1184 SubclassSubclass(selector, context)[method](arg).subclassMethod, Subclass.fn.subclassMethod,
1185 'SubclassSubclass'+description+' has Subclass methods'
1188 SubclassSubclass(selector, context)[method](arg).subclassSubclassMethod, SubclassSubclass.fn.subclassSubclassMethod,
1189 'SubclassSubclass'+description+' has SubclassSubclass methods'