1 module("core", { teardown: moduleTeardown });
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 // manually clean up detached elements
91 for ( var i = 0; i < 3; ++i ) {
92 elem = jQuery("<input type='text' value='TEST' />");
94 equals( elem[0].defaultValue, "TEST", "Ensure cached nodes are cloned properly (Bug #6655)" );
96 // manually clean up detached elements
100 test("selector state", function() {
105 test = jQuery(undefined);
106 equals( test.selector, "", "Empty jQuery Selector" );
107 equals( test.context, undefined, "Empty jQuery Context" );
109 test = jQuery(document);
110 equals( test.selector, "", "Document Selector" );
111 equals( test.context, document, "Document Context" );
113 test = jQuery(document.body);
114 equals( test.selector, "", "Body Selector" );
115 equals( test.context, document.body, "Body Context" );
117 test = jQuery("#main");
118 equals( test.selector, "#main", "#main Selector" );
119 equals( test.context, document, "#main Context" );
121 test = jQuery("#notfoundnono");
122 equals( test.selector, "#notfoundnono", "#notfoundnono Selector" );
123 equals( test.context, document, "#notfoundnono Context" );
125 test = jQuery("#main", document);
126 equals( test.selector, "#main", "#main Selector" );
127 equals( test.context, document, "#main Context" );
129 test = jQuery("#main", document.body);
130 equals( test.selector, "#main", "#main Selector" );
131 equals( test.context, document.body, "#main Context" );
135 equals( test.selector, "#main", "#main Selector" );
136 equals( test.context, document.body, "#main Context" );
138 test = jQuery(document.body).find("#main");
139 equals( test.selector, "#main", "#main find Selector" );
140 equals( test.context, document.body, "#main find Context" );
142 test = jQuery("#main").filter("div");
143 equals( test.selector, "#main.filter(div)", "#main filter Selector" );
144 equals( test.context, document, "#main filter Context" );
146 test = jQuery("#main").not("div");
147 equals( test.selector, "#main.not(div)", "#main not Selector" );
148 equals( test.context, document, "#main not Context" );
150 test = jQuery("#main").filter("div").not("div");
151 equals( test.selector, "#main.filter(div).not(div)", "#main filter, not Selector" );
152 equals( test.context, document, "#main filter, not Context" );
154 test = jQuery("#main").filter("div").not("div").end();
155 equals( test.selector, "#main.filter(div)", "#main filter, not, end Selector" );
156 equals( test.context, document, "#main filter, not, end Context" );
158 test = jQuery("#main").parent("body");
159 equals( test.selector, "#main.parent(body)", "#main parent Selector" );
160 equals( test.context, document, "#main parent Context" );
162 test = jQuery("#main").eq(0);
163 equals( test.selector, "#main.slice(0,1)", "#main eq Selector" );
164 equals( test.context, document, "#main eq Context" );
168 jQuery(d).appendTo(jQuery(d)).selector,
169 jQuery(d).appendTo(d).selector,
170 "manipulation methods make same selector for jQuery objects"
175 test("browser", function() {
178 jQuery.get("data/ua.txt", function(data){
179 var uas = data.split("\n");
180 expect( (uas.length - 1) * 2 );
182 jQuery.each(uas, function(){
183 var parts = this.split("\t");
185 var ua = jQuery.uaMatch( parts[2] );
186 equals( ua.browser, parts[0], "Checking browser for " + parts[2] );
187 equals( ua.version, parts[1], "Checking version string for " + parts[2] );
196 test("noConflict", function() {
201 equals( jQuery, jQuery.noConflict(), "noConflict returned the jQuery object" );
202 equals( jQuery, $$, "Make sure jQuery wasn't touched." );
203 equals( $, original$, "Make sure $ was reverted." );
207 equals( jQuery.noConflict(true), $$, "noConflict returned the jQuery object" );
208 equals( jQuery, originaljQuery, "Make sure jQuery was reverted." );
209 equals( $, original$, "Make sure $ was reverted." );
210 ok( $$("#main").html("test"), "Make sure that jQuery still works." );
215 test("trim", function() {
218 var nbsp = String.fromCharCode(160);
220 equals( jQuery.trim("hello "), "hello", "trailing space" );
221 equals( jQuery.trim(" hello"), "hello", "leading space" );
222 equals( jQuery.trim(" hello "), "hello", "space on both sides" );
223 equals( jQuery.trim(" " + nbsp + "hello " + nbsp + " "), "hello", " " );
225 equals( jQuery.trim(), "", "Nothing in." );
226 equals( jQuery.trim( undefined ), "", "Undefined" );
227 equals( jQuery.trim( null ), "", "Null" );
228 equals( jQuery.trim( 5 ), "5", "Number" );
229 equals( jQuery.trim( false ), "false", "Boolean" );
232 test("type", function() {
235 equals( jQuery.type(null), "null", "null" );
236 equals( jQuery.type(undefined), "undefined", "undefined" );
237 equals( jQuery.type(true), "boolean", "Boolean" );
238 equals( jQuery.type(false), "boolean", "Boolean" );
239 equals( jQuery.type(Boolean(true)), "boolean", "Boolean" );
240 equals( jQuery.type(0), "number", "Number" );
241 equals( jQuery.type(1), "number", "Number" );
242 equals( jQuery.type(Number(1)), "number", "Number" );
243 equals( jQuery.type(""), "string", "String" );
244 equals( jQuery.type("a"), "string", "String" );
245 equals( jQuery.type(String("a")), "string", "String" );
246 equals( jQuery.type({}), "object", "Object" );
247 equals( jQuery.type(/foo/), "regexp", "RegExp" );
248 equals( jQuery.type(new RegExp("asdf")), "regexp", "RegExp" );
249 equals( jQuery.type([1]), "array", "Array" );
250 equals( jQuery.type(new Date()), "date", "Date" );
251 equals( jQuery.type(new Function("return;")), "function", "Function" );
252 equals( jQuery.type(function(){}), "function", "Function" );
253 equals( jQuery.type(window), "object", "Window" );
254 equals( jQuery.type(document), "object", "Document" );
255 equals( jQuery.type(document.body), "object", "Element" );
256 equals( jQuery.type(document.createTextNode("foo")), "object", "TextNode" );
257 equals( jQuery.type(document.getElementsByTagName("*")), "object", "NodeList" );
260 test("isPlainObject", function() {
265 // The use case that we want to match
266 ok(jQuery.isPlainObject({}), "{}");
268 // Not objects shouldn't be matched
269 ok(!jQuery.isPlainObject(""), "string");
270 ok(!jQuery.isPlainObject(0) && !jQuery.isPlainObject(1), "number");
271 ok(!jQuery.isPlainObject(true) && !jQuery.isPlainObject(false), "boolean");
272 ok(!jQuery.isPlainObject(null), "null");
273 ok(!jQuery.isPlainObject(undefined), "undefined");
275 // Arrays shouldn't be matched
276 ok(!jQuery.isPlainObject([]), "array");
278 // Instantiated objects shouldn't be matched
279 ok(!jQuery.isPlainObject(new Date), "new Date");
281 var fn = function(){};
283 // Functions shouldn't be matched
284 ok(!jQuery.isPlainObject(fn), "fn");
286 // Again, instantiated objects shouldn't be matched
287 ok(!jQuery.isPlainObject(new fn), "new fn (no methods)");
289 // Makes the function a little more realistic
290 // (and harder to detect, incidentally)
291 fn.prototype = {someMethod: function(){}};
293 // Again, instantiated objects shouldn't be matched
294 ok(!jQuery.isPlainObject(new fn), "new fn");
297 ok(!jQuery.isPlainObject(document.createElement("div")), "DOM Element");
300 ok(!jQuery.isPlainObject(window), "window");
303 var iframe = document.createElement("iframe");
304 document.body.appendChild(iframe);
306 window.iframeDone = function(otherObject){
307 // Objects from other windows should be matched
308 ok(jQuery.isPlainObject(new otherObject), "new otherObject");
309 document.body.removeChild( iframe );
313 var doc = iframe.contentDocument || iframe.contentWindow.document;
315 doc.write("<body onload='window.parent.iframeDone(Object);'>");
318 document.body.removeChild( iframe );
320 ok(true, "new otherObject - iframes not supported");
325 test("isFunction", function() {
328 // Make sure that false values return false
329 ok( !jQuery.isFunction(), "No Value" );
330 ok( !jQuery.isFunction( null ), "null Value" );
331 ok( !jQuery.isFunction( undefined ), "undefined Value" );
332 ok( !jQuery.isFunction( "" ), "Empty String Value" );
333 ok( !jQuery.isFunction( 0 ), "0 Value" );
336 // Safari uses "(Internal Function)"
337 ok( jQuery.isFunction(String), "String Function("+String+")" );
338 ok( jQuery.isFunction(Array), "Array Function("+Array+")" );
339 ok( jQuery.isFunction(Object), "Object Function("+Object+")" );
340 ok( jQuery.isFunction(Function), "Function Function("+Function+")" );
342 // When stringified, this could be misinterpreted
343 var mystr = "function";
344 ok( !jQuery.isFunction(mystr), "Function String" );
346 // When stringified, this could be misinterpreted
347 var myarr = [ "function" ];
348 ok( !jQuery.isFunction(myarr), "Function Array" );
350 // When stringified, this could be misinterpreted
351 var myfunction = { "function": "test" };
352 ok( !jQuery.isFunction(myfunction), "Function Object" );
354 // Make sure normal functions still work
355 var fn = function(){};
356 ok( jQuery.isFunction(fn), "Normal Function" );
358 var obj = document.createElement("object");
360 // Firefox says this is a function
361 ok( !jQuery.isFunction(obj), "Object Element" );
363 // IE says this is an object
364 // Since 1.3, this isn't supported (#2968)
365 //ok( jQuery.isFunction(obj.getAttribute), "getAttribute Function" );
367 var nodes = document.body.childNodes;
369 // Safari says this is a function
370 ok( !jQuery.isFunction(nodes), "childNodes Property" );
372 var first = document.body.firstChild;
374 // Normal elements are reported ok everywhere
375 ok( !jQuery.isFunction(first), "A normal DOM Element" );
377 var input = document.createElement("input");
379 document.body.appendChild( input );
381 // IE says this is an object
382 // Since 1.3, this isn't supported (#2968)
383 //ok( jQuery.isFunction(input.focus), "A default function property" );
385 document.body.removeChild( input );
387 var a = document.createElement("a");
388 a.href = "some-function";
389 document.body.appendChild( a );
391 // This serializes with the word 'function' in it
392 ok( !jQuery.isFunction(a), "Anchor Element" );
394 document.body.removeChild( a );
396 // Recursive function calls have lengths and array-like properties
397 function callme(callback){
398 function fn(response){
402 ok( jQuery.isFunction(fn), "Recursive Function Call" );
404 fn({ some: "data" });
408 callme(function(){});
412 test("isXMLDoc - HTML", function() {
415 ok( !jQuery.isXMLDoc( document ), "HTML document" );
416 ok( !jQuery.isXMLDoc( document.documentElement ), "HTML documentElement" );
417 ok( !jQuery.isXMLDoc( document.body ), "HTML Body Element" );
419 var iframe = document.createElement("iframe");
420 document.body.appendChild( iframe );
423 var body = jQuery(iframe).contents()[0];
426 ok( !jQuery.isXMLDoc( body ), "Iframe body element" );
428 ok( false, "Iframe body element exception" );
432 ok( true, "Iframe body element - iframe not working correctly" );
435 document.body.removeChild( iframe );
439 test("isXMLDoc - XML", function() {
442 jQuery.get('data/dashboard.xml', function(xml) {
443 ok( jQuery.isXMLDoc( xml ), "XML document" );
444 ok( jQuery.isXMLDoc( xml.documentElement ), "XML documentElement" );
445 ok( jQuery.isXMLDoc( jQuery("tab", xml)[0] ), "XML Tab Element" );
451 test("isWindow", function() {
454 ok( jQuery.isWindow(window), "window" );
455 ok( !jQuery.isWindow(), "empty" );
456 ok( !jQuery.isWindow(null), "null" );
457 ok( !jQuery.isWindow(undefined), "undefined" );
458 ok( !jQuery.isWindow(document), "document" );
459 ok( !jQuery.isWindow(document.documentElement), "documentElement" );
460 ok( !jQuery.isWindow(""), "string" );
461 ok( !jQuery.isWindow(1), "number" );
462 ok( !jQuery.isWindow(true), "boolean" );
463 ok( !jQuery.isWindow({}), "object" );
465 // ok( !jQuery.isWindow({ setInterval: function(){} }), "fake window" );
466 ok( !jQuery.isWindow(/window/), "regexp" );
467 ok( !jQuery.isWindow(function(){}), "function" );
470 test("jQuery('html')", function() {
475 var s = jQuery("<script>jQuery.foo='test';</script>")[0];
476 ok( s, "Creating a script" );
477 ok( !jQuery.foo, "Make sure the script wasn't executed prematurely" );
478 jQuery("body").append("<script>jQuery.foo='test';</script>");
479 ok( jQuery.foo, "Executing a scripts contents in the right context" );
481 // Test multi-line HTML
482 var div = jQuery("<div>\r\nsome text\n<p>some p</p>\nmore text\r\n</div>")[0];
483 equals( div.nodeName.toUpperCase(), "DIV", "Make sure we're getting a div." );
484 equals( div.firstChild.nodeType, 3, "Text node." );
485 equals( div.lastChild.nodeType, 3, "Text node." );
486 equals( div.childNodes[1].nodeType, 1, "Paragraph." );
487 equals( div.childNodes[1].firstChild.nodeType, 3, "Paragraph text." );
490 ok( jQuery("<link rel='stylesheet'/>")[0], "Creating a link" );
492 ok( !jQuery("<script/>")[0].parentNode, "Create a script" );
494 ok( jQuery("<input/>").attr("type", "hidden"), "Create an input and set the type." );
496 var j = jQuery("<span>hi</span> there <!-- mon ami -->");
497 ok( j.length >= 2, "Check node,textnode,comment creation (some browsers delete comments)" );
499 ok( !jQuery("<option>test</option>")[0].selected, "Make sure that options are auto-selected #2050" );
501 ok( jQuery("<div></div>")[0], "Create a div with closing tag." );
502 ok( jQuery("<table></table>")[0], "Create a table with closing tag." );
505 test("jQuery('html', context)", function() {
508 var $div = jQuery("<div/>")[0];
509 var $span = jQuery("<span/>", $div);
510 equals($span.length, 1, "Verify a span created with a div context works, #1763");
514 test("jQuery(selector, xml).text(str) - Loaded via XML document", function() {
517 jQuery.get('data/dashboard.xml', function(xml) {
518 // tests for #1419 where IE was a problem
519 var tab = jQuery("tab", xml).eq(0);
520 equals( tab.text(), "blabla", "Verify initial text correct" );
522 equals( tab.text(), "newtext", "Verify new text correct" );
528 test("end()", function() {
530 equals( 'Yahoo', jQuery('#yahoo').parent().end().text(), 'Check for end' );
531 ok( jQuery('#yahoo').end(), 'Check for end with nothing to end' );
533 var x = jQuery('#yahoo');
535 equals( 'Yahoo', jQuery('#yahoo').text(), 'Check for non-destructive behaviour' );
538 test("length", function() {
540 equals( jQuery("p").length, 6, "Get Number of Elements Found" );
543 test("size()", function() {
545 equals( jQuery("p").size(), 6, "Get Number of Elements Found" );
548 test("get()", function() {
550 same( jQuery("p").get(), q("firstp","ap","sndp","en","sap","first"), "Get All Elements" );
553 test("toArray()", function() {
555 same( jQuery("p").toArray(),
556 q("firstp","ap","sndp","en","sap","first"),
557 "Convert jQuery object to an Array" )
560 test("get(Number)", function() {
562 equals( jQuery("p").get(0), document.getElementById("firstp"), "Get A Single Element" );
563 strictEqual( jQuery("#firstp").get(1), undefined, "Try get with index larger elements count" );
566 test("get(-Number)",function() {
568 equals( jQuery("p").get(-1), document.getElementById("first"), "Get a single element with negative index" );
569 strictEqual( jQuery("#firstp").get(-2), undefined, "Try get with index negative index larger then elements count" );
572 test("each(Function)", function() {
574 var div = jQuery("div");
575 div.each(function(){this.foo = 'zoo';});
577 for ( var i = 0; i < div.size(); i++ ) {
578 if ( div.get(i).foo != "zoo" ) pass = false;
580 ok( pass, "Execute a function, Relative" );
583 test("slice()", function() {
586 var $links = jQuery("#ap a");
588 same( $links.slice(1,2).get(), q("groups"), "slice(1,2)" );
589 same( $links.slice(1).get(), q("groups", "anchor1", "mark"), "slice(1)" );
590 same( $links.slice(0,3).get(), q("google", "groups", "anchor1"), "slice(0,3)" );
591 same( $links.slice(-1).get(), q("mark"), "slice(-1)" );
593 same( $links.eq(1).get(), q("groups"), "eq(1)" );
594 same( $links.eq('2').get(), q("anchor1"), "eq('2')" );
595 same( $links.eq(-1).get(), q("mark"), "eq(-1)" );
598 test("first()/last()", function() {
601 var $links = jQuery("#ap a"), $none = jQuery("asdf");
603 same( $links.first().get(), q("google"), "first()" );
604 same( $links.last().get(), q("mark"), "last()" );
606 same( $none.first().get(), [], "first() none" );
607 same( $none.last().get(), [], "last() none" );
610 test("map()", function() {
611 expect(2);//expect(6);
614 jQuery("#ap").map(function(){
615 return jQuery(this).find("a").get();
617 q("google", "groups", "anchor1", "mark"),
622 jQuery("#ap > a").map(function(){
623 return this.parentNode;
629 return;//these haven't been accepted yet
632 var keys = jQuery.map( {a:1,b:2}, function( v, k ){
636 equals( keys.join(""), "ab", "Map the keys from a hash to an array" );
638 var values = jQuery.map( {a:1,b:2}, function( v, k ){
642 equals( values.join(""), "12", "Map the values from a hash to an array" );
644 var scripts = document.getElementsByTagName("script");
645 var mapped = jQuery.map( scripts, function( v, k ){
649 equals( mapped.length, scripts.length, "Map an array(-like) to a hash" );
651 var flat = jQuery.map( Array(4), function( v, k ){
652 return k % 2 ? k : [k,k,k];//try mixing array and regular returns
655 equals( flat.join(""), "00012223", "try the new flatten technique(#2616)" );
658 test("jQuery.merge()", function() {
661 var parse = jQuery.merge;
663 same( parse([],[]), [], "Empty arrays" );
665 same( parse([1],[2]), [1,2], "Basic" );
666 same( parse([1,2],[3,4]), [1,2,3,4], "Basic" );
668 same( parse([1,2],[]), [1,2], "Second empty" );
669 same( parse([],[1,2]), [1,2], "First empty" );
671 // Fixed at [5998], #3641
672 same( parse([-2,-1], [0,1,2]), [-2,-1,0,1,2], "Second array including a zero (falsy)");
674 // After fixing #5527
675 same( parse([], [null, undefined]), [null, undefined], "Second array including null and undefined values");
676 same( parse({length:0}, [1,2]), {length:2, 0:1, 1:2}, "First array like");
679 test("jQuery.extend(Object, Object)", function() {
682 var settings = { xnumber1: 5, xnumber2: 7, xstring1: "peter", xstring2: "pan" },
683 options = { xnumber2: 1, xstring2: "x", xxx: "newstring" },
684 optionsCopy = { xnumber2: 1, xstring2: "x", xxx: "newstring" },
685 merged = { xnumber1: 5, xnumber2: 1, xstring1: "peter", xstring2: "x", xxx: "newstring" },
686 deep1 = { foo: { bar: true } },
687 deep1copy = { foo: { bar: true } },
688 deep2 = { foo: { baz: true }, foo2: document },
689 deep2copy = { foo: { baz: true }, foo2: document },
690 deepmerged = { foo: { bar: true, baz: true }, foo2: document },
692 nestedarray = { arr: arr };
694 jQuery.extend(settings, options);
695 same( settings, merged, "Check if extended: settings must be extended" );
696 same( options, optionsCopy, "Check if not modified: options must not be modified" );
698 jQuery.extend(settings, null, options);
699 same( settings, merged, "Check if extended: settings must be extended" );
700 same( options, optionsCopy, "Check if not modified: options must not be modified" );
702 jQuery.extend(true, deep1, deep2);
703 same( deep1.foo, deepmerged.foo, "Check if foo: settings must be extended" );
704 same( deep2.foo, deep2copy.foo, "Check if not deep2: options must not be modified" );
705 equals( deep1.foo2, document, "Make sure that a deep clone was not attempted on the document" );
707 ok( jQuery.extend(true, {}, nestedarray).arr !== arr, "Deep extend of object must clone child array" );
710 ok( jQuery.isArray( jQuery.extend(true, { arr: {} }, nestedarray).arr ), "Cloned array heve to be an Array" );
711 ok( jQuery.isPlainObject( jQuery.extend(true, { arr: arr }, { arr: {} }).arr ), "Cloned object heve to be an plain object" );
714 var optionsWithLength = { foo: { length: -1 } };
715 jQuery.extend(true, empty, optionsWithLength);
716 same( empty.foo, optionsWithLength.foo, "The length property must copy correctly" );
719 var optionsWithDate = { foo: { date: new Date } };
720 jQuery.extend(true, empty, optionsWithDate);
721 same( empty.foo, optionsWithDate.foo, "Dates copy correctly" );
723 var myKlass = function() {};
724 var customObject = new myKlass();
725 var optionsWithCustomObject = { foo: { date: customObject } };
727 jQuery.extend(true, empty, optionsWithCustomObject);
728 ok( empty.foo && empty.foo.date === customObject, "Custom objects copy correctly (no methods)" );
730 // Makes the class a little more realistic
731 myKlass.prototype = { someMethod: function(){} };
733 jQuery.extend(true, empty, optionsWithCustomObject);
734 ok( empty.foo && empty.foo.date === customObject, "Custom objects copy correctly" );
736 var ret = jQuery.extend(true, { foo: 4 }, { foo: new Number(5) } );
737 ok( ret.foo == 5, "Wrapped numbers copy correctly" );
740 nullUndef = jQuery.extend({}, options, { xnumber2: null });
741 ok( nullUndef.xnumber2 === null, "Check to make sure null values are copied");
743 nullUndef = jQuery.extend({}, options, { xnumber2: undefined });
744 ok( nullUndef.xnumber2 === options.xnumber2, "Check to make sure undefined values are not copied");
746 nullUndef = jQuery.extend({}, options, { xnumber0: null });
747 ok( nullUndef.xnumber0 === null, "Check to make sure null values are inserted");
750 var recursive = { foo:target, bar:5 };
751 jQuery.extend(true, target, recursive);
752 same( target, { bar:5 }, "Check to make sure a recursive obj doesn't go never-ending loop by not copying it over" );
754 var ret = jQuery.extend(true, { foo: [] }, { foo: [0] } ); // 1907
755 equals( ret.foo.length, 1, "Check to make sure a value with coersion 'false' copies over when necessary to fix #1907" );
757 var ret = jQuery.extend(true, { foo: "1,2,3" }, { foo: [1, 2, 3] } );
758 ok( typeof ret.foo != "string", "Check to make sure values equal with coersion (but not actually equal) overwrite correctly" );
760 var ret = jQuery.extend(true, { foo:"bar" }, { foo:null } );
761 ok( typeof ret.foo !== 'undefined', "Make sure a null value doesn't crash with deep extend, for #1908" );
763 var obj = { foo:null };
764 jQuery.extend(true, obj, { foo:"notnull" } );
765 equals( obj.foo, "notnull", "Make sure a null value can be overwritten" );
768 jQuery.extend(func, { key: "value" } );
769 equals( func.key, "value", "Verify a function can be extended" );
771 var defaults = { xnumber1: 5, xnumber2: 7, xstring1: "peter", xstring2: "pan" },
772 defaultsCopy = { xnumber1: 5, xnumber2: 7, xstring1: "peter", xstring2: "pan" },
773 options1 = { xnumber2: 1, xstring2: "x" },
774 options1Copy = { xnumber2: 1, xstring2: "x" },
775 options2 = { xstring2: "xx", xxx: "newstringx" },
776 options2Copy = { xstring2: "xx", xxx: "newstringx" },
777 merged2 = { xnumber1: 5, xnumber2: 1, xstring1: "peter", xstring2: "xx", xxx: "newstringx" };
779 var settings = jQuery.extend({}, defaults, options1, options2);
780 same( settings, merged2, "Check if extended: settings must be extended" );
781 same( defaults, defaultsCopy, "Check if not modified: options1 must not be modified" );
782 same( options1, options1Copy, "Check if not modified: options1 must not be modified" );
783 same( options2, options2Copy, "Check if not modified: options2 must not be modified" );
786 test("jQuery.each(Object,Function)", function() {
788 jQuery.each( [0,1,2], function(i, n){
789 equals( i, n, "Check array iteration" );
792 jQuery.each( [5,6,7], function(i, n){
793 equals( i, n - 5, "Check array iteration" );
796 jQuery.each( { name: "name", lang: "lang" }, function(i, n){
797 equals( i, n, "Check object iteration" );
801 jQuery.each([1,2,3], function(i,v){ total += v; });
802 equals( total, 6, "Looping over an array" );
804 jQuery.each([1,2,3], function(i,v){ total += v; if ( i == 1 ) return false; });
805 equals( total, 3, "Looping over an array, with break" );
807 jQuery.each({"a":1,"b":2,"c":3}, function(i,v){ total += v; });
808 equals( total, 6, "Looping over an object" );
810 jQuery.each({"a":3,"b":3,"c":3}, function(i,v){ total += v; return false; });
811 equals( total, 3, "Looping over an object, with break" );
813 var f = function(){};
815 jQuery.each(f, function(i){
818 equals( "baz", f.foo, "Loop over a function" );
821 test("jQuery.makeArray", function(){
824 equals( jQuery.makeArray(jQuery('html>*'))[0].nodeName.toUpperCase(), "HEAD", "Pass makeArray a jQuery object" );
826 equals( jQuery.makeArray(document.getElementsByName("PWD")).slice(0,1)[0].name, "PWD", "Pass makeArray a nodelist" );
828 equals( (function(){ return jQuery.makeArray(arguments); })(1,2).join(""), "12", "Pass makeArray an arguments array" );
830 equals( jQuery.makeArray([1,2,3]).join(""), "123", "Pass makeArray a real array" );
832 equals( jQuery.makeArray().length, 0, "Pass nothing to makeArray and expect an empty array" );
834 equals( jQuery.makeArray( 0 )[0], 0 , "Pass makeArray a number" );
836 equals( jQuery.makeArray( "foo" )[0], "foo", "Pass makeArray a string" );
838 equals( jQuery.makeArray( true )[0].constructor, Boolean, "Pass makeArray a boolean" );
840 equals( jQuery.makeArray( document.createElement("div") )[0].nodeName.toUpperCase(), "DIV", "Pass makeArray a single node" );
842 equals( jQuery.makeArray( {length:2, 0:"a", 1:"b"} ).join(""), "ab", "Pass makeArray an array like map (with length)" );
844 ok( !!jQuery.makeArray( document.documentElement.childNodes ).slice(0,1)[0].nodeName, "Pass makeArray a childNodes array" );
846 // function, is tricky as it has length
847 equals( jQuery.makeArray( function(){ return 1;} )[0](), 1, "Pass makeArray a function" );
849 //window, also has length
850 equals( jQuery.makeArray(window)[0], window, "Pass makeArray the window" );
852 equals( jQuery.makeArray(/a/)[0].constructor, RegExp, "Pass makeArray a regex" );
854 ok( jQuery.makeArray(document.getElementById('form')).length >= 13, "Pass makeArray a form (treat as elements)" );
857 same( jQuery.makeArray({'length': '0'}), [], "Make sure object is coerced properly.");
858 same( jQuery.makeArray({'length': '5'}), [], "Make sure object is coerced properly.");
861 test("jQuery.isEmptyObject", function(){
864 equals(true, jQuery.isEmptyObject({}), "isEmptyObject on empty object literal" );
865 equals(false, jQuery.isEmptyObject({a:1}), "isEmptyObject on non-empty object literal" );
868 // equals(true, jQuery.isEmptyObject(null), "isEmptyObject on null" );
871 test("jQuery.proxy", function(){
874 var test = function(){ equals( this, thisObject, "Make sure that scope is set properly." ); };
875 var thisObject = { foo: "bar", method: test };
877 // Make sure normal works
878 test.call( thisObject );
881 jQuery.proxy( test, thisObject )();
883 // Make sure it doesn't freak out
884 equals( jQuery.proxy( null, thisObject ), undefined, "Make sure no function was returned." );
886 // Use the string shortcut
887 jQuery.proxy( thisObject, "method" )();
890 test("jQuery.parseJSON", function(){
893 equals( jQuery.parseJSON(), null, "Nothing in, null out." );
894 equals( jQuery.parseJSON( null ), null, "Nothing in, null out." );
895 equals( jQuery.parseJSON( "" ), null, "Nothing in, null out." );
897 same( jQuery.parseJSON("{}"), {}, "Plain object parsing." );
898 same( jQuery.parseJSON('{"test":1}'), {"test":1}, "Plain object parsing." );
900 same( jQuery.parseJSON('\n{"test":1}'), {"test":1}, "Make sure leading whitespaces are handled." );
903 jQuery.parseJSON("{a:1}");
904 ok( false, "Test malformed JSON string." );
906 ok( true, "Test malformed JSON string." );
910 jQuery.parseJSON("{'a':1}");
911 ok( false, "Test malformed JSON string." );
913 ok( true, "Test malformed JSON string." );
917 test("jQuery._Deferred()", function() {
925 deferred = jQuery._Deferred();
929 deferred.done( function( value ) {
930 equals( value , "value" , "Test pre-resolve callback" );
934 deferred.resolve( "value" );
936 ok( test , "Test pre-resolve callbacks called right away" );
940 deferred.done( function( value ) {
941 equals( value , "value" , "Test post-resolve callback" );
945 ok( test , "Test post-resolve callbacks called right away" );
951 deferred.done( function() {
952 ok( false , "Cancel was ignored" );
956 ok( test , "Test cancel" );
958 deferred = jQuery._Deferred().resolve();
961 deferred.done( function() {
964 ok( true , "Test deferred do not cancel on exception" );
967 strictEqual( e , "Error" , "Test deferred propagates exceptions");
972 deferred = jQuery._Deferred().done( function() {
982 strictEqual( test , "AB" , "Test multiple done parameters" );
986 deferred.done( function() {
988 deferred.done( function() {
1001 strictEqual( test , "ABC" , "Test done callbacks order" );
1003 deferred = jQuery._Deferred();
1005 deferred.resolveWith( jQuery , [ document ] ).done( function( doc ) {
1006 ok( this === jQuery && arguments.length === 1 && doc === document , "Test fire context & args" );
1010 test("jQuery.Deferred()", function() {
1014 jQuery.Deferred( function( defer ) {
1015 strictEqual( this , defer , "Defer passed as this & first argument" );
1016 this.resolve( "done" );
1017 }).then( function( value ) {
1018 strictEqual( value , "done" , "Passed function executed" );
1021 jQuery.Deferred().resolve().then( function() {
1022 ok( true , "Success on resolve" );
1024 ok( false , "Error on resolve" );
1027 jQuery.Deferred().reject().then( function() {
1028 ok( false , "Success on reject" );
1030 ok( true , "Error on reject" );
1033 ( new jQuery.Deferred( function( defer ) {
1034 strictEqual( this , defer , "Defer passed as this & first argument (new)" );
1035 this.resolve( "done" );
1036 }) ).then( function( value ) {
1037 strictEqual( value , "done" , "Passed function executed (new)" );
1040 ( new jQuery.Deferred() ).resolve().then( function() {
1041 ok( true , "Success on resolve (new)" );
1043 ok( false , "Error on resolve (new)" );
1046 ( new jQuery.Deferred() ).reject().then( function() {
1047 ok( false , "Success on reject (new)" );
1049 ok( true , "Error on reject (new)" );
1052 var tmp = jQuery.Deferred();
1054 strictEqual( tmp.promise() , tmp.promise() , "Test deferred always return same promise" );
1055 strictEqual( tmp.promise() , tmp.promise().promise() , "Test deferred's promise always return same promise as deferred" );
1058 test("jQuery.when()", function() {
1062 // Some other objects
1065 "an empty string": "",
1066 "a non-empty string": "some string",
1068 "a number other than zero": 1,
1072 "undefined": undefined,
1073 "a plain object": {}
1075 } , function( message , value ) {
1077 ok( jQuery.isFunction( jQuery.when( value ).then( function( resolveValue ) {
1078 strictEqual( resolveValue , value , "Test the promise was resolved with " + message );
1079 } ).promise ) , "Test " + message + " triggers the creation of a new Promise" );
1083 ok( jQuery.isFunction( jQuery.when().then( function( resolveValue ) {
1084 strictEqual( resolveValue , undefined , "Test the promise was resolved with no parameter" );
1085 } ).promise ) , "Test calling when with no parameter triggers the creation of a new Promise" );
1089 for( i = 1 ; i < 4 ; i++ ) {
1090 jQuery.when( cache || jQuery.Deferred( function() {
1092 }) ).then( function( value ) {
1093 strictEqual( value , 1 , "Function executed" + ( i > 1 ? " only once" : "" ) );
1096 ok( false , "Fail called" );
1101 test("jQuery.when() - joined", function() {
1105 jQuery.when( 1, 2, 3 ).done( function( a, b, c ) {
1106 strictEqual( a , 1 , "Test first param is first resolved value - non-observables" );
1107 strictEqual( b , 2 , "Test second param is second resolved value - non-observables" );
1108 strictEqual( c , 3 , "Test third param is third resolved value - non-observables" );
1109 }).fail( function() {
1110 ok( false , "Test the created deferred was resolved - non-observables");
1113 var successDeferred = jQuery.Deferred().resolve( 1 , 2 , 3 ),
1114 errorDeferred = jQuery.Deferred().reject( "error" , "errorParam" );
1116 jQuery.when( 1 , successDeferred , 3 ).done( function( a, b, c ) {
1117 strictEqual( a , 1 , "Test first param is first resolved value - resolved observable" );
1118 same( b , [ 1 , 2 , 3 ] , "Test second param is second resolved value - resolved observable" );
1119 strictEqual( c , 3 , "Test third param is third resolved value - resolved observable" );
1120 }).fail( function() {
1121 ok( false , "Test the created deferred was resolved - resolved observable");
1124 jQuery.when( 1 , errorDeferred , 3 ).done( function() {
1125 ok( false , "Test the created deferred was rejected - rejected observable");
1126 }).fail( function( error , errorParam ) {
1127 strictEqual( error , "error" , "Test first param is first rejected value - rejected observable" );
1128 strictEqual( errorParam , "errorParam" , "Test second param is second rejected value - rejected observable" );
1132 test("jQuery.sub() - Static Methods", function(){
1134 var Subclass = jQuery.sub();
1136 topLevelMethod: function() {return this.debug;},
1141 setup: function(config) {
1142 this.extend(true, this.config, config);
1145 Subclass.fn.extend({subClassMethod: function() { return this;}});
1147 //Test Simple Subclass
1148 ok(Subclass.topLevelMethod() === false, 'Subclass.topLevelMethod thought debug was true');
1149 ok(Subclass.config.locale == 'en_US', Subclass.config.locale + ' is wrong!');
1150 same(Subclass.config.test, undefined, 'Subclass.config.test is set incorrectly');
1151 equal(jQuery.ajax, Subclass.ajax, 'The subclass failed to get all top level methods');
1153 //Create a SubSubclass
1154 var SubSubclass = Subclass.sub();
1156 //Make Sure the SubSubclass inherited properly
1157 ok(SubSubclass.topLevelMethod() === false, 'SubSubclass.topLevelMethod thought debug was true');
1158 ok(SubSubclass.config.locale == 'en_US', SubSubclass.config.locale + ' is wrong!');
1159 same(SubSubclass.config.test, undefined, 'SubSubclass.config.test is set incorrectly');
1160 equal(jQuery.ajax, SubSubclass.ajax, 'The subsubclass failed to get all top level methods');
1162 //Modify The Subclass and test the Modifications
1163 SubSubclass.fn.extend({subSubClassMethod: function() { return this;}});
1164 SubSubclass.setup({locale: 'es_MX', test: 'worked'});
1165 SubSubclass.debug = true;
1166 SubSubclass.ajax = function() {return false;};
1167 ok(SubSubclass.topLevelMethod(), 'SubSubclass.topLevelMethod thought debug was false');
1168 same(SubSubclass(document).subClassMethod, Subclass.fn.subClassMethod, 'Methods Differ!');
1169 ok(SubSubclass.config.locale == 'es_MX', SubSubclass.config.locale + ' is wrong!');
1170 ok(SubSubclass.config.test == 'worked', 'SubSubclass.config.test is set incorrectly');
1171 notEqual(jQuery.ajax, SubSubclass.ajax, 'The subsubclass failed to get all top level methods');
1173 //This shows that the modifications to the SubSubClass did not bubble back up to it's superclass
1174 ok(Subclass.topLevelMethod() === false, 'Subclass.topLevelMethod thought debug was true');
1175 ok(Subclass.config.locale == 'en_US', Subclass.config.locale + ' is wrong!');
1176 same(Subclass.config.test, undefined, 'Subclass.config.test is set incorrectly');
1177 same(Subclass(document).subSubClassMethod, undefined, 'subSubClassMethod set incorrectly');
1178 equal(jQuery.ajax, Subclass.ajax, 'The subclass failed to get all top level methods');
1181 test("jQuery.sub() - .fn Methods", function(){
1184 var Subclass = jQuery.sub(),
1185 SubclassSubclass = Subclass.sub(),
1186 jQueryDocument = jQuery(document),
1187 selectors, contexts, methods, method, arg, description;
1189 jQueryDocument.toString = function(){ return 'jQueryDocument'; };
1191 Subclass.fn.subclassMethod = function(){};
1192 SubclassSubclass.fn.subclassSubclassMethod = function(){};
1200 methods = [ // all methods that return a new jQuery instance
1206 ['filter', document],
1210 contexts = [undefined, document, jQueryDocument];
1212 jQuery.each(selectors, function(i, selector){
1214 jQuery.each(methods, function(){
1218 jQuery.each(contexts, function(i, context){
1220 description = '("'+selector+'", '+context+').'+method+'('+(arg||'')+')';
1223 jQuery(selector, context)[method](arg).subclassMethod, undefined,
1224 'jQuery'+description+' doesnt have Subclass methods'
1227 jQuery(selector, context)[method](arg).subclassSubclassMethod, undefined,
1228 'jQuery'+description+' doesnt have SubclassSubclass methods'
1231 Subclass(selector, context)[method](arg).subclassMethod, Subclass.fn.subclassMethod,
1232 'Subclass'+description+' has Subclass methods'
1235 Subclass(selector, context)[method](arg).subclassSubclassMethod, undefined,
1236 'Subclass'+description+' doesnt have SubclassSubclass methods'
1239 SubclassSubclass(selector, context)[method](arg).subclassMethod, Subclass.fn.subclassMethod,
1240 'SubclassSubclass'+description+' has Subclass methods'
1243 SubclassSubclass(selector, context)[method](arg).subclassSubclassMethod, SubclassSubclass.fn.subclassSubclassMethod,
1244 'SubclassSubclass'+description+' has SubclassSubclass methods'