├── Makefile
├── rhino
└── js.jar
├── src
├── env.js
└── htmlparser.js
└── test
├── debug.js
├── index.html
├── jquery.js
├── test.js
├── testrunner.js
└── unit
├── ajax.js
├── core.js
├── dimensions.js
├── event.js
├── fx.js
├── offset.js
└── selector.js
/Makefile:
--------------------------------------------------------------------------------
1 |
2 | ENV = src/env.js
3 | TEST = test/test.js
4 |
5 | JAR = java -jar rhino/js.jar
6 |
7 | test-rhino:
8 | @@${JAR} ${TEST}
9 |
10 | run-rhino:
11 | echo "load('src/env.js');window.location='test/index.html';" | ${JAR}
12 |
--------------------------------------------------------------------------------
/rhino/js.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jeresig/env-js/70ed3800d7abaaff54af67e39842f4fc3e5fac61/rhino/js.jar
--------------------------------------------------------------------------------
/src/env.js:
--------------------------------------------------------------------------------
1 | /*
2 | * Pure JavaScript Browser Environment
3 | * By John Resig
4 | * Copyright 2008 John Resig, under the MIT License
5 | */
6 |
7 | // The window Object
8 | var window = this;
9 |
10 | (function(){
11 |
12 | // Browser Navigator
13 |
14 | window.navigator = {
15 | get userAgent(){
16 | return "Mozilla/5.0 (Macintosh; U; Intel Mac OS X; en-US; rv:1.8.1.3) Gecko/20070309 Firefox/2.0.0.3";
17 | }
18 | };
19 |
20 | var curLocation = (new java.io.File("./")).toURL();
21 |
22 | window.__defineSetter__("location", function(url){
23 | var xhr = new XMLHttpRequest();
24 | xhr.open("GET", url);
25 | xhr.onreadystatechange = function(){
26 | curLocation = new java.net.URL( curLocation, url );
27 | window.document = xhr.responseXML;
28 |
29 | var event = document.createEvent();
30 | event.initEvent("load");
31 | window.dispatchEvent( event );
32 | };
33 | xhr.send();
34 | });
35 |
36 | window.__defineGetter__("location", function(url){
37 | return {
38 | get protocol(){
39 | return curLocation.getProtocol() + ":";
40 | },
41 | get href(){
42 | return curLocation.toString();
43 | },
44 | toString: function(){
45 | return this.href;
46 | }
47 | };
48 | });
49 |
50 | // Timers
51 |
52 | var timers = [];
53 |
54 | window.setTimeout = function(fn, time){
55 | var num;
56 | return num = setInterval(function(){
57 | fn();
58 | clearInterval(num);
59 | }, time);
60 | };
61 |
62 | window.setInterval = function(fn, time){
63 | var num = timers.length;
64 |
65 | timers[num] = new java.lang.Thread(new java.lang.Runnable({
66 | run: function(){
67 | while (true){
68 | java.lang.Thread.currentThread().sleep(time);
69 | fn();
70 | }
71 | }
72 | }));
73 |
74 | timers[num].start();
75 |
76 | return num;
77 | };
78 |
79 | window.clearInterval = function(num){
80 | if ( timers[num] ) {
81 | timers[num].stop();
82 | delete timers[num];
83 | }
84 | };
85 |
86 | // Window Events
87 |
88 | var events = [{}];
89 |
90 | window.addEventListener = function(type, fn){
91 | if ( !this.uuid || this == window ) {
92 | this.uuid = events.length;
93 | events[this.uuid] = {};
94 | }
95 |
96 | if ( !events[this.uuid][type] )
97 | events[this.uuid][type] = [];
98 |
99 | if ( events[this.uuid][type].indexOf( fn ) < 0 )
100 | events[this.uuid][type].push( fn );
101 | };
102 |
103 | window.removeEventListener = function(type, fn){
104 | if ( !this.uuid || this == window ) {
105 | this.uuid = events.length;
106 | events[this.uuid] = {};
107 | }
108 |
109 | if ( !events[this.uuid][type] )
110 | events[this.uuid][type] = [];
111 |
112 | events[this.uuid][type] =
113 | events[this.uuid][type].filter(function(f){
114 | return f != fn;
115 | });
116 | };
117 |
118 | window.dispatchEvent = function(event){
119 | if ( event.type ) {
120 | if ( this.uuid && events[this.uuid][event.type] ) {
121 | var self = this;
122 |
123 | events[this.uuid][event.type].forEach(function(fn){
124 | fn.call( self, event );
125 | });
126 | }
127 |
128 | if ( this["on" + event.type] )
129 | this["on" + event.type].call( self, event );
130 | }
131 | };
132 |
133 | // DOM Document
134 |
135 | window.DOMDocument = function(file){
136 | this._file = file;
137 | this._dom = Packages.javax.xml.parsers.
138 | DocumentBuilderFactory.newInstance()
139 | .newDocumentBuilder().parse(file);
140 |
141 | if ( !obj_nodes.containsKey( this._dom ) )
142 | obj_nodes.put( this._dom, this );
143 | };
144 |
145 | DOMDocument.prototype = {
146 | get nodeType(){
147 | return 9;
148 | },
149 | createTextNode: function(text){
150 | return makeNode( this._dom.createTextNode(
151 | text.replace(/&/g, "&").replace(//g, ">")) );
152 | },
153 | createElement: function(name){
154 | return makeNode( this._dom.createElement(name.toLowerCase()) );
155 | },
156 | getElementsByTagName: function(name){
157 | return new DOMNodeList( this._dom.getElementsByTagName(
158 | name.toLowerCase()) );
159 | },
160 | getElementsByName: function(name){
161 | var elems = this._dom.getElementsByTagName("*"), ret = [];
162 | ret.item = function(i){ return this[i]; };
163 | ret.getLength = function(){ return this.length; };
164 |
165 | for ( var i = 0; i < elems.length; i++ ) {
166 | var elem = elems.item(i);
167 | if ( elem.getAttribute("name") == name )
168 | ret.push( elem );
169 | }
170 |
171 | return new DOMNodeList( ret );
172 | },
173 | getElementById: function(id){
174 | var elems = this._dom.getElementsByTagName("*");
175 |
176 | for ( var i = 0; i < elems.length; i++ ) {
177 | var elem = elems.item(i);
178 | if ( elem.getAttribute("id") == id )
179 | return makeNode(elem);
180 | }
181 |
182 | return null;
183 | },
184 | get body(){
185 | return this.getElementsByTagName("body")[0];
186 | },
187 | get documentElement(){
188 | return makeNode( this._dom.getDocumentElement() );
189 | },
190 | get ownerDocument(){
191 | return null;
192 | },
193 | addEventListener: window.addEventListener,
194 | removeEventListener: window.removeEventListener,
195 | dispatchEvent: window.dispatchEvent,
196 | get nodeName() {
197 | return "#document";
198 | },
199 | importNode: function(node, deep){
200 | return makeNode( this._dom.importNode(node._dom, deep) );
201 | },
202 | toString: function(){
203 | return "Document" + (typeof this._file == "string" ?
204 | ": " + this._file : "");
205 | },
206 | get innerHTML(){
207 | return this.documentElement.outerHTML;
208 | },
209 |
210 | get defaultView(){
211 | return {
212 | getComputedStyle: function(elem){
213 | return {
214 | getPropertyValue: function(prop){
215 | prop = prop.replace(/\-(\w)/g,function(m,c){
216 | return c.toUpperCase();
217 | });
218 | var val = elem.style[prop];
219 |
220 | if ( prop == "opacity" && val == "" )
221 | val = "1";
222 |
223 | return val;
224 | }
225 | };
226 | }
227 | };
228 | },
229 |
230 | createEvent: function(){
231 | return {
232 | type: "",
233 | initEvent: function(type){
234 | this.type = type;
235 | }
236 | };
237 | }
238 | };
239 |
240 | function getDocument(node){
241 | return obj_nodes.get(node);
242 | }
243 |
244 | // DOM NodeList
245 |
246 | window.DOMNodeList = function(list){
247 | this._dom = list;
248 | this.length = list.getLength();
249 |
250 | for ( var i = 0; i < this.length; i++ ) {
251 | var node = list.item(i);
252 | this[i] = makeNode( node );
253 | }
254 | };
255 |
256 | DOMNodeList.prototype = {
257 | toString: function(){
258 | return "[ " +
259 | Array.prototype.join.call( this, ", " ) + " ]";
260 | },
261 | get outerHTML(){
262 | return Array.prototype.map.call(
263 | this, function(node){return node.outerHTML;}).join('');
264 | }
265 | };
266 |
267 | // DOM Node
268 |
269 | window.DOMNode = function(node){
270 | this._dom = node;
271 | };
272 |
273 | DOMNode.prototype = {
274 | get nodeType(){
275 | return this._dom.getNodeType();
276 | },
277 | get nodeValue(){
278 | return this._dom.getNodeValue();
279 | },
280 | get nodeName() {
281 | return this._dom.getNodeName();
282 | },
283 | get childNodes(){
284 | return new DOMNodeList( this._dom.getChildNodes() );
285 | },
286 | cloneNode: function(deep){
287 | return makeNode( this._dom.cloneNode(deep) );
288 | },
289 | get ownerDocument(){
290 | return getDocument( this._dom.ownerDocument );
291 | },
292 | get documentElement(){
293 | return makeNode( this._dom.documentElement );
294 | },
295 | get parentNode() {
296 | return makeNode( this._dom.getParentNode() );
297 | },
298 | get nextSibling() {
299 | return makeNode( this._dom.getNextSibling() );
300 | },
301 | get previousSibling() {
302 | return makeNode( this._dom.getPreviousSibling() );
303 | },
304 | toString: function(){
305 | return '"' + this.nodeValue + '"';
306 | },
307 | get outerHTML(){
308 | return this.nodeValue;
309 | }
310 | };
311 |
312 | window.DOMComment = function(node){
313 | this._dom = node;
314 | };
315 |
316 | DOMComment.prototype = extend(new DOMNode(), {
317 | get nodeType(){
318 | return 8;
319 | },
320 | get outerHTML(){
321 | return "";
322 | }
323 | });
324 |
325 | // DOM Element
326 |
327 | window.DOMElement = function(elem){
328 | this._dom = elem;
329 | this.style = {
330 | get opacity(){ return this._opacity; },
331 | set opacity(val){ this._opacity = val + ""; }
332 | };
333 |
334 | // Load CSS info
335 | var styles = (this.getAttribute("style") || "").split(/\s*;\s*/);
336 |
337 | for ( var i = 0; i < styles.length; i++ ) {
338 | var style = styles[i].split(/\s*:\s*/);
339 | if ( style.length == 2 )
340 | this.style[ style[0] ] = style[1];
341 | }
342 |
343 | if ( this.nodeName == "FORM" ) {
344 | this.__defineGetter__("elements", function(){
345 | return this.getElementsByTagName("*");
346 | });
347 |
348 | this.__defineGetter__("length", function(){
349 | var elems = this.elements;
350 | for ( var i = 0; i < elems.length; i++ ) {
351 | this[i] = elems[i];
352 | }
353 |
354 | return elems.length;
355 | });
356 | }
357 |
358 | if ( this.nodeName == "SELECT" ) {
359 | this.__defineGetter__("options", function(){
360 | return this.getElementsByTagName("option");
361 | });
362 | }
363 |
364 | this.defaultValue = this.value;
365 | };
366 |
367 | DOMElement.prototype = extend( new DOMNode(), {
368 | get nodeName(){
369 | return this.tagName;
370 | },
371 | get tagName(){
372 | return this._dom.getTagName().toUpperCase();
373 | },
374 | toString: function(){
375 | return "<" + this.tagName + (this.id ? "#" + this.id : "" ) + ">";
376 | },
377 | get outerHTML(){
378 | var ret = "<" + this.tagName, attr = this.attributes;
379 |
380 | for ( var i in attr )
381 | ret += " " + i + "='" + attr[i] + "'";
382 |
383 | if ( this.childNodes.length || this.nodeName == "SCRIPT" )
384 | ret += ">" + this.childNodes.outerHTML +
385 | "" + this.tagName + ">";
386 | else
387 | ret += "/>";
388 |
389 | return ret;
390 | },
391 |
392 | get attributes(){
393 | var attr = {}, attrs = this._dom.getAttributes();
394 |
395 | for ( var i = 0; i < attrs.getLength(); i++ )
396 | attr[ attrs.item(i).nodeName ] = attrs.item(i).nodeValue;
397 |
398 | return attr;
399 | },
400 |
401 | get innerHTML(){
402 | return this.childNodes.outerHTML;
403 | },
404 | set innerHTML(html){
405 | html = html.replace(/<\/?([A-Z]+)/g, function(m){
406 | return m.toLowerCase();
407 | }).replace(/ /g, " ");
408 |
409 | var nodes = this.ownerDocument.importNode(
410 | new DOMDocument( new java.io.ByteArrayInputStream(
411 | (new java.lang.String("" + html + " "))
412 | .getBytes("UTF8"))).documentElement, true).childNodes;
413 |
414 | while (this.firstChild)
415 | this.removeChild( this.firstChild );
416 |
417 | for ( var i = 0; i < nodes.length; i++ )
418 | this.appendChild( nodes[i] );
419 | },
420 |
421 | get textContent(){
422 | return nav(this.childNodes);
423 |
424 | function nav(nodes){
425 | var str = "";
426 | for ( var i = 0; i < nodes.length; i++ )
427 | if ( nodes[i].nodeType == 3 )
428 | str += nodes[i].nodeValue;
429 | else if ( nodes[i].nodeType == 1 )
430 | str += nav(nodes[i].childNodes);
431 | return str;
432 | }
433 | },
434 | set textContent(text){
435 | while (this.firstChild)
436 | this.removeChild( this.firstChild );
437 | this.appendChild( this.ownerDocument.createTextNode(text));
438 | },
439 |
440 | style: {},
441 | clientHeight: 0,
442 | clientWidth: 0,
443 | offsetHeight: 0,
444 | offsetWidth: 0,
445 |
446 | get disabled() {
447 | var val = this.getAttribute("disabled");
448 | return val != "false" && !!val;
449 | },
450 | set disabled(val) { return this.setAttribute("disabled",val); },
451 |
452 | get checked() {
453 | var val = this.getAttribute("checked");
454 | return val != "false" && !!val;
455 | },
456 | set checked(val) { return this.setAttribute("checked",val); },
457 |
458 | get selected() {
459 | if ( !this._selectDone ) {
460 | this._selectDone = true;
461 |
462 | if ( this.nodeName == "OPTION" && !this.parentNode.getAttribute("multiple") ) {
463 | var opt = this.parentNode.getElementsByTagName("option");
464 |
465 | if ( this == opt[0] ) {
466 | var select = true;
467 |
468 | for ( var i = 1; i < opt.length; i++ )
469 | if ( opt[i].selected ) {
470 | select = false;
471 | break;
472 | }
473 |
474 | if ( select )
475 | this.selected = true;
476 | }
477 | }
478 | }
479 |
480 | var val = this.getAttribute("selected");
481 | return val != "false" && !!val;
482 | },
483 | set selected(val) { return this.setAttribute("selected",val); },
484 |
485 | get className() { return this.getAttribute("class") || ""; },
486 | set className(val) {
487 | return this.setAttribute("class",
488 | val.replace(/(^\s*|\s*$)/g,""));
489 | },
490 |
491 | get type() { return this.getAttribute("type") || ""; },
492 | set type(val) { return this.setAttribute("type",val); },
493 |
494 | get defaultValue() { return this.getAttribute("defaultValue") || ""; },
495 | set defaultValue(val) { return this.setAttribute("defaultValue",val); },
496 |
497 | get value() { return this.getAttribute("value") || ""; },
498 | set value(val) { return this.setAttribute("value",val); },
499 |
500 | get src() { return this.getAttribute("src") || ""; },
501 | set src(val) { return this.setAttribute("src",val); },
502 |
503 | get id() { return this.getAttribute("id") || ""; },
504 | set id(val) { return this.setAttribute("id",val); },
505 |
506 | getAttribute: function(name){
507 | return this._dom.hasAttribute(name) ?
508 | new String( this._dom.getAttribute(name) ) :
509 | null;
510 | },
511 | setAttribute: function(name,value){
512 | this._dom.setAttribute(name,value);
513 | },
514 | removeAttribute: function(name){
515 | this._dom.removeAttribute(name);
516 | },
517 |
518 | get childNodes(){
519 | return new DOMNodeList( this._dom.getChildNodes() );
520 | },
521 | get firstChild(){
522 | return makeNode( this._dom.getFirstChild() );
523 | },
524 | get lastChild(){
525 | return makeNode( this._dom.getLastChild() );
526 | },
527 | appendChild: function(node){
528 | this._dom.appendChild( node._dom );
529 | },
530 | insertBefore: function(node,before){
531 | this._dom.insertBefore( node._dom, before ? before._dom : before );
532 |
533 | execScripts( node );
534 |
535 | function execScripts( node ) {
536 | if ( node.nodeName == "SCRIPT" ) {
537 | if ( !node.getAttribute("src") ) {
538 | eval.call( window, node.textContent );
539 | }
540 | } else {
541 | var scripts = node.getElementsByTagName("script");
542 | for ( var i = 0; i < scripts.length; i++ ) {
543 | execScripts( node );
544 | }
545 | }
546 | }
547 | },
548 | removeChild: function(node){
549 | this._dom.removeChild( node._dom );
550 | },
551 |
552 | getElementsByTagName: DOMDocument.prototype.getElementsByTagName,
553 |
554 | addEventListener: window.addEventListener,
555 | removeEventListener: window.removeEventListener,
556 | dispatchEvent: window.dispatchEvent,
557 |
558 | click: function(){
559 | var event = document.createEvent();
560 | event.initEvent("click");
561 | this.dispatchEvent(event);
562 | },
563 | submit: function(){
564 | var event = document.createEvent();
565 | event.initEvent("submit");
566 | this.dispatchEvent(event);
567 | },
568 | focus: function(){
569 | var event = document.createEvent();
570 | event.initEvent("focus");
571 | this.dispatchEvent(event);
572 | },
573 | blur: function(){
574 | var event = document.createEvent();
575 | event.initEvent("blur");
576 | this.dispatchEvent(event);
577 | },
578 | get contentWindow(){
579 | return this.nodeName == "IFRAME" ? {
580 | document: this.contentDocument
581 | } : null;
582 | },
583 | get contentDocument(){
584 | if ( this.nodeName == "IFRAME" ) {
585 | if ( !this._doc )
586 | this._doc = new DOMDocument(
587 | new java.io.ByteArrayInputStream((new java.lang.String(
588 | "
,
, ]
112 | */
113 | function q() {
114 | var r = [];
115 | for ( var i = 0; i < arguments.length; i++ )
116 | r.push( document.getElementById( arguments[i] ) );
117 | return r;
118 | }
119 |
120 | /**
121 | * Asserts that a select matches the given IDs
122 | * @example t("Check for something", "//[a]", ["foo", "baar"]);
123 | * @result returns true if "//[a]" return two elements with the IDs 'foo' and 'baar'
124 | */
125 | function t(a,b,c) {
126 | var f = jQuery(b);
127 | var s = "";
128 | for ( var i = 0; i < f.length; i++ )
129 | s += (s && ",") + '"' + f[i].id + '"';
130 | isSet(f, q.apply(q,c), a + " (" + b + ")");
131 | }
132 |
133 | /**
134 | * Checks that the first two arguments are equal, with an optional message.
135 | * Prints out both expected and actual values on failure.
136 | *
137 | * Prefered to ok( expected == actual, message )
138 | *
139 | * @example equals( "Expected 2 characters.", v.formatMessage("Expected {0} characters.", 2) );
140 | *
141 | * @param Object expected
142 | * @param Object actual
143 | * @param String message (optional)
144 | */
145 | function equals(expected, actual, message) {
146 | var result = expected == actual;
147 | message = message || (result ? "okay" : "failed");
148 | log( result, result ? message + ": " + expected : message + " actual: " + expected + " expected: " + actual );
149 | }
150 |
151 | var numTests = 0, total = 0, pass = 0, fail = 0;
152 |
153 | function log(state, msg){
154 | print( (state ? "PASS" : "FAIL") + " (" + (++total) + ") " +
155 | (currentModule ? "[" + currentModule + "] " : "") + msg );
156 |
157 | numTests++;
158 |
159 | if ( state )
160 | pass++;
161 | else
162 | fail++;
163 | }
164 |
165 | function results(){
166 | print( pass + " Passed, " + fail + " Failed" );
167 | }
168 |
169 | function start(){}
170 | function stop(){}
171 |
172 | /**
173 | * Trigger an event on an element.
174 | *
175 | * @example triggerEvent( document.body, "click" );
176 | *
177 | * @param DOMElement elem
178 | * @param String type
179 | */
180 | function triggerEvent( elem, type, event ) {
181 | /*
182 | if ( jQuery.browser.mozilla || jQuery.browser.opera ) {
183 | event = document.createEvent("MouseEvents");
184 | event.initMouseEvent(type, true, true, elem.ownerDocument.defaultView,
185 | 0, 0, 0, 0, 0, false, false, false, false, 0, null);
186 | elem.dispatchEvent( event );
187 | } else if ( jQuery.browser.msie ) {
188 | elem.fireEvent("on"+type);
189 | }
190 | */
191 | }
192 |
193 | /**
194 | * Add random number to url to stop IE from caching
195 | *
196 | * @example url("data/test.html")
197 | * @result "data/test.html?10538358428943"
198 | *
199 | * @example url("data/test.php?foo=bar")
200 | * @result "data/test.php?foo=bar&10538358345554"
201 | */
202 | function url(value) {
203 | return value + (/\?/.test(value) ? "&" : "?") + new Date().getTime() + "" + parseInt(Math.random()*100000);
204 | }
205 |
--------------------------------------------------------------------------------
/test/unit/ajax.js:
--------------------------------------------------------------------------------
1 | module("ajax");
2 |
3 | // Safari 3 randomly crashes when running these tests,
4 | // but only in the full suite - you can run just the Ajax
5 | // tests and they'll pass
6 | //if ( !jQuery.browser.safari ) {
7 |
8 | if ( !isLocal ) {
9 |
10 | test("jQuery.ajax() - success callbacks", function() {
11 | expect( 8 );
12 |
13 | jQuery.ajaxSetup({ timeout: 0 });
14 |
15 | stop();
16 |
17 | setTimeout(function(){
18 | jQuery('#foo').ajaxStart(function(){
19 | ok( true, "ajaxStart" );
20 | }).ajaxStop(function(){
21 | ok( true, "ajaxStop" );
22 | start();
23 | }).ajaxSend(function(){
24 | ok( true, "ajaxSend" );
25 | }).ajaxComplete(function(){
26 | ok( true, "ajaxComplete" );
27 | }).ajaxError(function(){
28 | ok( false, "ajaxError" );
29 | }).ajaxSuccess(function(){
30 | ok( true, "ajaxSuccess" );
31 | });
32 |
33 | jQuery.ajax({
34 | url: url("data/name.html"),
35 | beforeSend: function(){ ok(true, "beforeSend"); },
36 | success: function(){ ok(true, "success"); },
37 | error: function(){ ok(false, "error"); },
38 | complete: function(){ ok(true, "complete"); }
39 | });
40 | }, 13);
41 | });
42 |
43 | test("jQuery.ajax() - error callbacks", function() {
44 | expect( 8 );
45 | stop();
46 |
47 | jQuery('#foo').ajaxStart(function(){
48 | ok( true, "ajaxStart" );
49 | }).ajaxStop(function(){
50 | ok( true, "ajaxStop" );
51 | start();
52 | }).ajaxSend(function(){
53 | ok( true, "ajaxSend" );
54 | }).ajaxComplete(function(){
55 | ok( true, "ajaxComplete" );
56 | }).ajaxError(function(){
57 | ok( true, "ajaxError" );
58 | }).ajaxSuccess(function(){
59 | ok( false, "ajaxSuccess" );
60 | });
61 |
62 | jQuery.ajaxSetup({ timeout: 500 });
63 |
64 | jQuery.ajax({
65 | url: url("data/name.php?wait=5"),
66 | beforeSend: function(){ ok(true, "beforeSend"); },
67 | success: function(){ ok(false, "success"); },
68 | error: function(){ ok(true, "error"); },
69 | complete: function(){ ok(true, "complete"); }
70 | });
71 | });
72 |
73 | test("jQuery.ajax() - disabled globals", function() {
74 | expect( 3 );
75 | stop();
76 |
77 | jQuery('#foo').ajaxStart(function(){
78 | ok( false, "ajaxStart" );
79 | }).ajaxStop(function(){
80 | ok( false, "ajaxStop" );
81 | }).ajaxSend(function(){
82 | ok( false, "ajaxSend" );
83 | }).ajaxComplete(function(){
84 | ok( false, "ajaxComplete" );
85 | }).ajaxError(function(){
86 | ok( false, "ajaxError" );
87 | }).ajaxSuccess(function(){
88 | ok( false, "ajaxSuccess" );
89 | });
90 |
91 | jQuery.ajax({
92 | global: false,
93 | url: url("data/name.html"),
94 | beforeSend: function(){ ok(true, "beforeSend"); },
95 | success: function(){ ok(true, "success"); },
96 | error: function(){ ok(false, "error"); },
97 | complete: function(){
98 | ok(true, "complete");
99 | setTimeout(function(){ start(); }, 13);
100 | }
101 | });
102 | });
103 |
104 | test("jQuery.ajax - xml: non-namespace elements inside namespaced elements", function() {
105 | expect(3);
106 | stop();
107 | jQuery.ajax({
108 | url: url("data/with_fries.xml"),
109 | dataType: "xml",
110 | success: function(resp) {
111 | equals( jQuery("properties", resp).length, 1, 'properties in responseXML' );
112 | equals( jQuery("jsconf", resp).length, 1, 'jsconf in responseXML' );
113 | equals( jQuery("thing", resp).length, 2, 'things in responseXML' );
114 | start();
115 | }
116 | });
117 | });
118 |
119 | test("jQuery.ajax - beforeSend", function() {
120 | expect(1);
121 | stop();
122 |
123 | var check = false;
124 |
125 | jQuery.ajaxSetup({ timeout: 0 });
126 |
127 | jQuery.ajax({
128 | url: url("data/name.html"),
129 | beforeSend: function(xml) {
130 | check = true;
131 | },
132 | success: function(data) {
133 | ok( check, "check beforeSend was executed" );
134 | start();
135 | }
136 | });
137 | });
138 |
139 | test("jQuery.ajax - beforeSend, cancel request (#2688)", function() {
140 | expect(2);
141 | var request = jQuery.ajax({
142 | url: url("data/name.html"),
143 | beforeSend: function() {
144 | ok( true, "beforeSend got called, canceling" );
145 | return false;
146 | },
147 | success: function() {
148 | ok( false, "request didn't get canceled" );
149 | },
150 | complete: function() {
151 | ok( false, "request didn't get canceled" );
152 | },
153 | error: function() {
154 | ok( false, "request didn't get canceled" );
155 | }
156 | });
157 | ok( request === false, "canceled request must return false instead of XMLHttpRequest instance" );
158 | });
159 |
160 | var foobar;
161 |
162 | test("jQuery.ajax - dataType html", function() {
163 | expect(5);
164 | stop();
165 |
166 | foobar = null;
167 | testFoo = undefined;
168 |
169 | var verifyEvaluation = function() {
170 | equals( testFoo, "foo", 'Check if script was evaluated for datatype html' );
171 | equals( foobar, "bar", 'Check if script src was evaluated for datatype html' );
172 | start();
173 | };
174 |
175 | jQuery.ajax({
176 | dataType: "html",
177 | url: url("data/test.html"),
178 | success: function(data) {
179 | jQuery("#ap").html(data);
180 | ok( data.match(/^html text/), 'Check content for datatype html' );
181 | setTimeout(verifyEvaluation, 600);
182 | }
183 | });
184 | });
185 |
186 | test("serialize()", function() {
187 | expect(6);
188 |
189 | equals( jQuery('#form').serialize(),
190 | "action=Test&radio2=on&check=on&hidden=&foo%5Bbar%5D=&name=name&select1=&select2=3&select3=1&select3=2",
191 | 'Check form serialization as query string');
192 |
193 | equals( jQuery('#form :input').serialize(),
194 | "action=Test&radio2=on&check=on&hidden=&foo%5Bbar%5D=&name=name&select1=&select2=3&select3=1&select3=2",
195 | 'Check input serialization as query string');
196 |
197 | equals( jQuery('#testForm').serialize(),
198 | 'T3=%3F%0AZ&H1=x&H2=&PWD=&T1=&T2=YES&My+Name=me&S1=abc&S3=YES&S4=',
199 | 'Check form serialization as query string');
200 |
201 | equals( jQuery('#testForm :input').serialize(),
202 | 'T3=%3F%0AZ&H1=x&H2=&PWD=&T1=&T2=YES&My+Name=me&S1=abc&S3=YES&S4=',
203 | 'Check input serialization as query string');
204 |
205 | equals( jQuery('#form, #testForm').serialize(),
206 | "action=Test&radio2=on&check=on&hidden=&foo%5Bbar%5D=&name=name&select1=&select2=3&select3=1&select3=2&T3=%3F%0AZ&H1=x&H2=&PWD=&T1=&T2=YES&My+Name=me&S1=abc&S3=YES&S4=",
207 | 'Multiple form serialization as query string');
208 |
209 | equals( jQuery('#form, #testForm :input').serialize(),
210 | "action=Test&radio2=on&check=on&hidden=&foo%5Bbar%5D=&name=name&select1=&select2=3&select3=1&select3=2&T3=%3F%0AZ&H1=x&H2=&PWD=&T1=&T2=YES&My+Name=me&S1=abc&S3=YES&S4=",
211 | 'Mixed form/input serialization as query string');
212 | });
213 |
214 | test("jQuery.param()", function() {
215 | expect(4);
216 | var params = {foo:"bar", baz:42, quux:"All your base are belong to us"};
217 | equals( jQuery.param(params), "foo=bar&baz=42&quux=All+your+base+are+belong+to+us", "simple" );
218 |
219 | params = {someName: [1, 2, 3], regularThing: "blah" };
220 | equals( jQuery.param(params), "someName=1&someName=2&someName=3®ularThing=blah", "with array" );
221 |
222 | params = {"foo[]":["baz", 42, "All your base are belong to us"]};
223 | equals( jQuery.param(params), "foo%5B%5D=baz&foo%5B%5D=42&foo%5B%5D=All+your+base+are+belong+to+us", "more array" );
224 |
225 | params = {"foo[bar]":"baz", "foo[beep]":42, "foo[quux]":"All your base are belong to us"};
226 | equals( jQuery.param(params), "foo%5Bbar%5D=baz&foo%5Bbeep%5D=42&foo%5Bquux%5D=All+your+base+are+belong+to+us", "even more arrays" );
227 | });
228 |
229 | test("synchronous request", function() {
230 | expect(1);
231 | ok( /^{ "data"/.test( jQuery.ajax({url: url("data/json_obj.js"), async: false}).responseText ), "check returned text" );
232 | });
233 |
234 | test("synchronous request with callbacks", function() {
235 | expect(2);
236 | var result;
237 | jQuery.ajax({url: url("data/json_obj.js"), async: false, success: function(data) { ok(true, "sucess callback executed"); result = data; } });
238 | ok( /^{ "data"/.test( result ), "check returned text" );
239 | });
240 |
241 | test("pass-through request object", function() {
242 | expect(8);
243 | stop(true);
244 |
245 | var target = "data/name.html";
246 | var successCount = 0;
247 | var errorCount = 0;
248 | var errorEx = "";
249 | var success = function() {
250 | successCount++;
251 | };
252 | jQuery("#foo").ajaxError(function (e, xml, s, ex) {
253 | errorCount++;
254 | errorEx += ": " + xml.status;
255 | });
256 | jQuery("#foo").one('ajaxStop', function () {
257 | equals(successCount, 5, "Check all ajax calls successful");
258 | equals(errorCount, 0, "Check no ajax errors (status" + errorEx + ")");
259 | jQuery("#foo").unbind('ajaxError');
260 | start();
261 | });
262 |
263 | ok( jQuery.get(url(target), success), "get" );
264 | ok( jQuery.post(url(target), success), "post" );
265 | ok( jQuery.getScript(url("data/test.js"), success), "script" );
266 | ok( jQuery.getJSON(url("data/json_obj.js"), success), "json" );
267 | ok( jQuery.ajax({url: url(target), success: success}), "generic" );
268 | });
269 |
270 | test("ajax cache", function () {
271 | expect(18);
272 | stop();
273 |
274 | var count = 0;
275 |
276 | jQuery("#firstp").bind("ajaxSuccess", function (e, xml, s) {
277 | var re = /_=(.*?)(&|$)/g;
278 | var oldOne = null;
279 | for (var i = 0; i < 6; i++) {
280 | var ret = re.exec(s.url);
281 | if (!ret) {
282 | break;
283 | }
284 | oldOne = ret[1];
285 | }
286 | equals(i, 1, "Test to make sure only one 'no-cache' parameter is there");
287 | ok(oldOne != "tobereplaced555", "Test to be sure parameter (if it was there) was replaced");
288 | if(++count == 6)
289 | start();
290 | });
291 |
292 | ok( jQuery.ajax({url: "data/text.php", cache:false}), "test with no parameters" );
293 | ok( jQuery.ajax({url: "data/text.php?pizza=true", cache:false}), "test with 1 parameter" );
294 | ok( jQuery.ajax({url: "data/text.php?_=tobereplaced555", cache:false}), "test with _= parameter" );
295 | ok( jQuery.ajax({url: "data/text.php?pizza=true&_=tobereplaced555", cache:false}), "test with 1 parameter plus _= one" );
296 | ok( jQuery.ajax({url: "data/text.php?_=tobereplaced555&tv=false", cache:false}), "test with 1 parameter plus _= one before it" );
297 | ok( jQuery.ajax({url: "data/text.php?name=David&_=tobereplaced555&washere=true", cache:false}), "test with 2 parameters surrounding _= one" );
298 | });
299 |
300 | test("global ajaxSettings", function() {
301 | expect(2);
302 |
303 | var tmp = jQuery.extend({}, jQuery.ajaxSettings);
304 | var orig = { url: "data/with_fries.xml" };
305 | var t;
306 |
307 | jQuery.ajaxSetup({ data: {foo: 'bar', bar: 'BAR'} });
308 |
309 | t = jQuery.extend({}, orig);
310 | t.data = {};
311 | jQuery.ajax(t);
312 | ok( t.url.indexOf('foo') > -1 && t.url.indexOf('bar') > -1, "Check extending {}" );
313 |
314 | t = jQuery.extend({}, orig);
315 | t.data = { zoo: 'a', ping: 'b' };
316 | jQuery.ajax(t);
317 | ok( t.url.indexOf('ping') > -1 && t.url.indexOf('zoo') > -1 && t.url.indexOf('foo') > -1 && t.url.indexOf('bar') > -1, "Check extending { zoo: 'a', ping: 'b' }" );
318 |
319 | jQuery.ajaxSettings = tmp;
320 | });
321 |
322 | test("load(String)", function() {
323 | expect(1);
324 | stop(true); // check if load can be called with only url
325 | jQuery('#first').load("data/name.html", start);
326 | });
327 |
328 | test("load('url selector')", function() {
329 | expect(1);
330 | stop(true); // check if load can be called with only url
331 | jQuery('#first').load("data/test3.html div.user", function(){
332 | equals( jQuery(this).children("div").length, 2, "Verify that specific elements were injected" );
333 | start();
334 | });
335 | });
336 |
337 | test("load(String, Function) with ajaxSetup on dataType json, see #2046", function() {
338 | expect(1);
339 | stop();
340 | jQuery.ajaxSetup({ dataType: "json" });
341 | jQuery("#first").ajaxComplete(function (e, xml, s) {
342 | equals( s.dataType, "html", "Verify the load() dataType was html" );
343 | jQuery("#first").unbind("ajaxComplete");
344 | jQuery.ajaxSetup({ dataType: "" });
345 | start();
346 | });
347 | jQuery('#first').load("data/test3.html");
348 | });
349 |
350 | test("load(String, Function) - simple: inject text into DOM", function() {
351 | expect(2);
352 | stop();
353 | jQuery('#first').load(url("data/name.html"), function() {
354 | ok( /^ERROR/.test(jQuery('#first').text()), 'Check if content was injected into the DOM' );
355 | start();
356 | });
357 | });
358 |
359 | test("load(String, Function) - check scripts", function() {
360 | expect(7);
361 | stop();
362 | window.testFoo = undefined;
363 | window.foobar = null;
364 | var verifyEvaluation = function() {
365 | equals( foobar, "bar", 'Check if script src was evaluated after load' );
366 | equals( jQuery('#ap').html(), 'bar', 'Check if script evaluation has modified DOM');
367 | start();
368 | };
369 | jQuery('#first').load(url('data/test.html'), function() {
370 | ok( jQuery('#first').html().match(/^html text/), 'Check content after loading html' );
371 | equals( jQuery('#foo').html(), 'foo', 'Check if script evaluation has modified DOM');
372 | equals( testFoo, "foo", 'Check if script was evaluated after load' );
373 | setTimeout(verifyEvaluation, 600);
374 | });
375 | });
376 |
377 | test("load(String, Function) - check file with only a script tag", function() {
378 | expect(3);
379 | stop();
380 | testFoo = undefined;
381 | jQuery('#first').load(url('data/test2.html'), function() {
382 | equals( jQuery('#foo').html(), 'foo', 'Check if script evaluation has modified DOM');
383 | equals( testFoo, "foo", 'Check if script was evaluated after load' );
384 | start();
385 | });
386 | });
387 |
388 | test("load(String, Object, Function)", function() {
389 | expect(2);
390 | stop();
391 |
392 | jQuery('
').load(url('data/params_html.php'), { foo:3, bar:'ok' }, function() {
393 | var $post = jQuery(this).find('#post');
394 | equals( $post.find('#foo').text(), '3', 'Check if a hash of data is passed correctly');
395 | equals( $post.find('#bar').text(), 'ok', 'Check if a hash of data is passed correctly');
396 | start();
397 | });
398 | });
399 |
400 | test("load(String, String, Function)", function() {
401 | expect(2);
402 | stop();
403 |
404 | jQuery('
').load(url('data/params_html.php'), 'foo=3&bar=ok', function() {
405 | var $get = jQuery(this).find('#get');
406 | equals( $get.find('#foo').text(), '3', 'Check if a string of data is passed correctly');
407 | equals( $get.find('#bar').text(), 'ok', 'Check if a of data is passed correctly');
408 | start();
409 | });
410 | });
411 |
412 | test("jQuery.get(String, Hash, Function) - parse xml and use text() on nodes", function() {
413 | expect(2);
414 | stop();
415 | jQuery.get(url('data/dashboard.xml'), function(xml) {
416 | var content = [];
417 | jQuery('tab', xml).each(function() {
418 | content.push(jQuery(this).text());
419 | });
420 | equals( content[0], 'blabla', 'Check first tab');
421 | equals( content[1], 'blublu', 'Check second tab');
422 | start();
423 | });
424 | });
425 |
426 | test("jQuery.getScript(String, Function) - with callback", function() {
427 | expect(2);
428 | stop();
429 | window.foobar = null;
430 | jQuery.getScript(url("data/test.js"), function() {
431 | equals( foobar, "bar", 'Check if script was evaluated' );
432 | setTimeout(start, 100);
433 | });
434 | });
435 |
436 | test("jQuery.getScript(String, Function) - no callback", function() {
437 | expect(1);
438 | stop(true);
439 | jQuery.getScript(url("data/test.js"), start);
440 | });
441 |
442 | test("jQuery.ajax() - JSONP, Local", function() {
443 | expect(7);
444 |
445 | var count = 0;
446 | function plus(){ if ( ++count == 7 ) start(); }
447 |
448 | stop();
449 |
450 | jQuery.ajax({
451 | url: "data/jsonp.php",
452 | dataType: "jsonp",
453 | success: function(data){
454 | ok( data.data, "JSON results returned (GET, no callback)" );
455 | plus();
456 | },
457 | error: function(data){
458 | ok( false, "Ajax error JSON (GET, no callback)" );
459 | plus();
460 | }
461 | });
462 |
463 | jQuery.ajax({
464 | url: "data/jsonp.php?callback=?",
465 | dataType: "jsonp",
466 | success: function(data){
467 | ok( data.data, "JSON results returned (GET, url callback)" );
468 | plus();
469 | },
470 | error: function(data){
471 | ok( false, "Ajax error JSON (GET, url callback)" );
472 | plus();
473 | }
474 | });
475 |
476 | jQuery.ajax({
477 | url: "data/jsonp.php",
478 | dataType: "jsonp",
479 | data: "callback=?",
480 | success: function(data){
481 | ok( data.data, "JSON results returned (GET, data callback)" );
482 | plus();
483 | },
484 | error: function(data){
485 | ok( false, "Ajax error JSON (GET, data callback)" );
486 | plus();
487 | }
488 | });
489 |
490 | jQuery.ajax({
491 | url: "data/jsonp.php",
492 | dataType: "jsonp",
493 | jsonp: "callback",
494 | success: function(data){
495 | ok( data.data, "JSON results returned (GET, data obj callback)" );
496 | plus();
497 | },
498 | error: function(data){
499 | ok( false, "Ajax error JSON (GET, data obj callback)" );
500 | plus();
501 | }
502 | });
503 |
504 | jQuery.ajax({
505 | type: "POST",
506 | url: "data/jsonp.php",
507 | dataType: "jsonp",
508 | success: function(data){
509 | ok( data.data, "JSON results returned (POST, no callback)" );
510 | plus();
511 | },
512 | error: function(data){
513 | ok( false, "Ajax error JSON (GET, data obj callback)" );
514 | plus();
515 | }
516 | });
517 |
518 | jQuery.ajax({
519 | type: "POST",
520 | url: "data/jsonp.php",
521 | data: "callback=?",
522 | dataType: "jsonp",
523 | success: function(data){
524 | ok( data.data, "JSON results returned (POST, data callback)" );
525 | plus();
526 | },
527 | error: function(data){
528 | ok( false, "Ajax error JSON (POST, data callback)" );
529 | plus();
530 | }
531 | });
532 |
533 | jQuery.ajax({
534 | type: "POST",
535 | url: "data/jsonp.php",
536 | jsonp: "callback",
537 | dataType: "jsonp",
538 | success: function(data){
539 | ok( data.data, "JSON results returned (POST, data obj callback)" );
540 | plus();
541 | },
542 | error: function(data){
543 | ok( false, "Ajax error JSON (POST, data obj callback)" );
544 | plus();
545 | }
546 | });
547 | });
548 |
549 | test("jQuery.ajax() - JSONP, Remote", function() {
550 | expect(4);
551 |
552 | var count = 0;
553 | function plus(){ if ( ++count == 4 ) start(); }
554 |
555 | var base = window.location.href.replace(/\?.*$/, "");
556 |
557 | stop();
558 |
559 | jQuery.ajax({
560 | url: base + "data/jsonp.php",
561 | dataType: "jsonp",
562 | success: function(data){
563 | ok( data.data, "JSON results returned (GET, no callback)" );
564 | plus();
565 | },
566 | error: function(data){
567 | ok( false, "Ajax error JSON (GET, no callback)" );
568 | plus();
569 | }
570 | });
571 |
572 | jQuery.ajax({
573 | url: base + "data/jsonp.php?callback=?",
574 | dataType: "jsonp",
575 | success: function(data){
576 | ok( data.data, "JSON results returned (GET, url callback)" );
577 | plus();
578 | },
579 | error: function(data){
580 | ok( false, "Ajax error JSON (GET, url callback)" );
581 | plus();
582 | }
583 | });
584 |
585 | jQuery.ajax({
586 | url: base + "data/jsonp.php",
587 | dataType: "jsonp",
588 | data: "callback=?",
589 | success: function(data){
590 | ok( data.data, "JSON results returned (GET, data callback)" );
591 | plus();
592 | },
593 | error: function(data){
594 | ok( false, "Ajax error JSON (GET, data callback)" );
595 | plus();
596 | }
597 | });
598 |
599 | jQuery.ajax({
600 | url: base + "data/jsonp.php",
601 | dataType: "jsonp",
602 | jsonp: "callback",
603 | success: function(data){
604 | ok( data.data, "JSON results returned (GET, data obj callback)" );
605 | plus();
606 | },
607 | error: function(data){
608 | ok( false, "Ajax error JSON (GET, data obj callback)" );
609 | plus();
610 | }
611 | });
612 | });
613 |
614 | test("jQuery.ajax() - script, Remote", function() {
615 | expect(2);
616 |
617 | var base = window.location.href.replace(/\?.*$/, "");
618 |
619 | stop();
620 |
621 | window.foobar = null;
622 | jQuery.ajax({
623 | url: base + "data/test.js",
624 | dataType: "script",
625 | success: function(data){
626 | ok( foobar, "Script results returned (GET, no callback)" );
627 | start();
628 | }
629 | });
630 | });
631 |
632 | test("jQuery.ajax() - script, Remote with POST", function() {
633 | expect(3);
634 |
635 | var base = window.location.href.replace(/\?.*$/, "");
636 |
637 | stop();
638 |
639 | window.foobar = null;
640 | jQuery.ajax({
641 | url: base + "data/test.js",
642 | type: "POST",
643 | dataType: "script",
644 | success: function(data, status){
645 | ok( foobar, "Script results returned (GET, no callback)" );
646 | equals( status, "success", "Script results returned (GET, no callback)" );
647 | start();
648 | }
649 | });
650 | });
651 |
652 | test("jQuery.ajax() - script, Remote with scheme-less URL", function() {
653 | expect(2);
654 |
655 | var base = window.location.href.replace(/\?.*$/, "");
656 | base = base.replace(/^.*?\/\//, "//");
657 |
658 | stop();
659 |
660 | window.foobar = null;
661 | jQuery.ajax({
662 | url: base + "data/test.js",
663 | dataType: "script",
664 | success: function(data){
665 | ok( foobar, "Script results returned (GET, no callback)" );
666 | start();
667 | }
668 | });
669 | });
670 |
671 | test("jQuery.getJSON(String, Hash, Function) - JSON array", function() {
672 | expect(4);
673 | stop();
674 | jQuery.getJSON(url("data/json.php"), {json: "array"}, function(json) {
675 | equals( json[0].name, 'John', 'Check JSON: first, name' );
676 | equals( json[0].age, 21, 'Check JSON: first, age' );
677 | equals( json[1].name, 'Peter', 'Check JSON: second, name' );
678 | equals( json[1].age, 25, 'Check JSON: second, age' );
679 | start();
680 | });
681 | });
682 |
683 | test("jQuery.getJSON(String, Function) - JSON object", function() {
684 | expect(2);
685 | stop();
686 | jQuery.getJSON(url("data/json.php"), function(json) {
687 | equals( json.data.lang, 'en', 'Check JSON: lang' );
688 | equals( json.data.length, 25, 'Check JSON: length' );
689 | start();
690 | });
691 | });
692 |
693 | test("jQuery.getJSON(String, Function) - JSON object with absolute url to local content", function() {
694 | expect(2);
695 |
696 | var base = window.location.href.replace(/\?.*$/, "");
697 |
698 | stop();
699 | jQuery.getJSON(url(base + "data/json.php"), function(json) {
700 | equals( json.data.lang, 'en', 'Check JSON: lang' );
701 | equals( json.data.length, 25, 'Check JSON: length' );
702 | start();
703 | });
704 | });
705 |
706 | test("jQuery.post(String, Hash, Function) - simple with xml", function() {
707 | expect(4);
708 | stop();
709 | jQuery.post(url("data/name.php"), {xml: "5-2"}, function(xml){
710 | jQuery('math', xml).each(function() {
711 | equals( jQuery('calculation', this).text(), '5-2', 'Check for XML' );
712 | equals( jQuery('result', this).text(), '3', 'Check for XML' );
713 | });
714 | });
715 |
716 | jQuery.post(url("data/name.php?xml=5-2"), {}, function(xml){
717 | jQuery('math', xml).each(function() {
718 | equals( jQuery('calculation', this).text(), '5-2', 'Check for XML' );
719 | equals( jQuery('result', this).text(), '3', 'Check for XML' );
720 | });
721 | start();
722 | });
723 | });
724 |
725 | test("jQuery.ajaxSetup({timeout: Number}) - with global timeout", function() {
726 | stop();
727 |
728 | var passed = 0;
729 |
730 | jQuery.ajaxSetup({timeout: 1000});
731 |
732 | var pass = function() {
733 | passed++;
734 | if ( passed == 2 ) {
735 | ok( true, 'Check local and global callbacks after timeout' );
736 | jQuery('#main').unbind("ajaxError");
737 | start();
738 | }
739 | };
740 |
741 | var fail = function(a,b,c) {
742 | ok( false, 'Check for timeout failed ' + a + ' ' + b );
743 | start();
744 | };
745 |
746 | jQuery('#main').ajaxError(pass);
747 |
748 | jQuery.ajax({
749 | type: "GET",
750 | url: url("data/name.php?wait=5"),
751 | error: pass,
752 | success: fail
753 | });
754 |
755 | // reset timeout
756 | jQuery.ajaxSetup({timeout: 0});
757 | });
758 |
759 | test("jQuery.ajaxSetup({timeout: Number}) with localtimeout", function() {
760 | stop();
761 | jQuery.ajaxSetup({timeout: 50});
762 |
763 | jQuery.ajax({
764 | type: "GET",
765 | timeout: 5000,
766 | url: url("data/name.php?wait=1"),
767 | error: function() {
768 | ok( false, 'Check for local timeout failed' );
769 | start();
770 | },
771 | success: function() {
772 | ok( true, 'Check for local timeout' );
773 | start();
774 | }
775 | });
776 |
777 | // reset timeout
778 | jQuery.ajaxSetup({timeout: 0});
779 | });
780 |
781 | test("jQuery.ajax - simple get", function() {
782 | expect(1);
783 | stop();
784 | jQuery.ajax({
785 | type: "GET",
786 | url: url("data/name.php?name=foo"),
787 | success: function(msg){
788 | equals( msg, 'bar', 'Check for GET' );
789 | start();
790 | }
791 | });
792 | });
793 |
794 | test("jQuery.ajax - simple post", function() {
795 | expect(1);
796 | stop();
797 | jQuery.ajax({
798 | type: "POST",
799 | url: url("data/name.php"),
800 | data: "name=peter",
801 | success: function(msg){
802 | equals( msg, 'pan', 'Check for POST' );
803 | start();
804 | }
805 | });
806 | });
807 |
808 | test("ajaxSetup()", function() {
809 | expect(1);
810 | stop();
811 | jQuery.ajaxSetup({
812 | url: url("data/name.php?name=foo"),
813 | success: function(msg){
814 | equals( msg, 'bar', 'Check for GET' );
815 | start();
816 | }
817 | });
818 | jQuery.ajax();
819 | });
820 |
821 | test("custom timeout does not set error message when timeout occurs, see #970", function() {
822 | stop();
823 | jQuery.ajax({
824 | url: "data/name.php?wait=10",
825 | timeout: 500,
826 | error: function(request, status) {
827 | ok( status != null, "status shouldn't be null in error handler" );
828 | equals( "timeout", status );
829 | start();
830 | }
831 | });
832 | });
833 |
834 | test("data option: evaluate function values (#2806)", function() {
835 | stop();
836 | jQuery.ajax({
837 | url: "data/echoQuery.php",
838 | data: {
839 | key: function() {
840 | return "value";
841 | }
842 | },
843 | success: function(result) {
844 | equals( result, "key=value" );
845 | start();
846 | }
847 | })
848 | });
849 |
850 | }
851 |
852 | //}
853 |
--------------------------------------------------------------------------------
/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(8);
16 |
17 | var main = jQuery("#main");
18 | isSet( jQuery("div p", main).get(), q("sndp", "en", "sap"), "Basic selector with jQuery object as context" );
19 |
20 | /*
21 | // disabled since this test was doing nothing. i tried to fix it but i'm not sure
22 | // what the expected behavior should even be. FF returns "\n" for the text node
23 | // make sure this is handled
24 | var crlfContainer = jQuery('\r\n
');
25 | var x = crlfContainer.contents().get(0).nodeValue;
26 | equals( x, what???, "Check for \\r and \\n in jQuery()" );
27 | */
28 |
29 | /* // Disabled until we add this functionality in
30 | var pass = true;
31 | try {
32 | jQuery("Testing
").appendTo(document.getElementById("iframe").contentDocument.body);
33 | } catch(e){
34 | pass = false;
35 | }
36 | ok( pass, "jQuery('<tag>') needs optional document parameter to ease cross-frame DOM wrangling, see #968" );*/
37 |
38 | var code = jQuery("
");
39 | equals( code.length, 1, "Correct number of elements generated for code" );
40 | var img = jQuery(" ");
41 | equals( img.length, 1, "Correct number of elements generated for img" );
42 | var div = jQuery("
");
43 | equals( div.length, 4, "Correct number of elements generated for div hr code b" );
44 |
45 | // can actually yield more than one, when iframes are included, the window is an array as well
46 | equals( jQuery(window).length, 1, "Correct number of elements generated for window" );
47 |
48 | equals( jQuery(document).length, 1, "Correct number of elements generated for document" );
49 |
50 | equals( jQuery([1,2,3]).get(1), 2, "Test passing an array to the factory" );
51 |
52 | equals( jQuery(document.body).get(0), jQuery('body').get(0), "Test passing an html node to the factory" );
53 | });
54 |
55 | test("browser", function() {
56 | expect(13);
57 | var browsers = {
58 | //Internet Explorer
59 | "Mozilla/5.0 (Windows; U; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727)": "6.0",
60 | "Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 5.1; .NET CLR 1.1.4322; InfoPath.1; .NET CLR 2.0.50727)": "7.0",
61 | /** Failing #1876
62 | * "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1) ; .NET CLR 2.0.50727; .NET CLR 1.1.4322; .NET CLR 3.0.04506.30)": "7.0",
63 | */
64 | //Browsers with Gecko engine
65 | //Mozilla
66 | "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.12) Gecko/20050915" : "1.7.12",
67 | //Firefox
68 | "Mozilla/5.0 (Macintosh; U; Intel Mac OS X; en-US; rv:1.8.1.3) Gecko/20070309 Firefox/2.0.0.3": "1.8.1.3",
69 | //Netscape
70 | "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.5) Gecko/20070321 Netscape/8.1.3" : "1.7.5",
71 | //Flock
72 | "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.0.11) Gecko/20070321 Firefox/1.5.0.11 Flock/0.7.12" : "1.8.0.11",
73 | //Opera browser
74 | "Opera/9.20 (X11; Linux x86_64; U; en)": "9.20",
75 | "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; en) Opera 9.20" : "9.20",
76 | "Mozilla/5.0 (Windows NT 5.1; U; pl; rv:1.8.0) Gecko/20060728 Firefox/1.5.0 Opera 9.20": "9.20",
77 | //WebKit engine
78 | "Mozilla/5.0 (Macintosh; U; PPC Mac OS X; sv-se) AppleWebKit/418.9 (KHTML, like Gecko) Safari/419.3": "418.9",
79 | "Mozilla/5.0 (Macintosh; U; PPC Mac OS X; en) AppleWebKit/418.8 (KHTML, like Gecko) Safari/419.3" : "418.8",
80 | "Mozilla/5.0 (Macintosh; U; PPC Mac OS X; sv-se) AppleWebKit/312.8 (KHTML, like Gecko) Safari/312.5": "312.8",
81 | //Other user agent string
82 | "Other browser's user agent 1.0":null
83 | };
84 | for (var i in browsers) {
85 | var v = i.toLowerCase().match( /.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/ ); // RegEx from Core jQuery.browser.version check
86 | version = v ? v[1] : null;
87 | equals( version, browsers[i], "Checking UA string" );
88 | }
89 | });
90 |
91 | test("noConflict", function() {
92 | expect(6);
93 |
94 | var $$ = jQuery;
95 |
96 | equals( jQuery, jQuery.noConflict(), "noConflict returned the jQuery object" );
97 | equals( jQuery, $$, "Make sure jQuery wasn't touched." );
98 | equals( $, original$, "Make sure $ was reverted." );
99 |
100 | jQuery = $ = $$;
101 |
102 | equals( jQuery.noConflict(true), $$, "noConflict returned the jQuery object" );
103 | equals( jQuery, originaljQuery, "Make sure jQuery was reverted." );
104 | equals( $, original$, "Make sure $ was reverted." );
105 |
106 | jQuery = $$;
107 | });
108 |
109 | test("isFunction", function() {
110 | expect(21);
111 |
112 | // Make sure that false values return false
113 | ok( !jQuery.isFunction(), "No Value" );
114 | ok( !jQuery.isFunction( null ), "null Value" );
115 | ok( !jQuery.isFunction( undefined ), "undefined Value" );
116 | ok( !jQuery.isFunction( "" ), "Empty String Value" );
117 | ok( !jQuery.isFunction( 0 ), "0 Value" );
118 |
119 | // Check built-ins
120 | // Safari uses "(Internal Function)"
121 | ok( jQuery.isFunction(String), "String Function("+String+")" );
122 | ok( jQuery.isFunction(Array), "Array Function("+Array+")" );
123 | ok( jQuery.isFunction(Object), "Object Function("+Object+")" );
124 | ok( jQuery.isFunction(Function), "Function Function("+Function+")" );
125 |
126 | // When stringified, this could be misinterpreted
127 | var mystr = "function";
128 | ok( !jQuery.isFunction(mystr), "Function String" );
129 |
130 | // When stringified, this could be misinterpreted
131 | var myarr = [ "function" ];
132 | ok( !jQuery.isFunction(myarr), "Function Array" );
133 |
134 | // When stringified, this could be misinterpreted
135 | var myfunction = { "function": "test" };
136 | ok( !jQuery.isFunction(myfunction), "Function Object" );
137 |
138 | // Make sure normal functions still work
139 | var fn = function(){};
140 | ok( jQuery.isFunction(fn), "Normal Function" );
141 |
142 | var obj = document.createElement("object");
143 |
144 | // Firefox says this is a function
145 | ok( !jQuery.isFunction(obj), "Object Element" );
146 |
147 | // IE says this is an object
148 | ok( jQuery.isFunction(obj.getAttribute), "getAttribute Function" );
149 |
150 | var nodes = document.body.childNodes;
151 |
152 | // Safari says this is a function
153 | ok( !jQuery.isFunction(nodes), "childNodes Property" );
154 |
155 | var first = document.body.firstChild;
156 |
157 | // Normal elements are reported ok everywhere
158 | ok( !jQuery.isFunction(first), "A normal DOM Element" );
159 |
160 | var input = document.createElement("input");
161 | input.type = "text";
162 | document.body.appendChild( input );
163 |
164 | // IE says this is an object
165 | ok( jQuery.isFunction(input.focus), "A default function property" );
166 |
167 | document.body.removeChild( input );
168 |
169 | var a = document.createElement("a");
170 | a.href = "some-function";
171 | document.body.appendChild( a );
172 |
173 | // This serializes with the word 'function' in it
174 | ok( !jQuery.isFunction(a), "Anchor Element" );
175 |
176 | document.body.removeChild( a );
177 |
178 | // Recursive function calls have lengths and array-like properties
179 | function callme(callback){
180 | function fn(response){
181 | callback(response);
182 | }
183 |
184 | ok( jQuery.isFunction(fn), "Recursive Function Call" );
185 |
186 | fn({ some: "data" });
187 | };
188 |
189 | callme(function(){
190 | callme(function(){});
191 | });
192 | });
193 |
194 | var foo = false;
195 |
196 | test("jQuery('html')", function() {
197 | expect(6);
198 |
199 | reset();
200 | foo = false;
201 | var s = jQuery("")[0];
202 | ok( s, "Creating a script" );
203 | ok( !foo, "Make sure the script wasn't executed prematurely" );
204 | jQuery("body").append(s);
205 | ok( foo, "Executing a scripts contents in the right context" );
206 |
207 | reset();
208 | ok( jQuery(" ")[0], "Creating a link" );
209 |
210 | reset();
211 |
212 | var j = jQuery("hi there ");
213 | ok( j.length >= 2, "Check node,textnode,comment creation (some browsers delete comments)" );
214 |
215 | ok( !jQuery("test ")[0].selected, "Make sure that options are auto-selected #2050" );
216 | });
217 |
218 | test("jQuery('html', context)", function() {
219 | expect(1);
220 |
221 | var $div = jQuery("
");
222 | var $span = jQuery(" ", $div);
223 | equals($span.length, 1, "Verify a span created with a div context works, #1763");
224 | });
225 |
226 | if ( !isLocal ) {
227 | test("jQuery(selector, xml).text(str) - Loaded via XML document", function() {
228 | expect(2);
229 | stop();
230 | jQuery.get('data/dashboard.xml', function(xml) {
231 | // tests for #1419 where IE was a problem
232 | equals( jQuery("tab:first", xml).text(), "blabla", "Verify initial text correct" );
233 | jQuery("tab:first", xml).text("newtext");
234 | equals( jQuery("tab:first", xml).text(), "newtext", "Verify new text correct" );
235 | start();
236 | });
237 | });
238 | }
239 |
240 | test("length", function() {
241 | expect(1);
242 | equals( jQuery("p").length, 6, "Get Number of Elements Found" );
243 | });
244 |
245 | test("size()", function() {
246 | expect(1);
247 | equals( jQuery("p").size(), 6, "Get Number of Elements Found" );
248 | });
249 |
250 | test("get()", function() {
251 | expect(1);
252 | isSet( jQuery("p").get(), q("firstp","ap","sndp","en","sap","first"), "Get All Elements" );
253 | });
254 |
255 | test("get(Number)", function() {
256 | expect(1);
257 | equals( jQuery("p").get(0), document.getElementById("firstp"), "Get A Single Element" );
258 | });
259 |
260 | test("add(String|Element|Array|undefined)", function() {
261 | expect(12);
262 | isSet( jQuery("#sndp").add("#en").add("#sap").get(), q("sndp", "en", "sap"), "Check elements from document" );
263 | isSet( jQuery("#sndp").add( jQuery("#en")[0] ).add( jQuery("#sap") ).get(), q("sndp", "en", "sap"), "Check elements from document" );
264 | ok( jQuery([]).add(jQuery("#form")[0].elements).length >= 13, "Check elements from array" );
265 |
266 | // For the time being, we're discontinuing support for jQuery(form.elements) since it's ambiguous in IE
267 | // use jQuery([]).add(form.elements) instead.
268 | //equals( jQuery([]).add(jQuery("#form")[0].elements).length, jQuery(jQuery("#form")[0].elements).length, "Array in constructor must equals array in add()" );
269 |
270 | var x = jQuery([]).add(jQuery("xxx
")).add(jQuery("xxx
"));
271 | equals( x[0].id, "x1", "Check on-the-fly element1" );
272 | equals( x[1].id, "x2", "Check on-the-fly element2" );
273 |
274 | var x = jQuery([]).add("xxx
").add("xxx
");
275 | equals( x[0].id, "x1", "Check on-the-fly element1" );
276 | equals( x[1].id, "x2", "Check on-the-fly element2" );
277 |
278 | var notDefined;
279 | equals( jQuery([]).add(notDefined).length, 0, "Check that undefined adds nothing" );
280 |
281 | // Added after #2811
282 | equals( jQuery([]).add([window,document,document.body,document]).length, 3, "Pass an array" );
283 | equals( jQuery(document).add(document).length, 1, "Check duplicated elements" );
284 | equals( jQuery(window).add(window).length, 1, "Check duplicated elements using the window" );
285 | ok( jQuery([]).add( document.getElementById('form') ).length >= 13, "Add a form (adds the elements)" );
286 | });
287 |
288 | test("each(Function)", function() {
289 | expect(1);
290 | var div = jQuery("div");
291 | div.each(function(){this.foo = 'zoo';});
292 | var pass = true;
293 | for ( var i = 0; i < div.size(); i++ ) {
294 | if ( div.get(i).foo != "zoo" ) pass = false;
295 | }
296 | ok( pass, "Execute a function, Relative" );
297 | });
298 |
299 | test("index(Object)", function() {
300 | expect(10);
301 |
302 | var elements = jQuery([window, document]),
303 | inputElements = jQuery('#radio1,#radio2,#check1,#check2');
304 |
305 | equals( elements.index(window), 0, "Check for index of elements" );
306 | equals( elements.index(document), 1, "Check for index of elements" );
307 | equals( inputElements.index(document.getElementById('radio1')), 0, "Check for index of elements" );
308 | equals( inputElements.index(document.getElementById('radio2')), 1, "Check for index of elements" );
309 | equals( inputElements.index(document.getElementById('check1')), 2, "Check for index of elements" );
310 | equals( inputElements.index(document.getElementById('check2')), 3, "Check for index of elements" );
311 | equals( inputElements.index(window), -1, "Check for not found index" );
312 | equals( inputElements.index(document), -1, "Check for not found index" );
313 |
314 | // enabled since [5500]
315 | equals( elements.index( elements ), 0, "Pass in a jQuery object" );
316 | equals( elements.index( elements.eq(1) ), 1, "Pass in a jQuery object" );
317 | });
318 |
319 | test("attr(String)", function() {
320 | expect(26);
321 | equals( jQuery('#text1').attr('value'), "Test", 'Check for value attribute' );
322 | equals( jQuery('#text1').attr('value', "Test2").attr('defaultValue'), "Test", 'Check for defaultValue attribute' );
323 | equals( jQuery('#text1').attr('type'), "text", 'Check for type attribute' );
324 | equals( jQuery('#radio1').attr('type'), "radio", 'Check for type attribute' );
325 | equals( jQuery('#check1').attr('type'), "checkbox", 'Check for type attribute' );
326 | equals( jQuery('#simon1').attr('rel'), "bookmark", 'Check for rel attribute' );
327 | equals( jQuery('#google').attr('title'), "Google!", 'Check for title attribute' );
328 | equals( jQuery('#mark').attr('hreflang'), "en", 'Check for hreflang attribute' );
329 | equals( jQuery('#en').attr('lang'), "en", 'Check for lang attribute' );
330 | equals( jQuery('#simon').attr('class'), "blog link", 'Check for class attribute' );
331 | equals( jQuery('#name').attr('name'), "name", 'Check for name attribute' );
332 | equals( jQuery('#text1').attr('name'), "action", 'Check for name attribute' );
333 | ok( jQuery('#form').attr('action').indexOf("formaction") >= 0, 'Check for action attribute' );
334 | equals( jQuery('#text1').attr('maxlength'), '30', 'Check for maxlength attribute' );
335 | equals( jQuery('#text1').attr('maxLength'), '30', 'Check for maxLength attribute' );
336 | equals( jQuery('#area1').attr('maxLength'), '30', 'Check for maxLength attribute' );
337 | equals( jQuery('#select2').attr('selectedIndex'), 3, 'Check for selectedIndex attribute' );
338 | equals( jQuery('#foo').attr('nodeName'), 'DIV', 'Check for nodeName attribute' );
339 | equals( jQuery('#foo').attr('tagName'), 'DIV', 'Check for tagName attribute' );
340 |
341 | jQuery(' ').attr('href', '#5').appendTo('#main'); // using innerHTML in IE causes href attribute to be serialized to the full path
342 | equals( jQuery('#tAnchor5').attr('href'), "#5", 'Check for non-absolute href (an anchor)' );
343 |
344 |
345 | // Related to [5574] and [5683]
346 | var body = document.body, $body = jQuery(body);
347 |
348 | ok( $body.attr('foo') === undefined, 'Make sure that a non existent attribute returns undefined' );
349 | ok( $body.attr('nextSibling') === null, 'Make sure a null expando returns null' );
350 |
351 | body.setAttribute('foo', 'baz');
352 | equals( $body.attr('foo'), 'baz', 'Make sure the dom attribute is retrieved when no expando is found' );
353 |
354 | body.foo = 'bar';
355 | equals( $body.attr('foo'), 'bar', 'Make sure the expando is preferred over the dom attribute' );
356 |
357 | $body.attr('foo','cool');
358 | equals( $body.attr('foo'), 'cool', 'Make sure that setting works well when both expando and dom attribute are available' );
359 |
360 | body.foo = undefined;
361 | ok( $body.attr('foo') === undefined, 'Make sure the expando is preferred over the dom attribute, even if undefined' );
362 |
363 | body.removeAttribute('foo'); // Cleanup
364 | });
365 |
366 | if ( !isLocal ) {
367 | test("attr(String) in XML Files", function() {
368 | expect(2);
369 | stop();
370 | jQuery.get("data/dashboard.xml", function(xml) {
371 | equals( jQuery("locations", xml).attr("class"), "foo", "Check class attribute in XML document" );
372 | equals( jQuery("location", xml).attr("for"), "bar", "Check for attribute in XML document" );
373 | start();
374 | });
375 | });
376 | }
377 |
378 | test("attr(String, Function)", function() {
379 | expect(2);
380 | equals( jQuery('#text1').attr('value', function() { return this.id })[0].value, "text1", "Set value from id" );
381 | equals( jQuery('#text1').attr('title', function(i) { return i }).attr('title'), "0", "Set value with an index");
382 | });
383 |
384 | test("attr(Hash)", function() {
385 | expect(1);
386 | var pass = true;
387 | jQuery("div").attr({foo: 'baz', zoo: 'ping'}).each(function(){
388 | if ( this.getAttribute('foo') != "baz" && this.getAttribute('zoo') != "ping" ) pass = false;
389 | });
390 | ok( pass, "Set Multiple Attributes" );
391 | });
392 |
393 | test("attr(String, Object)", function() {
394 | expect(17);
395 | var div = jQuery("div").attr("foo", "bar");
396 | fail = false;
397 | for ( var i = 0; i < div.size(); i++ ) {
398 | if ( div.get(i).getAttribute('foo') != "bar" ){
399 | fail = i;
400 | break;
401 | }
402 | }
403 | equals( fail, false, "Set Attribute, the #"+fail+" element didn't get the attribute 'foo'" );
404 |
405 | ok( jQuery("#foo").attr({"width": null}), "Try to set an attribute to nothing" );
406 |
407 | jQuery("#name").attr('name', 'something');
408 | equals( jQuery("#name").attr('name'), 'something', 'Set name attribute' );
409 | jQuery("#check2").attr('checked', true);
410 | equals( document.getElementById('check2').checked, true, 'Set checked attribute' );
411 | jQuery("#check2").attr('checked', false);
412 | equals( document.getElementById('check2').checked, false, 'Set checked attribute' );
413 | jQuery("#text1").attr('readonly', true);
414 | equals( document.getElementById('text1').readOnly, true, 'Set readonly attribute' );
415 | jQuery("#text1").attr('readonly', false);
416 | equals( document.getElementById('text1').readOnly, false, 'Set readonly attribute' );
417 | jQuery("#name").attr('maxlength', '5');
418 | equals( document.getElementById('name').maxLength, '5', 'Set maxlength attribute' );
419 | jQuery("#name").attr('maxLength', '10');
420 | equals( document.getElementById('name').maxLength, '10', 'Set maxlength attribute' );
421 |
422 | // for #1070
423 | jQuery("#name").attr('someAttr', '0');
424 | equals( jQuery("#name").attr('someAttr'), '0', 'Set attribute to a string of "0"' );
425 | jQuery("#name").attr('someAttr', 0);
426 | equals( jQuery("#name").attr('someAttr'), 0, 'Set attribute to the number 0' );
427 | jQuery("#name").attr('someAttr', 1);
428 | equals( jQuery("#name").attr('someAttr'), 1, 'Set attribute to the number 1' );
429 |
430 | // using contents will get comments regular, text, and comment nodes
431 | var j = jQuery("#nonnodes").contents();
432 |
433 | j.attr("name", "attrvalue");
434 | equals( j.attr("name"), "attrvalue", "Check node,textnode,comment for attr" );
435 | j.removeAttr("name");
436 |
437 | reset();
438 |
439 | var type = jQuery("#check2").attr('type');
440 | var thrown = false;
441 | try {
442 | jQuery("#check2").attr('type','hidden');
443 | } catch(e) {
444 | thrown = true;
445 | }
446 | ok( thrown, "Exception thrown when trying to change type property" );
447 | equals( type, jQuery("#check2").attr('type'), "Verify that you can't change the type of an input element" );
448 |
449 | var check = document.createElement("input");
450 | var thrown = true;
451 | try {
452 | jQuery(check).attr('type','checkbox');
453 | } catch(e) {
454 | thrown = false;
455 | }
456 | ok( thrown, "Exception thrown when trying to change type property" );
457 | equals( "checkbox", jQuery(check).attr('type'), "Verify that you can change the type of an input element that isn't in the DOM" );
458 | });
459 |
460 | if ( !isLocal ) {
461 | test("attr(String, Object) - Loaded via XML document", function() {
462 | expect(2);
463 | stop();
464 | jQuery.get('data/dashboard.xml', function(xml) {
465 | var titles = [];
466 | jQuery('tab', xml).each(function() {
467 | titles.push(jQuery(this).attr('title'));
468 | });
469 | equals( titles[0], 'Location', 'attr() in XML context: Check first title' );
470 | equals( titles[1], 'Users', 'attr() in XML context: Check second title' );
471 | start();
472 | });
473 | });
474 | }
475 |
476 | test("css(String|Hash)", function() {
477 | expect(19);
478 |
479 | equals( jQuery('#main').css("display"), 'none', 'Check for css property "display"');
480 |
481 | ok( jQuery('#foo').is(':visible'), 'Modifying CSS display: Assert element is visible');
482 | jQuery('#foo').css({display: 'none'});
483 | ok( !jQuery('#foo').is(':visible'), 'Modified CSS display: Assert element is hidden');
484 | jQuery('#foo').css({display: 'block'});
485 | ok( jQuery('#foo').is(':visible'), 'Modified CSS display: Assert element is visible');
486 |
487 | jQuery('#floatTest').css({styleFloat: 'right'});
488 | equals( jQuery('#floatTest').css('styleFloat'), 'right', 'Modified CSS float using "styleFloat": Assert float is right');
489 | jQuery('#floatTest').css({cssFloat: 'left'});
490 | equals( jQuery('#floatTest').css('cssFloat'), 'left', 'Modified CSS float using "cssFloat": Assert float is left');
491 | jQuery('#floatTest').css({'float': 'right'});
492 | equals( jQuery('#floatTest').css('float'), 'right', 'Modified CSS float using "float": Assert float is right');
493 | jQuery('#floatTest').css({'font-size': '30px'});
494 | equals( jQuery('#floatTest').css('font-size'), '30px', 'Modified CSS font-size: Assert font-size is 30px');
495 |
496 | jQuery.each("0,0.25,0.5,0.75,1".split(','), function(i, n) {
497 | jQuery('#foo').css({opacity: n});
498 | equals( jQuery('#foo').css('opacity'), parseFloat(n), "Assert opacity is " + parseFloat(n) + " as a String" );
499 | jQuery('#foo').css({opacity: parseFloat(n)});
500 | equals( jQuery('#foo').css('opacity'), parseFloat(n), "Assert opacity is " + parseFloat(n) + " as a Number" );
501 | });
502 | jQuery('#foo').css({opacity: ''});
503 | equals( jQuery('#foo').css('opacity'), '1', "Assert opacity is 1 when set to an empty String" );
504 | });
505 |
506 | test("css(String, Object)", function() {
507 | expect(21);
508 | ok( jQuery('#foo').is(':visible'), 'Modifying CSS display: Assert element is visible');
509 | jQuery('#foo').css('display', 'none');
510 | ok( !jQuery('#foo').is(':visible'), 'Modified CSS display: Assert element is hidden');
511 | jQuery('#foo').css('display', 'block');
512 | ok( jQuery('#foo').is(':visible'), 'Modified CSS display: Assert element is visible');
513 |
514 | jQuery('#floatTest').css('styleFloat', 'left');
515 | equals( jQuery('#floatTest').css('styleFloat'), 'left', 'Modified CSS float using "styleFloat": Assert float is left');
516 | jQuery('#floatTest').css('cssFloat', 'right');
517 | equals( jQuery('#floatTest').css('cssFloat'), 'right', 'Modified CSS float using "cssFloat": Assert float is right');
518 | jQuery('#floatTest').css('float', 'left');
519 | equals( jQuery('#floatTest').css('float'), 'left', 'Modified CSS float using "float": Assert float is left');
520 | jQuery('#floatTest').css('font-size', '20px');
521 | equals( jQuery('#floatTest').css('font-size'), '20px', 'Modified CSS font-size: Assert font-size is 20px');
522 |
523 | jQuery.each("0,0.25,0.5,0.75,1".split(','), function(i, n) {
524 | jQuery('#foo').css('opacity', n);
525 | equals( jQuery('#foo').css('opacity'), parseFloat(n), "Assert opacity is " + parseFloat(n) + " as a String" );
526 | jQuery('#foo').css('opacity', parseFloat(n));
527 | equals( jQuery('#foo').css('opacity'), parseFloat(n), "Assert opacity is " + parseFloat(n) + " as a Number" );
528 | });
529 | jQuery('#foo').css('opacity', '');
530 | equals( jQuery('#foo').css('opacity'), '1', "Assert opacity is 1 when set to an empty String" );
531 | // for #1438, IE throws JS error when filter exists but doesn't have opacity in it
532 | if (jQuery.browser.msie) {
533 | jQuery('#foo').css("filter", "progid:DXImageTransform.Microsoft.Chroma(color='red');");
534 | }
535 | equals( jQuery('#foo').css('opacity'), '1', "Assert opacity is 1 when a different filter is set in IE, #1438" );
536 |
537 | // using contents will get comments regular, text, and comment nodes
538 | var j = jQuery("#nonnodes").contents();
539 | j.css("padding-left", "1px");
540 | equals( j.css("padding-left"), "1px", "Check node,textnode,comment css works" );
541 |
542 | // opera sometimes doesn't update 'display' correctly, see #2037
543 | jQuery("#t2037")[0].innerHTML = jQuery("#t2037")[0].innerHTML
544 | equals( jQuery("#t2037 .hidden").css("display"), "none", "Make sure browser thinks it is hidden" );
545 | });
546 |
547 | test("jQuery.css(elem, 'height') doesn't clear radio buttons (bug #1095)", function () {
548 | expect(4);
549 |
550 | var $checkedtest = jQuery("#checkedtest");
551 | // IE6 was clearing "checked" in jQuery.css(elem, "height");
552 | jQuery.css($checkedtest[0], "height");
553 | ok( !! jQuery(":radio:first", $checkedtest).attr("checked"), "Check first radio still checked." );
554 | ok( ! jQuery(":radio:last", $checkedtest).attr("checked"), "Check last radio still NOT checked." );
555 | ok( !! jQuery(":checkbox:first", $checkedtest).attr("checked"), "Check first checkbox still checked." );
556 | ok( ! jQuery(":checkbox:last", $checkedtest).attr("checked"), "Check last checkbox still NOT checked." );
557 | });
558 |
559 | test("width()", function() {
560 | expect(9);
561 |
562 | var $div = jQuery("#nothiddendiv");
563 | $div.width(30);
564 | equals($div.width(), 30, "Test set to 30 correctly");
565 | $div.width(-1); // handle negative numbers by ignoring #1599
566 | equals($div.width(), 30, "Test negative width ignored");
567 | $div.css("padding", "20px");
568 | equals($div.width(), 30, "Test padding specified with pixels");
569 | $div.css("border", "2px solid #fff");
570 | equals($div.width(), 30, "Test border specified with pixels");
571 | $div.css("padding", "2em");
572 | equals($div.width(), 30, "Test padding specified with ems");
573 | $div.css("border", "1em solid #fff");
574 | equals($div.width(), 30, "Test border specified with ems");
575 | $div.css("padding", "2%");
576 | equals($div.width(), 30, "Test padding specified with percent");
577 | $div.hide();
578 | equals($div.width(), 30, "Test hidden div");
579 |
580 | $div.css({ display: "", border: "", padding: "" });
581 |
582 | jQuery("#nothiddendivchild").css({ padding: "3px", border: "2px solid #fff" });
583 | equals(jQuery("#nothiddendivchild").width(), 20, "Test child width with border and padding");
584 | jQuery("#nothiddendiv, #nothiddendivchild").css({ border: "", padding: "", width: "" });
585 | });
586 |
587 | test("height()", function() {
588 | expect(8);
589 |
590 | var $div = jQuery("#nothiddendiv");
591 | $div.height(30);
592 | equals($div.height(), 30, "Test set to 30 correctly");
593 | $div.height(-1); // handle negative numbers by ignoring #1599
594 | equals($div.height(), 30, "Test negative height ignored");
595 | $div.css("padding", "20px");
596 | equals($div.height(), 30, "Test padding specified with pixels");
597 | $div.css("border", "2px solid #fff");
598 | equals($div.height(), 30, "Test border specified with pixels");
599 | $div.css("padding", "2em");
600 | equals($div.height(), 30, "Test padding specified with ems");
601 | $div.css("border", "1em solid #fff");
602 | equals($div.height(), 30, "Test border specified with ems");
603 | $div.css("padding", "2%");
604 | equals($div.height(), 30, "Test padding specified with percent");
605 | $div.hide();
606 | equals($div.height(), 30, "Test hidden div");
607 |
608 | $div.css({ display: "", border: "", padding: "", height: "1px" });
609 | });
610 |
611 | test("text()", function() {
612 | expect(1);
613 | var expected = "This link has class=\"blog\": Simon Willison's Weblog";
614 | equals( jQuery('#sap').text(), expected, 'Check for merged text of more then one element.' );
615 | });
616 |
617 | test("wrap(String|Element)", function() {
618 | expect(8);
619 | var defaultText = 'Try them out:'
620 | var result = jQuery('#first').wrap('
').text();
621 | equals( defaultText, result, 'Check for wrapping of on-the-fly html' );
622 | ok( jQuery('#first').parent().parent().is('.red'), 'Check if wrapper has class "red"' );
623 |
624 | reset();
625 | var defaultText = 'Try them out:'
626 | var result = jQuery('#first').wrap(document.getElementById('empty')).parent();
627 | ok( result.is('ol'), 'Check for element wrapping' );
628 | equals( result.text(), defaultText, 'Check for element wrapping' );
629 |
630 | reset();
631 | jQuery('#check1').click(function() {
632 | var checkbox = this;
633 | ok( checkbox.checked, "Checkbox's state is erased after wrap() action, see #769" );
634 | jQuery(checkbox).wrap( '
' );
635 | ok( checkbox.checked, "Checkbox's state is erased after wrap() action, see #769" );
636 | }).click();
637 |
638 | // using contents will get comments regular, text, and comment nodes
639 | var j = jQuery("#nonnodes").contents();
640 | j.wrap(" ");
641 | equals( jQuery("#nonnodes > i").length, 3, "Check node,textnode,comment wraps ok" );
642 | equals( jQuery("#nonnodes > i").text(), j.text() + j[1].nodeValue, "Check node,textnode,comment wraps doesn't hurt text" );
643 | });
644 |
645 | test("wrapAll(String|Element)", function() {
646 | expect(8);
647 | var prev = jQuery("#first")[0].previousSibling;
648 | var p = jQuery("#first")[0].parentNode;
649 | var result = jQuery('#first,#firstp').wrapAll('');
650 | equals( result.parent().length, 1, 'Check for wrapping of on-the-fly html' );
651 | ok( jQuery('#first').parent().parent().is('.red'), 'Check if wrapper has class "red"' );
652 | ok( jQuery('#firstp').parent().parent().is('.red'), 'Check if wrapper has class "red"' );
653 | equals( jQuery("#first").parent().parent()[0].previousSibling, prev, "Correct Previous Sibling" );
654 | equals( jQuery("#first").parent().parent()[0].parentNode, p, "Correct Parent" );
655 |
656 | reset();
657 | var prev = jQuery("#first")[0].previousSibling;
658 | var p = jQuery("#first")[0].parentNode;
659 | var result = jQuery('#first,#firstp').wrapAll(document.getElementById('empty'));
660 | equals( jQuery("#first").parent()[0], jQuery("#firstp").parent()[0], "Same Parent" );
661 | equals( jQuery("#first").parent()[0].previousSibling, prev, "Correct Previous Sibling" );
662 | equals( jQuery("#first").parent()[0].parentNode, p, "Correct Parent" );
663 | });
664 |
665 | test("wrapInner(String|Element)", function() {
666 | expect(6);
667 | var num = jQuery("#first").children().length;
668 | var result = jQuery('#first').wrapInner('');
669 | equals( jQuery("#first").children().length, 1, "Only one child" );
670 | ok( jQuery("#first").children().is(".red"), "Verify Right Element" );
671 | equals( jQuery("#first").children().children().children().length, num, "Verify Elements Intact" );
672 |
673 | reset();
674 | var num = jQuery("#first").children().length;
675 | var result = jQuery('#first').wrapInner(document.getElementById('empty'));
676 | equals( jQuery("#first").children().length, 1, "Only one child" );
677 | ok( jQuery("#first").children().is("#empty"), "Verify Right Element" );
678 | equals( jQuery("#first").children().children().length, num, "Verify Elements Intact" );
679 | });
680 |
681 | test("append(String|Element|Array<Element>|jQuery)", function() {
682 | expect(21);
683 | var defaultText = 'Try them out:'
684 | var result = jQuery('#first').append('buga ');
685 | equals( result.text(), defaultText + 'buga', 'Check if text appending works' );
686 | equals( jQuery('#select3').append('Append Test ').find('option:last-child').attr('value'), 'appendTest', 'Appending html options to select element');
687 |
688 | reset();
689 | var expected = "This link has class=\"blog\": Simon Willison's WeblogTry them out:";
690 | jQuery('#sap').append(document.getElementById('first'));
691 | equals( expected, jQuery('#sap').text(), "Check for appending of element" );
692 |
693 | reset();
694 | expected = "This link has class=\"blog\": Simon Willison's WeblogTry them out:Yahoo";
695 | jQuery('#sap').append([document.getElementById('first'), document.getElementById('yahoo')]);
696 | equals( expected, jQuery('#sap').text(), "Check for appending of array of elements" );
697 |
698 | reset();
699 | expected = "This link has class=\"blog\": Simon Willison's WeblogTry them out:Yahoo";
700 | jQuery('#sap').append(jQuery("#first, #yahoo"));
701 | equals( expected, jQuery('#sap').text(), "Check for appending of jQuery object" );
702 |
703 | reset();
704 | jQuery("#sap").append( 5 );
705 | ok( jQuery("#sap")[0].innerHTML.match( /5$/ ), "Check for appending a number" );
706 |
707 | reset();
708 | jQuery("#sap").append( " text with spaces " );
709 | ok( jQuery("#sap")[0].innerHTML.match(/ text with spaces $/), "Check for appending text with spaces" );
710 |
711 | reset();
712 | ok( jQuery("#sap").append([]), "Check for appending an empty array." );
713 | ok( jQuery("#sap").append(""), "Check for appending an empty string." );
714 | ok( jQuery("#sap").append(document.getElementsByTagName("foo")), "Check for appending an empty nodelist." );
715 |
716 | reset();
717 | jQuery("#sap").append(document.getElementById('form'));
718 | equals( jQuery("#sap>form").size(), 1, "Check for appending a form" ); // Bug #910
719 |
720 | reset();
721 | var pass = true;
722 | try {
723 | jQuery( jQuery("#iframe")[0].contentWindow.document.body ).append("test
");
724 | } catch(e) {
725 | pass = false;
726 | }
727 |
728 | ok( pass, "Test for appending a DOM node to the contents of an IFrame" );
729 |
730 | reset();
731 | jQuery(' ').appendTo('#form').append('test ');
732 | t( 'Append legend', '#legend', ['legend'] );
733 |
734 | reset();
735 | jQuery('#select1').append('Test ');
736 | equals( jQuery('#select1 option:last').text(), "Test", "Appending <OPTION> (all caps)" );
737 |
738 | jQuery('#table').append(' ');
739 | ok( jQuery('#table colgroup').length, "Append colgroup" );
740 |
741 | jQuery('#table colgroup').append(' ');
742 | ok( jQuery('#table colgroup col').length, "Append col" );
743 |
744 | reset();
745 | jQuery('#table').append(' ');
746 | ok( jQuery('#table caption').length, "Append caption" );
747 |
748 | reset();
749 | jQuery('form:last')
750 | .append(' ')
751 | .append('Test ');
752 |
753 | t( "Append Select", "#appendSelect1, #appendSelect2", ["appendSelect1", "appendSelect2"] );
754 |
755 | // using contents will get comments regular, text, and comment nodes
756 | var j = jQuery("#nonnodes").contents();
757 | var d = jQuery("
").appendTo("#nonnodes").append(j);
758 | equals( jQuery("#nonnodes").length, 1, "Check node,textnode,comment append moved leaving just the div" );
759 | ok( d.contents().length >= 2, "Check node,textnode,comment append works" );
760 | d.contents().appendTo("#nonnodes");
761 | d.remove();
762 | ok( jQuery("#nonnodes").contents().length >= 2, "Check node,textnode,comment append cleanup worked" );
763 | });
764 |
765 | test("appendTo(String|Element|Array<Element>|jQuery)", function() {
766 | expect(6);
767 | var defaultText = 'Try them out:'
768 | jQuery('buga ').appendTo('#first');
769 | equals( jQuery("#first").text(), defaultText + 'buga', 'Check if text appending works' );
770 | equals( jQuery('Append Test ').appendTo('#select3').parent().find('option:last-child').attr('value'), 'appendTest', 'Appending html options to select element');
771 |
772 | reset();
773 | var expected = "This link has class=\"blog\": Simon Willison's WeblogTry them out:";
774 | jQuery(document.getElementById('first')).appendTo('#sap');
775 | equals( expected, jQuery('#sap').text(), "Check for appending of element" );
776 |
777 | reset();
778 | expected = "This link has class=\"blog\": Simon Willison's WeblogTry them out:Yahoo";
779 | jQuery([document.getElementById('first'), document.getElementById('yahoo')]).appendTo('#sap');
780 | equals( expected, jQuery('#sap').text(), "Check for appending of array of elements" );
781 |
782 | reset();
783 | expected = "This link has class=\"blog\": Simon Willison's WeblogTry them out:Yahoo";
784 | jQuery("#first, #yahoo").appendTo('#sap');
785 | equals( expected, jQuery('#sap').text(), "Check for appending of jQuery object" );
786 |
787 | reset();
788 | jQuery('#select1').appendTo('#foo');
789 | t( 'Append select', '#foo select', ['select1'] );
790 | });
791 |
792 | test("prepend(String|Element|Array<Element>|jQuery)", function() {
793 | expect(5);
794 | var defaultText = 'Try them out:'
795 | var result = jQuery('#first').prepend('buga ');
796 | equals( result.text(), 'buga' + defaultText, 'Check if text prepending works' );
797 | equals( jQuery('#select3').prepend('Prepend Test ').find('option:first-child').attr('value'), 'prependTest', 'Prepending html options to select element');
798 |
799 | reset();
800 | var expected = "Try them out:This link has class=\"blog\": Simon Willison's Weblog";
801 | jQuery('#sap').prepend(document.getElementById('first'));
802 | equals( expected, jQuery('#sap').text(), "Check for prepending of element" );
803 |
804 | reset();
805 | expected = "Try them out:YahooThis link has class=\"blog\": Simon Willison's Weblog";
806 | jQuery('#sap').prepend([document.getElementById('first'), document.getElementById('yahoo')]);
807 | equals( expected, jQuery('#sap').text(), "Check for prepending of array of elements" );
808 |
809 | reset();
810 | expected = "Try them out:YahooThis link has class=\"blog\": Simon Willison's Weblog";
811 | jQuery('#sap').prepend(jQuery("#first, #yahoo"));
812 | equals( expected, jQuery('#sap').text(), "Check for prepending of jQuery object" );
813 | });
814 |
815 | test("prependTo(String|Element|Array<Element>|jQuery)", function() {
816 | expect(6);
817 | var defaultText = 'Try them out:'
818 | jQuery('buga ').prependTo('#first');
819 | equals( jQuery('#first').text(), 'buga' + defaultText, 'Check if text prepending works' );
820 | equals( jQuery('Prepend Test ').prependTo('#select3').parent().find('option:first-child').attr('value'), 'prependTest', 'Prepending html options to select element');
821 |
822 | reset();
823 | var expected = "Try them out:This link has class=\"blog\": Simon Willison's Weblog";
824 | jQuery(document.getElementById('first')).prependTo('#sap');
825 | equals( expected, jQuery('#sap').text(), "Check for prepending of element" );
826 |
827 | reset();
828 | expected = "Try them out:YahooThis link has class=\"blog\": Simon Willison's Weblog";
829 | jQuery([document.getElementById('yahoo'), document.getElementById('first')]).prependTo('#sap');
830 | equals( expected, jQuery('#sap').text(), "Check for prepending of array of elements" );
831 |
832 | reset();
833 | expected = "Try them out:YahooThis link has class=\"blog\": Simon Willison's Weblog";
834 | jQuery("#yahoo, #first").prependTo('#sap');
835 | equals( expected, jQuery('#sap').text(), "Check for prepending of jQuery object" );
836 |
837 | reset();
838 | jQuery(' ').prependTo('form:last');
839 | jQuery('Test ').prependTo('form:last');
840 |
841 | t( "Prepend Select", "#prependSelect1, #prependSelect2", ["prependSelect1", "prependSelect2"] );
842 | });
843 |
844 | test("before(String|Element|Array<Element>|jQuery)", function() {
845 | expect(4);
846 | var expected = 'This is a normal link: bugaYahoo';
847 | jQuery('#yahoo').before('buga ');
848 | equals( expected, jQuery('#en').text(), 'Insert String before' );
849 |
850 | reset();
851 | expected = "This is a normal link: Try them out:Yahoo";
852 | jQuery('#yahoo').before(document.getElementById('first'));
853 | equals( expected, jQuery('#en').text(), "Insert element before" );
854 |
855 | reset();
856 | expected = "This is a normal link: Try them out:diveintomarkYahoo";
857 | jQuery('#yahoo').before([document.getElementById('first'), document.getElementById('mark')]);
858 | equals( expected, jQuery('#en').text(), "Insert array of elements before" );
859 |
860 | reset();
861 | expected = "This is a normal link: Try them out:diveintomarkYahoo";
862 | jQuery('#yahoo').before(jQuery("#first, #mark"));
863 | equals( expected, jQuery('#en').text(), "Insert jQuery before" );
864 | });
865 |
866 | test("insertBefore(String|Element|Array<Element>|jQuery)", function() {
867 | expect(4);
868 | var expected = 'This is a normal link: bugaYahoo';
869 | jQuery('buga ').insertBefore('#yahoo');
870 | equals( expected, jQuery('#en').text(), 'Insert String before' );
871 |
872 | reset();
873 | expected = "This is a normal link: Try them out:Yahoo";
874 | jQuery(document.getElementById('first')).insertBefore('#yahoo');
875 | equals( expected, jQuery('#en').text(), "Insert element before" );
876 |
877 | reset();
878 | expected = "This is a normal link: Try them out:diveintomarkYahoo";
879 | jQuery([document.getElementById('first'), document.getElementById('mark')]).insertBefore('#yahoo');
880 | equals( expected, jQuery('#en').text(), "Insert array of elements before" );
881 |
882 | reset();
883 | expected = "This is a normal link: Try them out:diveintomarkYahoo";
884 | jQuery("#first, #mark").insertBefore('#yahoo');
885 | equals( expected, jQuery('#en').text(), "Insert jQuery before" );
886 | });
887 |
888 | test("after(String|Element|Array<Element>|jQuery)", function() {
889 | expect(4);
890 | var expected = 'This is a normal link: Yahoobuga';
891 | jQuery('#yahoo').after('buga ');
892 | equals( expected, jQuery('#en').text(), 'Insert String after' );
893 |
894 | reset();
895 | expected = "This is a normal link: YahooTry them out:";
896 | jQuery('#yahoo').after(document.getElementById('first'));
897 | equals( expected, jQuery('#en').text(), "Insert element after" );
898 |
899 | reset();
900 | expected = "This is a normal link: YahooTry them out:diveintomark";
901 | jQuery('#yahoo').after([document.getElementById('first'), document.getElementById('mark')]);
902 | equals( expected, jQuery('#en').text(), "Insert array of elements after" );
903 |
904 | reset();
905 | expected = "This is a normal link: YahooTry them out:diveintomark";
906 | jQuery('#yahoo').after(jQuery("#first, #mark"));
907 | equals( expected, jQuery('#en').text(), "Insert jQuery after" );
908 | });
909 |
910 | test("insertAfter(String|Element|Array<Element>|jQuery)", function() {
911 | expect(4);
912 | var expected = 'This is a normal link: Yahoobuga';
913 | jQuery('buga ').insertAfter('#yahoo');
914 | equals( expected, jQuery('#en').text(), 'Insert String after' );
915 |
916 | reset();
917 | expected = "This is a normal link: YahooTry them out:";
918 | jQuery(document.getElementById('first')).insertAfter('#yahoo');
919 | equals( expected, jQuery('#en').text(), "Insert element after" );
920 |
921 | reset();
922 | expected = "This is a normal link: YahooTry them out:diveintomark";
923 | jQuery([document.getElementById('mark'), document.getElementById('first')]).insertAfter('#yahoo');
924 | equals( expected, jQuery('#en').text(), "Insert array of elements after" );
925 |
926 | reset();
927 | expected = "This is a normal link: YahooTry them out:diveintomark";
928 | jQuery("#mark, #first").insertAfter('#yahoo');
929 | equals( expected, jQuery('#en').text(), "Insert jQuery after" );
930 | });
931 |
932 | test("replaceWith(String|Element|Array<Element>|jQuery)", function() {
933 | expect(10);
934 | jQuery('#yahoo').replaceWith('buga ');
935 | ok( jQuery("#replace")[0], 'Replace element with string' );
936 | ok( !jQuery("#yahoo")[0], 'Verify that original element is gone, after string' );
937 |
938 | reset();
939 | jQuery('#yahoo').replaceWith(document.getElementById('first'));
940 | ok( jQuery("#first")[0], 'Replace element with element' );
941 | ok( !jQuery("#yahoo")[0], 'Verify that original element is gone, after element' );
942 |
943 | reset();
944 | jQuery('#yahoo').replaceWith([document.getElementById('first'), document.getElementById('mark')]);
945 | ok( jQuery("#first")[0], 'Replace element with array of elements' );
946 | ok( jQuery("#mark")[0], 'Replace element with array of elements' );
947 | ok( !jQuery("#yahoo")[0], 'Verify that original element is gone, after array of elements' );
948 |
949 | reset();
950 | jQuery('#yahoo').replaceWith(jQuery("#first, #mark"));
951 | ok( jQuery("#first")[0], 'Replace element with set of elements' );
952 | ok( jQuery("#mark")[0], 'Replace element with set of elements' );
953 | ok( !jQuery("#yahoo")[0], 'Verify that original element is gone, after set of elements' );
954 | });
955 |
956 | test("replaceAll(String|Element|Array<Element>|jQuery)", function() {
957 | expect(10);
958 | jQuery('buga ').replaceAll("#yahoo");
959 | ok( jQuery("#replace")[0], 'Replace element with string' );
960 | ok( !jQuery("#yahoo")[0], 'Verify that original element is gone, after string' );
961 |
962 | reset();
963 | jQuery(document.getElementById('first')).replaceAll("#yahoo");
964 | ok( jQuery("#first")[0], 'Replace element with element' );
965 | ok( !jQuery("#yahoo")[0], 'Verify that original element is gone, after element' );
966 |
967 | reset();
968 | jQuery([document.getElementById('first'), document.getElementById('mark')]).replaceAll("#yahoo");
969 | ok( jQuery("#first")[0], 'Replace element with array of elements' );
970 | ok( jQuery("#mark")[0], 'Replace element with array of elements' );
971 | ok( !jQuery("#yahoo")[0], 'Verify that original element is gone, after array of elements' );
972 |
973 | reset();
974 | jQuery("#first, #mark").replaceAll("#yahoo");
975 | ok( jQuery("#first")[0], 'Replace element with set of elements' );
976 | ok( jQuery("#mark")[0], 'Replace element with set of elements' );
977 | ok( !jQuery("#yahoo")[0], 'Verify that original element is gone, after set of elements' );
978 | });
979 |
980 | test("end()", function() {
981 | expect(3);
982 | equals( 'Yahoo', jQuery('#yahoo').parent().end().text(), 'Check for end' );
983 | ok( jQuery('#yahoo').end(), 'Check for end with nothing to end' );
984 |
985 | var x = jQuery('#yahoo');
986 | x.parent();
987 | equals( 'Yahoo', jQuery('#yahoo').text(), 'Check for non-destructive behaviour' );
988 | });
989 |
990 | test("find(String)", function() {
991 | expect(2);
992 | equals( 'Yahoo', jQuery('#foo').find('.blogTest').text(), 'Check for find' );
993 |
994 | // using contents will get comments regular, text, and comment nodes
995 | var j = jQuery("#nonnodes").contents();
996 | equals( j.find("div").length, 0, "Check node,textnode,comment to find zero divs" );
997 | });
998 |
999 | test("clone()", function() {
1000 | expect(20);
1001 | equals( 'This is a normal link: Yahoo', jQuery('#en').text(), 'Assert text for #en' );
1002 | var clone = jQuery('#yahoo').clone();
1003 | equals( 'Try them out:Yahoo', jQuery('#first').append(clone).text(), 'Check for clone' );
1004 | equals( 'This is a normal link: Yahoo', jQuery('#en').text(), 'Reassert text for #en' );
1005 |
1006 | var cloneTags = [
1007 | "", " ", " ", "
",
1008 | "
", "
", "
", "
",
1009 | "
", "
", "
", "
",
1010 | "
", "
", "
", "
"
1011 | ];
1012 | for (var i = 0; i < cloneTags.length; i++) {
1013 | var j = jQuery(cloneTags[i]);
1014 | equals( j[0].tagName, j.clone()[0].tagName, 'Clone a <' + cloneTags[i].substring(1));
1015 | }
1016 |
1017 | // using contents will get comments regular, text, and comment nodes
1018 | var cl = jQuery("#nonnodes").contents().clone();
1019 | ok( cl.length >= 2, "Check node,textnode,comment clone works (some browsers delete comments on clone)" );
1020 | });
1021 |
1022 | if (!isLocal) {
1023 | test("clone() on XML nodes", function() {
1024 | expect(2);
1025 | stop();
1026 | jQuery.get("data/dashboard.xml", function (xml) {
1027 | var root = jQuery(xml.documentElement).clone();
1028 | jQuery("tab:first", xml).text("origval");
1029 | jQuery("tab:first", root).text("cloneval");
1030 | equals(jQuery("tab:first", xml).text(), "origval", "Check original XML node was correctly set");
1031 | equals(jQuery("tab:first", root).text(), "cloneval", "Check cloned XML node was correctly set");
1032 | start();
1033 | });
1034 | });
1035 | }
1036 |
1037 | test("is(String)", function() {
1038 | expect(26);
1039 | ok( jQuery('#form').is('form'), 'Check for element: A form must be a form' );
1040 | ok( !jQuery('#form').is('div'), 'Check for element: A form is not a div' );
1041 | ok( jQuery('#mark').is('.blog'), 'Check for class: Expected class "blog"' );
1042 | ok( !jQuery('#mark').is('.link'), 'Check for class: Did not expect class "link"' );
1043 | ok( jQuery('#simon').is('.blog.link'), 'Check for multiple classes: Expected classes "blog" and "link"' );
1044 | ok( !jQuery('#simon').is('.blogTest'), 'Check for multiple classes: Expected classes "blog" and "link", but not "blogTest"' );
1045 | ok( jQuery('#en').is('[lang="en"]'), 'Check for attribute: Expected attribute lang to be "en"' );
1046 | ok( !jQuery('#en').is('[lang="de"]'), 'Check for attribute: Expected attribute lang to be "en", not "de"' );
1047 | ok( jQuery('#text1').is('[type="text"]'), 'Check for attribute: Expected attribute type to be "text"' );
1048 | ok( !jQuery('#text1').is('[type="radio"]'), 'Check for attribute: Expected attribute type to be "text", not "radio"' );
1049 | ok( jQuery('#text2').is(':disabled'), 'Check for pseudoclass: Expected to be disabled' );
1050 | ok( !jQuery('#text1').is(':disabled'), 'Check for pseudoclass: Expected not disabled' );
1051 | ok( jQuery('#radio2').is(':checked'), 'Check for pseudoclass: Expected to be checked' );
1052 | ok( !jQuery('#radio1').is(':checked'), 'Check for pseudoclass: Expected not checked' );
1053 | ok( jQuery('#foo').is(':has(p)'), 'Check for child: Expected a child "p" element' );
1054 | ok( !jQuery('#foo').is(':has(ul)'), 'Check for child: Did not expect "ul" element' );
1055 | ok( jQuery('#foo').is(':has(p):has(a):has(code)'), 'Check for childs: Expected "p", "a" and "code" child elements' );
1056 | ok( !jQuery('#foo').is(':has(p):has(a):has(code):has(ol)'), 'Check for childs: Expected "p", "a" and "code" child elements, but no "ol"' );
1057 | ok( !jQuery('#foo').is(0), 'Expected false for an invalid expression - 0' );
1058 | ok( !jQuery('#foo').is(null), 'Expected false for an invalid expression - null' );
1059 | ok( !jQuery('#foo').is(''), 'Expected false for an invalid expression - ""' );
1060 | ok( !jQuery('#foo').is(undefined), 'Expected false for an invalid expression - undefined' );
1061 |
1062 | // test is() with comma-seperated expressions
1063 | ok( jQuery('#en').is('[lang="en"],[lang="de"]'), 'Comma-seperated; Check for lang attribute: Expect en or de' );
1064 | ok( jQuery('#en').is('[lang="de"],[lang="en"]'), 'Comma-seperated; Check for lang attribute: Expect en or de' );
1065 | ok( jQuery('#en').is('[lang="en"] , [lang="de"]'), 'Comma-seperated; Check for lang attribute: Expect en or de' );
1066 | ok( jQuery('#en').is('[lang="de"] , [lang="en"]'), 'Comma-seperated; Check for lang attribute: Expect en or de' );
1067 | });
1068 |
1069 | test("jQuery.extend(Object, Object)", function() {
1070 | expect(20);
1071 |
1072 | var settings = { xnumber1: 5, xnumber2: 7, xstring1: "peter", xstring2: "pan" },
1073 | options = { xnumber2: 1, xstring2: "x", xxx: "newstring" },
1074 | optionsCopy = { xnumber2: 1, xstring2: "x", xxx: "newstring" },
1075 | merged = { xnumber1: 5, xnumber2: 1, xstring1: "peter", xstring2: "x", xxx: "newstring" },
1076 | deep1 = { foo: { bar: true } },
1077 | deep1copy = { foo: { bar: true } },
1078 | deep2 = { foo: { baz: true }, foo2: document },
1079 | deep2copy = { foo: { baz: true }, foo2: document },
1080 | deepmerged = { foo: { bar: true, baz: true }, foo2: document };
1081 |
1082 | jQuery.extend(settings, options);
1083 | isObj( settings, merged, "Check if extended: settings must be extended" );
1084 | isObj( options, optionsCopy, "Check if not modified: options must not be modified" );
1085 |
1086 | jQuery.extend(settings, null, options);
1087 | isObj( settings, merged, "Check if extended: settings must be extended" );
1088 | isObj( options, optionsCopy, "Check if not modified: options must not be modified" );
1089 |
1090 | jQuery.extend(true, deep1, deep2);
1091 | isObj( deep1.foo, deepmerged.foo, "Check if foo: settings must be extended" );
1092 | isObj( deep2.foo, deep2copy.foo, "Check if not deep2: options must not be modified" );
1093 | equals( deep1.foo2, document, "Make sure that a deep clone was not attempted on the document" );
1094 |
1095 | var nullUndef;
1096 | nullUndef = jQuery.extend({}, options, { xnumber2: null });
1097 | ok( nullUndef.xnumber2 === null, "Check to make sure null values are copied");
1098 |
1099 | nullUndef = jQuery.extend({}, options, { xnumber2: undefined });
1100 | ok( nullUndef.xnumber2 === options.xnumber2, "Check to make sure undefined values are not copied");
1101 |
1102 | nullUndef = jQuery.extend({}, options, { xnumber0: null });
1103 | ok( nullUndef.xnumber0 === null, "Check to make sure null values are inserted");
1104 |
1105 | var target = {};
1106 | var recursive = { foo:target, bar:5 };
1107 | jQuery.extend(true, target, recursive);
1108 | isObj( target, { bar:5 }, "Check to make sure a recursive obj doesn't go never-ending loop by not copying it over" );
1109 |
1110 | var ret = jQuery.extend(true, { foo: [] }, { foo: [0] } ); // 1907
1111 | equals( ret.foo.length, 1, "Check to make sure a value with coersion 'false' copies over when necessary to fix #1907" );
1112 |
1113 | var ret = jQuery.extend(true, { foo: "1,2,3" }, { foo: [1, 2, 3] } );
1114 | ok( typeof ret.foo != "string", "Check to make sure values equal with coersion (but not actually equal) overwrite correctly" );
1115 |
1116 | var ret = jQuery.extend(true, { foo:"bar" }, { foo:null } );
1117 | ok( typeof ret.foo !== 'undefined', "Make sure a null value doesn't crash with deep extend, for #1908" );
1118 |
1119 | var obj = { foo:null };
1120 | jQuery.extend(true, obj, { foo:"notnull" } );
1121 | equals( obj.foo, "notnull", "Make sure a null value can be overwritten" );
1122 |
1123 | function func() {}
1124 | jQuery.extend(func, { key: "value" } );
1125 | equals( func.key, "value", "Verify a function can be extended" );
1126 |
1127 | var defaults = { xnumber1: 5, xnumber2: 7, xstring1: "peter", xstring2: "pan" },
1128 | defaultsCopy = { xnumber1: 5, xnumber2: 7, xstring1: "peter", xstring2: "pan" },
1129 | options1 = { xnumber2: 1, xstring2: "x" },
1130 | options1Copy = { xnumber2: 1, xstring2: "x" },
1131 | options2 = { xstring2: "xx", xxx: "newstringx" },
1132 | options2Copy = { xstring2: "xx", xxx: "newstringx" },
1133 | merged2 = { xnumber1: 5, xnumber2: 1, xstring1: "peter", xstring2: "xx", xxx: "newstringx" };
1134 |
1135 | var settings = jQuery.extend({}, defaults, options1, options2);
1136 | isObj( settings, merged2, "Check if extended: settings must be extended" );
1137 | isObj( defaults, defaultsCopy, "Check if not modified: options1 must not be modified" );
1138 | isObj( options1, options1Copy, "Check if not modified: options1 must not be modified" );
1139 | isObj( options2, options2Copy, "Check if not modified: options2 must not be modified" );
1140 | });
1141 |
1142 | test("val()", function() {
1143 | expect(3);
1144 | equals( jQuery("#text1").val(), "Test", "Check for value of input element" );
1145 | // ticket #1714 this caused a JS error in IE
1146 | equals( jQuery("#first").val(), "", "Check a paragraph element to see if it has a value" );
1147 | ok( jQuery([]).val() === undefined, "Check an empty jQuery object will return undefined from val" );
1148 | });
1149 |
1150 | test("val(String/Number)", function() {
1151 | expect(6);
1152 | document.getElementById('text1').value = "bla";
1153 | equals( jQuery("#text1").val(), "bla", "Check for modified value of input element" );
1154 |
1155 | jQuery("#text1").val('test');
1156 | equals( document.getElementById('text1').value, "test", "Check for modified (via val(String)) value of input element" );
1157 |
1158 | jQuery("#text1").val(67);
1159 | equals( document.getElementById('text1').value, "67", "Check for modified (via val(Number)) value of input element" );
1160 |
1161 | jQuery("#select1").val("3");
1162 | equals( jQuery("#select1").val(), "3", "Check for modified (via val(String)) value of select element" );
1163 |
1164 | jQuery("#select1").val(2);
1165 | equals( jQuery("#select1").val(), "2", "Check for modified (via val(Number)) value of select element" );
1166 |
1167 | // using contents will get comments regular, text, and comment nodes
1168 | var j = jQuery("#nonnodes").contents();
1169 | j.val("asdf");
1170 | equals( j.val(), "asdf", "Check node,textnode,comment with val()" );
1171 | j.removeAttr("value");
1172 | });
1173 |
1174 | var scriptorder = 0;
1175 |
1176 | test("html(String)", function() {
1177 | expect(11);
1178 | var div = jQuery("#main > div");
1179 | div.html("
test ");
1180 | var pass = true;
1181 | for ( var i = 0; i < div.size(); i++ ) {
1182 | if ( div.get(i).childNodes.length != 1 ) pass = false;
1183 | }
1184 | ok( pass, "Set HTML" );
1185 |
1186 | reset();
1187 | // using contents will get comments regular, text, and comment nodes
1188 | var j = jQuery("#nonnodes").contents();
1189 | j.html("
bold ");
1190 |
1191 | // this is needed, or the expando added by jQuery unique will yield a different html
1192 | j.find('b').removeData();
1193 | equals( j.html().toLowerCase(), "
bold ", "Check node,textnode,comment with html()" );
1194 |
1195 | jQuery("#main").html("
");
1196 | jQuery("#main select").html("
O1 O2 O3 ");
1197 | equals( jQuery("#main select").val(), "O2", "Selected option correct" );
1198 |
1199 | stop();
1200 |
1201 | jQuery("#main").html('');
1202 |
1203 | jQuery("#main").html('foo
');
1204 |
1205 | // it was decided that waiting to execute ALL scripts makes sense since nested ones have to wait anyway so this test case is changed, see #1959
1206 | jQuery("#main").html("