repo
stringlengths
5
106
file_url
stringlengths
78
301
file_path
stringlengths
4
211
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 14:56:49
2026-01-05 02:23:25
truncated
bool
2 classes
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/src/core/isAttached.js
src/core/isAttached.js
import { jQuery } from "../core.js"; import { documentElement } from "../var/documentElement.js"; var isAttached = function( elem ) { return jQuery.contains( elem.ownerDocument, elem ) || elem.getRootNode( composed ) === elem.ownerDocument; }, composed = { composed: true }; // Support: IE 9 - 11+ // Check attachment across shadow DOM boundaries when possible (gh-3504). // Provide a fallback for browsers without Shadow DOM v1 support. if ( !documentElement.getRootNode ) { isAttached = function( elem ) { return jQuery.contains( elem.ownerDocument, elem ); }; } export { isAttached };
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
false
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/src/core/parseHTML.js
src/core/parseHTML.js
import { jQuery } from "../core.js"; import { rsingleTag } from "./var/rsingleTag.js"; import { buildFragment } from "../manipulation/buildFragment.js"; import { isObviousHtml } from "./isObviousHtml.js"; // Argument "data" should be string of html or a TrustedHTML wrapper of obvious HTML // context (optional): If specified, the fragment will be created in this context, // defaults to document // keepScripts (optional): If true, will include scripts passed in the html string jQuery.parseHTML = function( data, context, keepScripts ) { if ( typeof data !== "string" && !isObviousHtml( data + "" ) ) { return []; } if ( typeof context === "boolean" ) { keepScripts = context; context = false; } var parsed, scripts; if ( !context ) { // Stop scripts or inline event handlers from being executed immediately // by using DOMParser context = ( new window.DOMParser() ) .parseFromString( "", "text/html" ); } parsed = rsingleTag.exec( data ); scripts = !keepScripts && []; // Single tag if ( parsed ) { return [ context.createElement( parsed[ 1 ] ) ]; } parsed = buildFragment( [ data ], context, scripts ); if ( scripts && scripts.length ) { jQuery( scripts ).remove(); } return jQuery.merge( [], parsed.childNodes ); };
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
false
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/src/core/toType.js
src/core/toType.js
import { class2type } from "../var/class2type.js"; import { toString } from "../var/toString.js"; export function toType( obj ) { if ( obj == null ) { return obj + ""; } return typeof obj === "object" ? class2type[ toString.call( obj ) ] || "object" : typeof obj; }
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
false
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/src/core/stripAndCollapse.js
src/core/stripAndCollapse.js
import { rnothtmlwhite } from "../var/rnothtmlwhite.js"; // Strip and collapse whitespace according to HTML spec // https://infra.spec.whatwg.org/#strip-and-collapse-ascii-whitespace export function stripAndCollapse( value ) { var tokens = value.match( rnothtmlwhite ) || []; return tokens.join( " " ); }
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
false
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/src/core/ready.js
src/core/ready.js
import { jQuery } from "../core.js"; import { document } from "../var/document.js"; import "../core/readyException.js"; import "../deferred.js"; // The deferred used on DOM ready var readyList = jQuery.Deferred(); jQuery.fn.ready = function( fn ) { readyList .then( fn ) // Wrap jQuery.readyException in a function so that the lookup // happens at the time of error handling instead of callback // registration. .catch( function( error ) { jQuery.readyException( error ); } ); return this; }; jQuery.extend( { // Is the DOM ready to be used? Set to true once it occurs. isReady: false, // A counter to track how many items to wait for before // the ready event fires. See trac-6781 readyWait: 1, // Handle when the DOM is ready ready: function( wait ) { // Abort if there are pending holds or we're already ready if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { return; } // Remember that the DOM is ready jQuery.isReady = true; // If a normal DOM Ready event fired, decrement, and wait if need be if ( wait !== true && --jQuery.readyWait > 0 ) { return; } // If there are functions bound, to execute readyList.resolveWith( document, [ jQuery ] ); } } ); jQuery.ready.then = readyList.then; // The ready event handler and self cleanup method function completed() { document.removeEventListener( "DOMContentLoaded", completed ); window.removeEventListener( "load", completed ); jQuery.ready(); } // Catch cases where $(document).ready() is called // after the browser event has already occurred. if ( document.readyState !== "loading" ) { // Handle it asynchronously to allow scripts the opportunity to delay ready window.setTimeout( jQuery.ready ); } else { // Use the handy event callback document.addEventListener( "DOMContentLoaded", completed ); // A fallback to window.onload, that will always work window.addEventListener( "load", completed ); }
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
false
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/src/core/readyException.js
src/core/readyException.js
import { jQuery } from "../core.js"; jQuery.readyException = function( error ) { window.setTimeout( function() { throw error; } ); };
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
false
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/src/core/nodeName.js
src/core/nodeName.js
export function nodeName( elem, name ) { return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); }
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
false
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/src/core/parseXML.js
src/core/parseXML.js
import { jQuery } from "../core.js"; // Cross-browser xml parsing jQuery.parseXML = function( data ) { var xml, parserErrorElem; if ( !data || typeof data !== "string" ) { return null; } // Support: IE 9 - 11+ // IE throws on parseFromString with invalid input. try { xml = ( new window.DOMParser() ).parseFromString( data, "text/xml" ); } catch ( e ) {} parserErrorElem = xml && xml.getElementsByTagName( "parsererror" )[ 0 ]; if ( !xml || parserErrorElem ) { jQuery.error( "Invalid XML: " + ( parserErrorElem ? jQuery.map( parserErrorElem.childNodes, function( el ) { return el.textContent; } ).join( "\n" ) : data ) ); } return xml; };
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
false
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/src/core/DOMEval.js
src/core/DOMEval.js
import { document } from "../var/document.js"; var preservedScriptAttributes = { type: true, src: true, nonce: true, noModule: true }; export function DOMEval( code, node, doc ) { doc = doc || document; var i, script = doc.createElement( "script" ); script.text = code; for ( i in preservedScriptAttributes ) { if ( node && node[ i ] ) { script[ i ] = node[ i ]; } } if ( doc.head.appendChild( script ).parentNode ) { script.parentNode.removeChild( script ); } }
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
false
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/src/core/isObviousHtml.js
src/core/isObviousHtml.js
export function isObviousHtml( input ) { return input[ 0 ] === "<" && input[ input.length - 1 ] === ">" && input.length >= 3; }
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
false
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/src/core/ready-no-deferred.js
src/core/ready-no-deferred.js
import { jQuery } from "../core.js"; import { document } from "../var/document.js"; var readyCallbacks = [], whenReady = function( fn ) { readyCallbacks.push( fn ); }, executeReady = function( fn ) { // Prevent errors from freezing future callback execution (gh-1823) // Not backwards-compatible as this does not execute sync window.setTimeout( function() { fn.call( document, jQuery ); } ); }; jQuery.fn.ready = function( fn ) { whenReady( fn ); return this; }; jQuery.extend( { // Is the DOM ready to be used? Set to true once it occurs. isReady: false, // A counter to track how many items to wait for before // the ready event fires. See trac-6781 readyWait: 1, ready: function( wait ) { // Abort if there are pending holds or we're already ready if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { return; } // Remember that the DOM is ready jQuery.isReady = true; // If a normal DOM Ready event fired, decrement, and wait if need be if ( wait !== true && --jQuery.readyWait > 0 ) { return; } whenReady = function( fn ) { readyCallbacks.push( fn ); while ( readyCallbacks.length ) { fn = readyCallbacks.shift(); if ( typeof fn === "function" ) { executeReady( fn ); } } }; whenReady(); } } ); // Make jQuery.ready Promise consumable (gh-1778) jQuery.ready.then = jQuery.fn.ready; /** * The ready event handler and self cleanup method */ function completed() { document.removeEventListener( "DOMContentLoaded", completed ); window.removeEventListener( "load", completed ); jQuery.ready(); } // Catch cases where $(document).ready() is called // after the browser event has already occurred. if ( document.readyState !== "loading" ) { // Handle it asynchronously to allow scripts the opportunity to delay ready window.setTimeout( jQuery.ready ); } else { // Use the handy event callback document.addEventListener( "DOMContentLoaded", completed ); // A fallback to window.onload, that will always work window.addEventListener( "load", completed ); }
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
false
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/src/core/isArrayLike.js
src/core/isArrayLike.js
import { toType } from "./toType.js"; import { isWindow } from "../var/isWindow.js"; export function isArrayLike( obj ) { var length = !!obj && obj.length, type = toType( obj ); if ( typeof obj === "function" || isWindow( obj ) ) { return false; } return type === "array" || length === 0 || typeof length === "number" && length > 0 && ( length - 1 ) in obj; }
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
false
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/src/core/init.js
src/core/init.js
// Initialize a jQuery object import { jQuery } from "../core.js"; import { document } from "../var/document.js"; import { rsingleTag } from "./var/rsingleTag.js"; import { isObviousHtml } from "./isObviousHtml.js"; import "../traversing/findFilter.js"; // A central reference to the root jQuery(document) var rootjQuery, // A simple way to check for HTML strings // Prioritize #id over <tag> to avoid XSS via location.hash (trac-9521) // Strict HTML recognition (trac-11290: must start with <) // Shortcut simple #id case for speed rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]+))$/, init = jQuery.fn.init = function( selector, context ) { var match, elem; // HANDLE: $(""), $(null), $(undefined), $(false) if ( !selector ) { return this; } // HANDLE: $(DOMElement) if ( selector.nodeType ) { this[ 0 ] = selector; this.length = 1; return this; // HANDLE: $(function) // Shortcut for document ready } else if ( typeof selector === "function" ) { return rootjQuery.ready !== undefined ? rootjQuery.ready( selector ) : // Execute immediately if ready is not present selector( jQuery ); } else { // Handle obvious HTML strings match = selector + ""; if ( isObviousHtml( match ) ) { // Assume that strings that start and end with <> are HTML and skip // the regex check. This also handles browser-supported HTML wrappers // like TrustedHTML. match = [ null, selector, null ]; // Handle HTML strings or selectors } else if ( typeof selector === "string" ) { match = rquickExpr.exec( selector ); } else { return jQuery.makeArray( selector, this ); } // Match html or make sure no context is specified for #id // Note: match[1] may be a string or a TrustedHTML wrapper if ( match && ( match[ 1 ] || !context ) ) { // HANDLE: $(html) -> $(array) if ( match[ 1 ] ) { context = context instanceof jQuery ? context[ 0 ] : context; // Option to run scripts is true for back-compat // Intentionally let the error be thrown if parseHTML is not present jQuery.merge( this, jQuery.parseHTML( match[ 1 ], context && context.nodeType ? context.ownerDocument || context : document, true ) ); // HANDLE: $(html, props) if ( rsingleTag.test( match[ 1 ] ) && jQuery.isPlainObject( context ) ) { for ( match in context ) { // Properties of context are called as methods if possible if ( typeof this[ match ] === "function" ) { this[ match ]( context[ match ] ); // ...and otherwise set as attributes } else { this.attr( match, context[ match ] ); } } } return this; // HANDLE: $(#id) } else { elem = document.getElementById( match[ 2 ] ); if ( elem ) { // Inject the element directly into the jQuery object this[ 0 ] = elem; this.length = 1; } return this; } // HANDLE: $(expr) & $(expr, $(...)) } else if ( !context || context.jquery ) { return ( context || rootjQuery ).find( selector ); // HANDLE: $(expr, context) // (which is just equivalent to: $(context).find(expr) } else { return this.constructor( context ).find( selector ); } } }; // Give the init function the jQuery prototype for later instantiation init.prototype = jQuery.fn; // Initialize central reference rootjQuery = jQuery( document );
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
false
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/src/core/access.js
src/core/access.js
import { jQuery } from "../core.js"; import { toType } from "../core/toType.js"; // Multifunctional method to get and set values of a collection // The value/s can optionally be executed if it's a function export function access( elems, fn, key, value, chainable, emptyGet, raw ) { var i = 0, len = elems.length, bulk = key == null; // Sets many values if ( toType( key ) === "object" ) { chainable = true; for ( i in key ) { access( elems, fn, i, key[ i ], true, emptyGet, raw ); } // Sets one value } else if ( value !== undefined ) { chainable = true; if ( typeof value !== "function" ) { raw = true; } if ( bulk ) { // Bulk operations run against the entire set if ( raw ) { fn.call( elems, value ); fn = null; // ...except when executing function values } else { bulk = fn; fn = function( elem, _key, value ) { return bulk.call( jQuery( elem ), value ); }; } } if ( fn ) { for ( ; i < len; i++ ) { fn( elems[ i ], key, raw ? value : value.call( elems[ i ], i, fn( elems[ i ], key ) ) ); } } } if ( chainable ) { return elems; } // Gets if ( bulk ) { return fn.call( elems ); } return len ? fn( elems[ 0 ], key ) : emptyGet; }
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
false
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/src/core/camelCase.js
src/core/camelCase.js
// Matches dashed string for camelizing var rdashAlpha = /-([a-z])/g; // Used by camelCase as callback to replace() function fcamelCase( _all, letter ) { return letter.toUpperCase(); } // Convert dashed to camelCase export function camelCase( string ) { return string.replace( rdashAlpha, fcamelCase ); }
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
false
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/src/core/var/rsingleTag.js
src/core/var/rsingleTag.js
// rsingleTag matches a string consisting of a single HTML element with no attributes // and captures the element's name export var rsingleTag = /^<([a-z][^\/\0>:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i;
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
false
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/src/data/Data.js
src/data/Data.js
import { jQuery } from "../core.js"; import { camelCase } from "../core/camelCase.js"; import { rnothtmlwhite } from "../var/rnothtmlwhite.js"; import { acceptData } from "./var/acceptData.js"; export function Data() { this.expando = jQuery.expando + Data.uid++; } Data.uid = 1; Data.prototype = { cache: function( owner ) { // Check if the owner object already has a cache var value = owner[ this.expando ]; // If not, create one if ( !value ) { value = Object.create( null ); // We can accept data for non-element nodes in modern browsers, // but we should not, see trac-8335. // Always return an empty object. if ( acceptData( owner ) ) { // If it is a node unlikely to be stringify-ed or looped over // use plain assignment if ( owner.nodeType ) { owner[ this.expando ] = value; // Otherwise secure it in a non-enumerable property // configurable must be true to allow the property to be // deleted when data is removed } else { Object.defineProperty( owner, this.expando, { value: value, configurable: true } ); } } } return value; }, set: function( owner, data, value ) { var prop, cache = this.cache( owner ); // Handle: [ owner, key, value ] args // Always use camelCase key (gh-2257) if ( typeof data === "string" ) { cache[ camelCase( data ) ] = value; // Handle: [ owner, { properties } ] args } else { // Copy the properties one-by-one to the cache object for ( prop in data ) { cache[ camelCase( prop ) ] = data[ prop ]; } } return value; }, get: function( owner, key ) { return key === undefined ? this.cache( owner ) : // Always use camelCase key (gh-2257) owner[ this.expando ] && owner[ this.expando ][ camelCase( key ) ]; }, access: function( owner, key, value ) { // In cases where either: // // 1. No key was specified // 2. A string key was specified, but no value provided // // Take the "read" path and allow the get method to determine // which value to return, respectively either: // // 1. The entire cache object // 2. The data stored at the key // if ( key === undefined || ( ( key && typeof key === "string" ) && value === undefined ) ) { return this.get( owner, key ); } // When the key is not a string, or both a key and value // are specified, set or extend (existing objects) with either: // // 1. An object of properties // 2. A key and value // this.set( owner, key, value ); // Since the "set" path can have two possible entry points // return the expected data based on which path was taken[*] return value !== undefined ? value : key; }, remove: function( owner, key ) { var i, cache = owner[ this.expando ]; if ( cache === undefined ) { return; } if ( key !== undefined ) { // Support array or space separated string of keys if ( Array.isArray( key ) ) { // If key is an array of keys... // We always set camelCase keys, so remove that. key = key.map( camelCase ); } else { key = camelCase( key ); // If a key with the spaces exists, use it. // Otherwise, create an array by matching non-whitespace key = key in cache ? [ key ] : ( key.match( rnothtmlwhite ) || [] ); } i = key.length; while ( i-- ) { delete cache[ key[ i ] ]; } } // Remove the expando if there's no more data if ( key === undefined || jQuery.isEmptyObject( cache ) ) { // Support: Chrome <=35 - 45+ // Webkit & Blink performance suffers when deleting properties // from DOM nodes, so set to undefined instead // https://bugs.chromium.org/p/chromium/issues/detail?id=378607 (bug restricted) if ( owner.nodeType ) { owner[ this.expando ] = undefined; } else { delete owner[ this.expando ]; } } }, hasData: function( owner ) { var cache = owner[ this.expando ]; return cache !== undefined && !jQuery.isEmptyObject( cache ); } };
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
false
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/src/data/var/acceptData.js
src/data/var/acceptData.js
/** * Determines whether an object can have data */ export function acceptData( owner ) { // Accepts only: // - Node // - Node.ELEMENT_NODE // - Node.DOCUMENT_NODE // - Object // - Any return owner.nodeType === 1 || owner.nodeType === 9 || !( +owner.nodeType ); }
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
false
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/src/data/var/dataPriv.js
src/data/var/dataPriv.js
import { Data } from "../Data.js"; export var dataPriv = new Data();
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
false
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/src/data/var/dataUser.js
src/data/var/dataUser.js
import { Data } from "../Data.js"; export var dataUser = new Data();
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
false
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/test/jquery.js
test/jquery.js
// Use the right jQuery source on the test page (and iframes) ( function() { var dynamicImportSource, config, src, parentUrl = window.location.protocol + "//" + window.location.host, QUnit = window.QUnit; function getQUnitConfig() { var config = Object.create( null ); // Default to unminified jQuery for directly-opened iframes if ( !QUnit ) { config.dev = true; } else { // QUnit.config is populated from QUnit.urlParams but only at the beginning // of the test run. We need to read both. QUnit.config.urlConfig.forEach( function( entry ) { config[ entry.id ] = QUnit.config[ entry.id ] != null ? QUnit.config[ entry.id ] : QUnit.urlParams[ entry.id ]; } ); } return config; } // Define configuration parameters controlling how jQuery is loaded if ( QUnit ) { QUnit.config.urlConfig.push( { id: "esmodules", label: "Load as modules", tooltip: "Load the jQuery module file (and its dependencies)" }, { id: "dev", label: "Load unminified", tooltip: "Load the development (unminified) jQuery file" } ); } config = getQUnitConfig(); src = config.dev ? "dist/jquery.js" : "dist/jquery.min.js"; // Honor ES modules loading on the main window (detected by seeing QUnit on it). // This doesn't apply to iframes because they synchronously expect jQuery to be there. if ( config.esmodules && QUnit ) { // Support: IE 11+ // IE doesn't support the dynamic import syntax so it would crash // with a SyntaxError here. dynamicImportSource = "" + "import( `${ parentUrl }/src/jquery.js` )\n" + " .then( ( { jQuery } ) => {\n" + " window.jQuery = jQuery;\n" + " if ( typeof loadTests === \"function\" ) {\n" + " // Include tests if specified\n" + " loadTests();\n" + " }\n" + " } )\n" + " .catch( error => {\n" + " console.error( error );\n" + " QUnit.done();\n" + " } );"; eval( dynamicImportSource ); // Otherwise, load synchronously } else { document.write( "<script id='jquery-js' nonce='jquery+hardcoded+nonce' src='" + parentUrl + "/" + src + "'><\x2Fscript>" ); } } )();
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
false
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/test/integration/data/gh-1764-fullscreen.js
test/integration/data/gh-1764-fullscreen.js
/* exported bootstrapFrom */ // `mode` may be "iframe" or not specified. function bootstrapFrom( mainSelector, mode ) { if ( mode === "iframe" && window.parent === window ) { jQuery( mainSelector + " .result" ) .attr( "class", "result warn" ) .text( "This test should be run in an iframe. Open ../gh-1764-fullscreen.html." ); jQuery( mainSelector + " .toggle-fullscreen" ).remove(); return; } var fullscreenSupported = document.exitFullscreen || document.exitFullscreen || document.msExitFullscreen || document.mozCancelFullScreen || document.webkitExitFullscreen; function isFullscreen() { return !!( document.fullscreenElement || document.mozFullScreenElement || document.webkitFullscreenElement || document.msFullscreenElement ); } function requestFullscreen( element ) { if ( !isFullscreen() ) { if ( element.requestFullscreen ) { element.requestFullscreen(); } else if ( element.msRequestFullscreen ) { element.msRequestFullscreen(); } else if ( element.mozRequestFullScreen ) { element.mozRequestFullScreen(); } else if ( element.webkitRequestFullscreen ) { element.webkitRequestFullscreen(); } } } function exitFullscreen() { if ( document.exitFullscreen ) { document.exitFullscreen(); } else if ( document.msExitFullscreen ) { document.msExitFullscreen(); } else if ( document.mozCancelFullScreen ) { document.mozCancelFullScreen(); } else if ( document.webkitExitFullscreen ) { document.webkitExitFullscreen(); } } function runTest() { var dimensions; if ( !fullscreenSupported ) { jQuery( mainSelector + " .result" ) .attr( "class", "result success" ) .text( "Fullscreen mode is not supported in this browser. Test not run." ); } else if ( !isFullscreen() ) { jQuery( mainSelector + " .result" ) .attr( "class", "result warn" ) .text( "Enable fullscreen mode to fire the test." ); } else { dimensions = jQuery( mainSelector + " .result" ).css( [ "width", "height" ] ); dimensions.width = parseFloat( dimensions.width ).toFixed( 3 ); dimensions.height = parseFloat( dimensions.height ).toFixed( 3 ); if ( dimensions.width === "700.000" && dimensions.height === "56.000" ) { jQuery( mainSelector + " .result" ) .attr( "class", "result success" ) .text( "Dimensions in fullscreen mode are computed correctly." ); } else { jQuery( mainSelector + " .result" ) .attr( "class", "result error" ) .html( "Incorrect dimensions; " + "expected: { width: '700.000', height: '56.000' };<br>" + "got: { width: '" + dimensions.width + "', height: '" + dimensions.height + "' }." ); } } } function toggleFullscreen() { if ( isFullscreen() ) { exitFullscreen(); } else { requestFullscreen( jQuery( mainSelector + " .container" )[ 0 ] ); } } $( mainSelector + " .toggle-fullscreen" ).on( "click", toggleFullscreen ); $( document ).on( [ "webkitfullscreenchange", "mozfullscreenchange", "fullscreenchange", "MSFullscreenChange" ].join( " " ), runTest ); runTest(); }
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
false
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/test/bundler_smoke_tests/run-jsdom-tests.js
test/bundler_smoke_tests/run-jsdom-tests.js
import fs from "node:fs/promises"; import jsdom, { JSDOM } from "jsdom"; import path from "node:path"; import { fileURLToPath } from "node:url"; import { runRollupEsmAndCommonJs, runRollupPureEsm } from "./lib/run-rollup.js"; import { runWebpack } from "./lib/run-webpack.js"; import { cleanTmpBundlersDir } from "./lib/utils.js"; const dirname = path.dirname( fileURLToPath( import.meta.url ) ); async function runJSDOMTest( { title, folder } ) { console.log( "Running bundlers tests:", title ); const template = await fs.readFile( `${ dirname }/test.html`, "utf-8" ); const scriptSource = await fs.readFile( `${ dirname }/tmp/${ folder }/main.js`, "utf-8" ); const html = template .replace( /@TITLE\b/, () => title ) .replace( /@SCRIPT\b/, () => scriptSource ); const virtualConsole = new jsdom.VirtualConsole(); virtualConsole.forwardTo( console ); virtualConsole.on( "assert", ( success ) => { if ( !success ) { process.exitCode = 1; } } ); new JSDOM( html, { resources: "usable", runScripts: "dangerously", virtualConsole } ); if ( process.exitCode === 0 || process.exitCode == null ) { console.log( "Bundlers tests passed for:", title ); } else { console.error( "Bundlers tests failed for:", title ); } } async function buildAndTest() { await cleanTmpBundlersDir(); await Promise.all( [ runRollupPureEsm(), runRollupEsmAndCommonJs(), runWebpack() ] ); await Promise.all( [ runJSDOMTest( { title: "Rollup with pure ESM setup", folder: "rollup-pure-esm" } ), runJSDOMTest( { title: "Rollup with ESM + CommonJS", folder: "rollup-commonjs" } ), runJSDOMTest( { title: "Webpack", folder: "webpack" } ) ] ); // The directory won't be cleaned in case of failures; this may aid debugging. await cleanTmpBundlersDir(); } await buildAndTest();
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
false
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/test/bundler_smoke_tests/rollup-commonjs.config.js
test/bundler_smoke_tests/rollup-commonjs.config.js
import path from "node:path"; import { fileURLToPath } from "node:url"; import resolve from "@rollup/plugin-node-resolve"; import commonjs from "@rollup/plugin-commonjs"; const dirname = path.dirname( fileURLToPath( import.meta.url ) ); export default { input: `${ dirname }/src-esm-commonjs/main.js`, output: { dir: `${ dirname }/tmp/rollup-commonjs`, format: "iife", sourcemap: true }, plugins: [ resolve(), commonjs() ] };
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
false
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/test/bundler_smoke_tests/rollup-pure-esm.config.js
test/bundler_smoke_tests/rollup-pure-esm.config.js
import path from "node:path"; import { fileURLToPath } from "node:url"; import resolve from "@rollup/plugin-node-resolve"; const dirname = path.dirname( fileURLToPath( import.meta.url ) ); export default { input: `${ dirname }/src-pure-esm/main.js`, output: { dir: `${ dirname }/tmp/rollup-pure-esm`, format: "iife", sourcemap: true }, plugins: [ resolve() ] };
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
false
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/test/bundler_smoke_tests/src-pure-esm/main.js
test/bundler_smoke_tests/src-pure-esm/main.js
import { $ } from "jquery"; import { $ as $slim } from "jquery/slim"; import { jQueryFactory } from "jquery/factory"; import { jQueryFactory as jQueryFactorySlim } from "jquery/factory-slim"; console.assert( /^jQuery/.test( $.expando ), "jQuery.expando should be detected on full jQuery" ); console.assert( /^jQuery/.test( $slim.expando ), "jQuery.expando should be detected on slim jQuery" ); console.assert( !( "expando" in jQueryFactory ), "jQuery.expando should not be attached to the full factory" ); const $fromFactory = jQueryFactory( window ); console.assert( /^jQuery/.test( $fromFactory.expando ), "jQuery.expando should be detected on full jQuery from factory" ); console.assert( !( "expando" in jQueryFactorySlim ), "jQuery.expando should not be attached to the slim factory" ); const $fromFactorySlim = jQueryFactorySlim( window ); console.assert( /^jQuery/.test( $fromFactorySlim.expando ), "jQuery.expando should be detected on slim jQuery from factory" );
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
false
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/test/bundler_smoke_tests/src-esm-commonjs/main.js
test/bundler_smoke_tests/src-esm-commonjs/main.js
import { $ as $imported } from "jquery"; import { $ as $slimImported } from "jquery/slim"; import { jQueryFactory as jQueryFactoryImported } from "jquery/factory"; import { jQueryFactory as jQueryFactorySlimImported } from "jquery/factory-slim"; import { $required, $slimRequired, jQueryFactoryRequired, jQueryFactorySlimRequired } from "./jquery-require.cjs"; console.assert( $required === $imported, "Only one copy of full jQuery should exist" ); console.assert( /^jQuery/.test( $imported.expando ), "jQuery.expando should be detected on full jQuery" ); console.assert( $slimRequired === $slimImported, "Only one copy of slim jQuery should exist" ); console.assert( /^jQuery/.test( $slimImported.expando ), "jQuery.expando should be detected on slim jQuery" ); console.assert( jQueryFactoryImported === jQueryFactoryRequired, "Only one copy of full jQueryFactory should exist" ); console.assert( !( "expando" in jQueryFactoryImported ), "jQuery.expando should not be attached to the full factory" ); const $fromFactory = jQueryFactoryImported( window ); console.assert( /^jQuery/.test( $fromFactory.expando ), "jQuery.expando should be detected on full jQuery from factory" ); console.assert( jQueryFactorySlimImported === jQueryFactorySlimRequired, "Only one copy of slim jQueryFactory should exist" ); console.assert( !( "expando" in jQueryFactorySlimImported ), "jQuery.expando should not be attached to the slim factory" ); const $fromFactorySlim = jQueryFactorySlimImported( window ); console.assert( /^jQuery/.test( $fromFactorySlim.expando ), "jQuery.expando should be detected on slim jQuery from factory" );
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
false
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/test/bundler_smoke_tests/lib/run-webpack.js
test/bundler_smoke_tests/lib/run-webpack.js
import webpack from "webpack"; // See https://webpack.js.org/api/node/#webpack export async function runWebpack() { return new Promise( async( resolve, reject ) => { console.log( "Running Webpack" ); const { default: config } = await import( "../webpack.config.cjs" ); webpack( config, ( err, stats ) => { if ( err || stats.hasErrors() ) { console.error( "Errors detected during Webpack compilation" ); reject( err ); return; } console.log( "Build completed: Webpack" ); resolve(); } ); } ); }
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
false
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/test/bundler_smoke_tests/lib/run-rollup.js
test/bundler_smoke_tests/lib/run-rollup.js
import { rollup } from "rollup"; import { loadConfigFile } from "rollup/loadConfigFile"; import path from "node:path"; import { fileURLToPath } from "node:url"; const dirname = path.dirname( fileURLToPath( import.meta.url ) ); const pureEsmConfigPath = path.resolve( dirname, "..", "rollup-pure-esm.config.js" ); const commonJSConfigPath = path.resolve( dirname, "..", "rollup-commonjs.config.js" ); // See https://rollupjs.org/javascript-api/#programmatically-loading-a-config-file async function runRollup( name, configPath ) { console.log( `Running Rollup, version: ${ name }` ); // options is an array of "inputOptions" objects with an additional // "output" property that contains an array of "outputOptions". // We generate a single output so the array only has one element. const { options: [ optionsObj ], warnings } = await loadConfigFile( configPath, {} ); // "warnings" wraps the default `onwarn` handler passed by the CLI. // This prints all warnings up to this point: warnings.flush(); const bundle = await rollup( optionsObj ); await Promise.all( optionsObj.output.map( bundle.write ) ); console.log( `Build completed: Rollup, version: ${ name }` ); } export async function runRollupPureEsm() { await runRollup( "pure ESM", pureEsmConfigPath ); } export async function runRollupEsmAndCommonJs() { await runRollup( "ESM + CommonJS", commonJSConfigPath ); }
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
false
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/test/bundler_smoke_tests/lib/utils.js
test/bundler_smoke_tests/lib/utils.js
import fs from "node:fs/promises"; import path from "node:path"; import { fileURLToPath } from "node:url"; const dirname = path.dirname( fileURLToPath( import.meta.url ) ); const TMP_BUNDLERS_DIR = path.resolve( dirname, "..", "tmp" ); export async function cleanTmpBundlersDir() { await fs.rm( TMP_BUNDLERS_DIR, { force: true, recursive: true } ); }
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
false
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/test/unit/effects.js
test/unit/effects.js
( function() { // Can't test what ain't there if ( !includesModule( "effects" ) ) { return; } var fxInterval = 13, oldRaf = window.requestAnimationFrame, hideOptions = { inline: function() { jQuery.style( this, "display", "none" ); }, cascade: function() { this.className = "hidden"; } }; QUnit.module( "effects", { beforeEach: function() { this.sandbox = sinon.createSandbox(); this.clock = this.sandbox.useFakeTimers( 505877050 ); window.requestAnimationFrame = null; jQuery.fx.step = {}; }, afterEach: function() { this.sandbox.restore(); jQuery.fx.stop(); window.requestAnimationFrame = oldRaf; return moduleTeardown.apply( this, arguments ); } } ); QUnit[ QUnit.jQuerySelectors ? "test" : "skip" ]( "sanity check", function( assert ) { assert.expect( 1 ); assert.equal( jQuery( "#qunit-fixture:visible, #foo:visible" ).length, 2, "QUnit state is correct for testing effects" ); } ); QUnit.test( "show() basic", function( assert ) { assert.expect( 1 ); var div = jQuery( "<div>" ).hide().appendTo( "#qunit-fixture" ).show(); assert.equal( div.css( "display" ), "block", "Make sure pre-hidden divs show" ); // Clean up the detached node div.remove(); } ); QUnit.test( "show()", function( assert ) { assert.expect( 27 ); var div, speeds, test, hiddendiv = jQuery( "div.hidden" ); assert.equal( jQuery.css( hiddendiv[ 0 ], "display" ), "none", "hiddendiv is display: none" ); hiddendiv.css( "display", "block" ); assert.equal( jQuery.css( hiddendiv[ 0 ], "display" ), "block", "hiddendiv is display: block" ); hiddendiv.show(); assert.equal( jQuery.css( hiddendiv[ 0 ], "display" ), "block", "hiddendiv is display: block" ); hiddendiv.css( "display", "" ); div = jQuery( "#fx-queue div" ).slice( 0, 4 ); div.show().each( function() { assert.notEqual( this.style.display, "none", "don't change any <div> with display block" ); } ); speeds = { "null speed": null, "undefined speed": undefined, "false speed": false }; jQuery.each( speeds, function( name, speed ) { var pass = true; div.hide().show( speed ).each( function() { if ( this.style.display === "none" ) { pass = false; } } ); assert.ok( pass, "Show with " + name ); } ); jQuery.each( speeds, function( name, speed ) { var pass = true; div.hide().show( speed, function() { pass = false; } ); assert.ok( pass, "Show with " + name + " does not call animate callback" ); } ); jQuery( "<div id='show-tests'>" + "<div><p><a href='#'></a></p><code></code><pre></pre><span></span></div>" + "<table><thead><tr><th></th></tr></thead><tbody><tr><td></td></tr></tbody></table>" + "<ul><li></li></ul></div>" ).appendTo( "#qunit-fixture" ).find( "*" ).css( "display", "none" ); test = { "div": "block", "p": "block", "a": "inline", "code": "inline", "pre": "block", "span": "inline", "table": "table", "thead": "table-header-group", "tbody": "table-row-group", "tr": "table-row", "th": "table-cell", "td": "table-cell", "ul": "block", "li": "list-item" }; jQuery.each( test, function( selector, expected ) { var elem = jQuery( selector, "#show-tests" ).show(); assert.equal( elem.css( "display" ), expected, "Show using correct display type for " + selector ); } ); jQuery( "#show-tests" ).remove(); // Make sure that showing or hiding a text node doesn't cause an error jQuery( "<div>test</div> text <span>test</span>" ).show().remove(); jQuery( "<div>test</div> text <span>test</span>" ).hide().remove(); } ); supportjQuery.each( hideOptions, function( type, setup ) { QUnit.test( "show(Number) - " + type + " hidden", function( assert ) { assert.expect( 30 ); jQuery( "<div id='show-tests'>" + "<div><p><a href='#'></a></p><code></code><pre></pre><span></span></div>" + "<table><thead><tr><th></th></tr></thead><tbody><tr><td></td></tr></tbody>" + "</table>" + "<ul><li></li></ul></div>" ).appendTo( "#qunit-fixture" ).find( "*" ).each( setup ); // Note: inline elements are expected to be inline-block // because we're showing width/height // Can't animate width/height inline // See trac-14344 var test = { "div": "block", "p": "block", "a": "inline", "code": "inline", "pre": "block", "span": "inline", "table": "table", "thead": "table-header-group", "tbody": "table-row-group", "tr": "table-row", "th": "table-cell", "td": "table-cell", "ul": "block", "li": "list-item" }; jQuery.each( test, function( selector ) { jQuery( selector, "#show-tests" ).show( fxInterval * 10 ); } ); this.clock.tick( fxInterval * 5 ); jQuery.each( test, function( selector, expected ) { jQuery( selector, "#show-tests" ).each( function() { assert.equal( jQuery( this ).css( "display" ), expected === "inline" ? "inline-block" : expected, "Correct display type during animation for " + selector ); } ); } ); this.clock.tick( fxInterval * 5 ); jQuery.each( test, function( selector, expected ) { jQuery( selector, "#show-tests" ).each( function() { assert.equal( jQuery( this ).css( "display" ), expected, "Correct display type after animation for " + selector ); } ); } ); jQuery( "#show-tests" ).remove(); } ); } ); // Supports trac-7397 supportjQuery.each( hideOptions, function( type, setup ) { QUnit.test( "Persist correct display value - " + type + " hidden", function( assert ) { assert.expect( 3 ); jQuery( "<div id='show-tests'><span style='position:absolute;'>foo</span></div>" ) .appendTo( "#qunit-fixture" ).find( "*" ).each( setup ); var $span = jQuery( "#show-tests span" ), displayNone = $span.css( "display" ), display = "", clock = this.clock; $span.show(); display = $span.css( "display" ); $span.hide(); $span.fadeIn( fxInterval * 10, function() { assert.equal( $span.css( "display" ), display, "Expecting display: " + display ); $span.fadeOut( fxInterval * 10, function() { assert.equal( $span.css( "display" ), displayNone, "Expecting display: " + displayNone ); $span.fadeIn( fxInterval * 10, function() { assert.equal( $span.css( "display" ), display, "Expecting display: " + display ); } ); } ); } ); clock.tick( fxInterval * 30 ); } ); // Support: IE 11+ // IE doesn't support Shadow DOM. QUnit.testUnlessIE( "Persist correct display value - " + type + " hidden, shadow child", function( assert ) { assert.expect( 3 ); jQuery( "<div id='shadowHost'></div>" ).appendTo( "#qunit-fixture" ); var shadowHost = document.querySelector( "#shadowHost" ); var shadowRoot = shadowHost.attachShadow( { mode: "open" } ); shadowRoot.innerHTML = "<style>.hidden{display: none;}</style>" + "<span id='shadowChild' class='hidden'></span>"; var shadowChild = shadowRoot.querySelector( "#shadowChild" ); var $shadowChild = jQuery( shadowChild ); var displayNone = "none"; var display = "inline"; var clock = this.clock; $shadowChild.fadeIn( fxInterval * 10, function() { assert.equal( $shadowChild.css( "display" ), display, "Expecting shadow display: " + display ); $shadowChild.fadeOut( fxInterval * 10, function() { assert.equal( $shadowChild.css( "display" ), displayNone, "Expecting shadow display: " + displayNone ); $shadowChild.fadeIn( fxInterval * 10, function() { assert.equal( $shadowChild.css( "display" ), display, "Expecting shadow display: " + display ); } ); } ); } ); clock.tick( fxInterval * 30 ); } ); } ); QUnit.test( "animate(Hash, Object, Function)", function( assert ) { assert.expect( 1 ); var hash = { opacity: "show" }, hashCopy = jQuery.extend( {}, hash ); jQuery( "#foo" ).animate( hash, 0, function() { assert.equal( hash.opacity, hashCopy.opacity, "Check if animate changed the hash parameter" ); } ); } ); QUnit.test( "animate relative values", function( assert ) { var value = 40, clock = this.clock, bases = [ "%", "px", "em" ], adjustments = [ "px", "em" ], container = jQuery( "<div></div>" ) .css( { position: "absolute", height: "50em", width: "50em" } ), animations = bases.length * adjustments.length; assert.expect( 2 * animations ); jQuery.each( bases, function( _, baseUnit ) { jQuery.each( adjustments, function( _, adjustUnit ) { var base = value + baseUnit, adjust = { height: "+=2" + adjustUnit, width: "-=2" + adjustUnit }, elem = jQuery( "<div></div>" ) .appendTo( container.clone().appendTo( "#qunit-fixture" ) ) .css( { position: "absolute", height: base, width: value + adjustUnit } ), baseScale = elem[ 0 ].offsetHeight / value, adjustScale = elem[ 0 ].offsetWidth / value; elem.css( "width", base ).animate( adjust, fxInterval * 10, function() { assert.equal( this.offsetHeight, value * baseScale + 2 * adjustScale, baseUnit + "+=" + adjustUnit ); assert.equal( this.offsetWidth, value * baseScale - 2 * adjustScale, baseUnit + "-=" + adjustUnit ); } ); clock.tick( fxInterval * 10 ); } ); } ); } ); QUnit.test( "animate negative height", function( assert ) { assert.expect( 1 ); jQuery( "#foo" ).animate( { height: -100 }, fxInterval * 10, function() { assert.equal( this.offsetHeight, 0, "Verify height." ); } ); this.clock.tick( fxInterval * 10 ); } ); QUnit.test( "animate negative margin", function( assert ) { assert.expect( 1 ); jQuery( "#foo" ).animate( { "marginTop": -100 }, fxInterval * 10, function() { assert.equal( jQuery( this ).css( "marginTop" ), "-100px", "Verify margin." ); } ); this.clock.tick( fxInterval * 10 ); } ); QUnit.test( "animate negative margin with px", function( assert ) { assert.expect( 1 ); jQuery( "#foo" ).animate( { marginTop: "-100px" }, fxInterval * 10, function() { assert.equal( jQuery( this ).css( "marginTop" ), "-100px", "Verify margin." ); } ); this.clock.tick( fxInterval * 10 ); } ); QUnit.test( "animate negative padding", function( assert ) { assert.expect( 1 ); jQuery( "#foo" ).animate( { "paddingBottom": -100 }, fxInterval * 10, function() { assert.equal( jQuery( this ).css( "paddingBottom" ), "0px", "Verify paddingBottom." ); } ); this.clock.tick( fxInterval * 10 ); } ); QUnit.test( "animate block as inline width/height", function( assert ) { assert.expect( 3 ); jQuery( "#foo" ).css( { display: "inline", width: "", height: "" } ).animate( { width: 42, height: 42 }, fxInterval * 10, function() { assert.equal( jQuery( this ).css( "display" ), "inline-block", "inline-block was set on non-floated inline element when animating width/height" ); assert.equal( this.offsetWidth, 42, "width was animated" ); assert.equal( this.offsetHeight, 42, "height was animated" ); } ); this.clock.tick( fxInterval * 10 ); } ); QUnit.test( "animate native inline width/height", function( assert ) { assert.expect( 3 ); jQuery( "#foo" ).css( { display: "", width: "", height: "" } ) .append( "<span>text</span>" ) .children( "span" ) .animate( { width: 42, height: 42 }, fxInterval * 10, function() { assert.equal( jQuery( this ).css( "display" ), "inline-block", "inline-block was set on non-floated inline element when animating width/height" ); assert.equal( this.offsetWidth, 42, "width was animated" ); assert.equal( this.offsetHeight, 42, "height was animated" ); } ); this.clock.tick( fxInterval * 10 ); } ); QUnit.test( "animate block width/height", function( assert ) { assert.expect( 3 ); jQuery( "<div>" ).appendTo( "#qunit-fixture" ).css( { display: "block", width: 20, height: 20, paddingLeft: 60 } ).animate( { width: 42, height: 42 }, { duration: fxInterval * 10, step: function() { if ( jQuery( this ).width() > 42 ) { assert.ok( false, "width was incorrectly augmented during animation" ); } }, complete: function() { assert.equal( jQuery( this ).css( "display" ), "block", "inline-block was not set on block element when animating width/height" ); assert.equal( jQuery( this ).width(), 42, "width was animated" ); assert.equal( jQuery( this ).height(), 42, "height was animated" ); } } ); this.clock.tick( fxInterval * 10 ); } ); QUnit.test( "animate table width/height", function( assert ) { assert.expect( 1 ); jQuery( "#table" ).animate( { width: 42, height: 42 }, fxInterval * 10, function() { assert.equal( jQuery( this ).css( "display" ), "table", "display mode is correct" ); } ); this.clock.tick( fxInterval * 10 ); } ); QUnit.test( "animate table-row width/height", function( assert ) { assert.expect( 3 ); var tr = jQuery( "#table" ) .attr( { "cellspacing": 0, "cellpadding": 0, "border": 0 } ) .html( "<tr style='height:42px;'><td style='padding:0;'><div style='width:20px;height:20px;'></div></td></tr>" ) .find( "tr" ); tr.animate( { width: 10, height: 10 }, fxInterval * 10, function() { assert.equal( jQuery( this ).css( "display" ), "table-row", "display mode is correct" ); assert.equal( this.offsetWidth, 20, "width animated to shrink wrap point" ); assert.equal( this.offsetHeight, 20, "height animated to shrink wrap point" ); } ); this.clock.tick( fxInterval * 10 ); } ); QUnit.test( "animate table-cell width/height", function( assert ) { assert.expect( 3 ); var td = jQuery( "#table" ) .attr( { "cellspacing": 0, "cellpadding": 0, "border": 0 } ) .html( "<tr><td style='width:42px;height:42px;padding:0;'><div style='width:20px;height:20px;'></div></td></tr>" ) .find( "td" ); td.animate( { width: 10, height: 10 }, fxInterval * 10, function() { assert.equal( jQuery( this ).css( "display" ), "table-cell", "display mode is correct" ); assert.equal( this.offsetWidth, 20, "width animated to shrink wrap point" ); assert.equal( this.offsetHeight, 20, "height animated to shrink wrap point" ); } ); this.clock.tick( fxInterval * 10 ); } ); QUnit.test( "animate percentage(%) on width/height", function( assert ) { assert.expect( 2 ); var $div = jQuery( "<div style='position:absolute;top:-999px;left:-999px;width:60px;height:60px;'><div style='width:50%;height:50%;'></div></div>" ) .appendTo( "#qunit-fixture" ).children( "div" ); $div.animate( { width: "25%", height: "25%" }, fxInterval, function() { var $this = jQuery( this ); assert.equal( $this.css( "width" ), "15px", "Width was animated to 15px rather than 25px" ); assert.equal( $this.css( "height" ), "15px", "Height was animated to 15px rather than 25px" ); } ); this.clock.tick( fxInterval * 1.5 ); } ); QUnit.test( "animate resets overflow-x and overflow-y when finished", function( assert ) { assert.expect( 2 ); jQuery( "#foo" ) .css( { display: "block", width: 20, height: 20, overflowX: "visible", overflowY: "auto" } ) .animate( { width: 42, height: 42 }, fxInterval * 10, function() { assert.equal( this.style.overflowX, "visible", "overflow-x is visible" ); assert.equal( this.style.overflowY, "auto", "overflow-y is auto" ); } ); this.clock.tick( fxInterval * 10 ); } ); QUnit.test( "animate option { queue: false }", function( assert ) { assert.expect( 2 ); var foo = jQuery( "#foo" ); foo.animate( { fontSize: "2em" }, { queue: false, duration: fxInterval, complete: function() { assert.ok( true, "Animation Completed" ); } } ); this.clock.tick( fxInterval ); assert.equal( foo.queue().length, 0, "Queue is empty" ); } ); QUnit.test( "animate option { queue: true }", function( assert ) { assert.expect( 2 ); var foo = jQuery( "#foo" ); foo.animate( { fontSize: "2em" }, { queue: true, duration: fxInterval, complete: function() { assert.ok( true, "Animation Completed" ); } } ); assert.notEqual( foo.queue().length, 0, "Default queue is not empty" ); //clear out existing timers before next test this.clock.tick( fxInterval ); } ); QUnit.test( "animate option { queue: 'name' }", function( assert ) { assert.expect( 5 ); var foo = jQuery( "#foo" ), origWidth = parseFloat( foo.css( "width" ) ), order = []; foo.animate( { width: origWidth + 100 }, { queue: "name", duration: 1, complete: function() { // second callback function order.push( 2 ); assert.equal( parseFloat( foo.css( "width" ) ), origWidth + 100, "Animation ended" ); assert.equal( foo.queue( "name" ).length, 1, "Queue length of 'name' queue" ); } } ).queue( "name", function() { // last callback function assert.deepEqual( order, [ 1, 2 ], "Callbacks in expected order" ); } ); // this is the first callback function that should be called order.push( 1 ); assert.equal( parseFloat( foo.css( "width" ) ), origWidth, "Animation does not start on its own." ); assert.equal( foo.queue( "name" ).length, 2, "Queue length of 'name' queue" ); foo.dequeue( "name" ); this.clock.tick( fxInterval ); } ); QUnit.test( "animate with no properties", function( assert ) { assert.expect( 2 ); var foo, divs = jQuery( "div" ), count = 0; divs.animate( {}, function() { count++; } ); assert.equal( divs.length, count, "Make sure that callback is called for each element in the set." ); foo = jQuery( "#foo" ); foo.animate( {} ); foo.animate( { top: 10 }, fxInterval * 10, function() { assert.ok( true, "Animation was properly dequeued." ); } ); this.clock.tick( fxInterval * 10 ); } ); QUnit.test( "animate duration 0", function( assert ) { assert.expect( 11 ); var $elem, $elems = jQuery( [ { a: 0 }, { a: 0 } ] ), counter = 0; assert.equal( jQuery.timers.length, 0, "Make sure no animation was running from another test" ); $elems.eq( 0 ).animate( { a: 1 }, 0, function() { assert.ok( true, "Animate a simple property." ); counter++; } ); // Failed until [6115] assert.equal( jQuery.timers.length, 0, "Make sure synchronic animations are not left on jQuery.timers" ); assert.equal( counter, 1, "One synchronic animations" ); $elems.animate( { a: 2 }, 0, function() { assert.ok( true, "Animate a second simple property." ); counter++; } ); assert.equal( counter, 3, "Multiple synchronic animations" ); $elems.eq( 0 ).animate( { a: 3 }, 0, function() { assert.ok( true, "Animate a third simple property." ); counter++; } ); $elems.eq( 1 ).animate( { a: 3 }, fxInterval * 20, function() { counter++; // Failed until [6115] assert.equal( counter, 5, "One synchronic and one asynchronic" ); } ); this.clock.tick( fxInterval * 20 ); $elem = jQuery( "<div></div>" ); $elem.show( 0, function() { assert.ok( true, "Show callback with no duration" ); } ); $elem.hide( 0, function() { assert.ok( true, "Hide callback with no duration" ); } ); // manually clean up detached elements $elem.remove(); } ); QUnit.test( "animate hyphenated properties", function( assert ) { assert.expect( 1 ); jQuery( "#foo" ) .css( "font-size", 10 ) .animate( { "font-size": 20 }, fxInterval * 20, function() { assert.equal( this.style.fontSize, "20px", "The font-size property was animated." ); } ); // FIXME why is this double only when run with other tests this.clock.tick( fxInterval * 40 ); } ); QUnit.test( "animate non-element", function( assert ) { assert.expect( 1 ); var obj = { test: 0 }; jQuery( obj ).animate( { test: 200 }, fxInterval * 20, function() { assert.equal( obj.test, 200, "The custom property should be modified." ); } ); this.clock.tick( fxInterval * 20 ); } ); QUnit.test( "animate non-element's zIndex without appending \"px\"", function( assert ) { assert.expect( 1 ); var obj = { zIndex: 0 }; jQuery( obj ).animate( { zIndex: 200 }, fxInterval * 20, function() { assert.equal( obj.zIndex, 200, "The custom property should be modified without appending \"px\"." ); } ); this.clock.tick( fxInterval * 20 ); } ); QUnit.test( "stop()", function( assert ) { assert.expect( 4 ); var $one, $two, $foo = jQuery( "#foo" ), w = 0, nw; $foo.hide().css( "width", 200 ) .animate( { "width": "show" }, fxInterval * 150 ); this.clock.tick( fxInterval * 10 ); nw = $foo.css( "width" ); assert.notEqual( parseFloat( nw ), w, "An animation occurred " + nw + " " + w + "px" ); $foo.stop(); nw = $foo.css( "width" ); assert.notEqual( parseFloat( nw ), w, "Stop didn't reset the animation " + nw + " " + w + "px" ); this.clock.tick( fxInterval * 10 ); $foo.removeData(); $foo.removeData( undefined, true ); assert.equal( nw, $foo.css( "width" ), "The animation didn't continue" ); $one = jQuery( "#fadein" ); $two = jQuery( "#show" ); $one.fadeTo( fxInterval * 10, 0, function() { $one.stop(); } ); this.clock.tick( fxInterval * 10 ); $two.fadeTo( fxInterval * 10, 0, function() { assert.equal( $two.css( "opacity" ), "0", "Stop does not interfere with animations on other elements (trac-6641)" ); // Reset styles $one.add( $two ).css( "opacity", "" ); } ); this.clock.tick( fxInterval * 10 ); } ); QUnit.test( "stop() - several in queue", function( assert ) { assert.expect( 5 ); var nw, $foo = jQuery( "#foo" ); // default duration is 400ms, so 800px ensures we aren't 0 or 1 after 1ms $foo.hide().css( "width", 800 ); $foo.animate( { "width": "show" }, 400, "linear" ); $foo.animate( { "width": "hide" } ); $foo.animate( { "width": "show" } ); this.clock.tick( 1 ); jQuery.fx.tick(); assert.equal( $foo.queue().length, 3, "3 in the queue" ); nw = $foo.css( "width" ); assert.notEqual( parseFloat( nw ), 1, "An animation occurred " + nw ); $foo.stop(); assert.equal( $foo.queue().length, 2, "2 in the queue" ); nw = $foo.css( "width" ); assert.notEqual( parseFloat( nw ), 1, "Stop didn't reset the animation " + nw ); $foo.stop( true ); assert.equal( $foo.queue().length, 0, "0 in the queue" ); } ); QUnit.test( "stop(clearQueue)", function( assert ) { assert.expect( 4 ); var $foo = jQuery( "#foo" ), w = 0, nw; $foo.hide().css( "width", fxInterval * 20 ).css( "width" ); $foo.animate( { "width": "show" }, fxInterval * 100 ); $foo.animate( { "width": "hide" }, fxInterval * 100 ); $foo.animate( { "width": "show" }, fxInterval * 100 ); this.clock.tick( fxInterval * 10 ); nw = $foo.css( "width" ); assert.ok( parseFloat( nw ) !== w, "An animation occurred " + nw + " " + w + "px" ); $foo.stop( true ); nw = $foo.css( "width" ); assert.ok( parseFloat( nw ) !== w, "Stop didn't reset the animation " + nw + " " + w + "px" ); assert.equal( $foo.queue().length, 0, "The animation queue was cleared" ); this.clock.tick( fxInterval * 10 ); assert.equal( nw, $foo.css( "width" ), "The animation didn't continue" ); } ); QUnit.test( "stop(clearQueue, gotoEnd)", function( assert ) { assert.expect( 1 ); var $foo = jQuery( "#foo" ), w = 0, nw; $foo.hide().css( "width", fxInterval * 20 ).css( "width" ); $foo.animate( { width: "show" }, fxInterval * 100 ); $foo.animate( { width: "hide" }, fxInterval * 100 ); $foo.animate( { width: "show" }, fxInterval * 100 ); $foo.animate( { width: "hide" }, fxInterval * 100 ); this.clock.tick( fxInterval * 10 ); nw = $foo.css( "width" ); assert.ok( parseFloat( nw ) !== w, "An animation occurred " + nw + " " + w + "px" ); $foo.stop( false, true ); nw = $foo.css( "width" ); // Disabled, being flaky //equal( nw, 1, "Stop() reset the animation" ); this.clock.tick( fxInterval * 10 ); // Disabled, being flaky //equal( $foo.queue().length, 2, "The next animation continued" ); $foo.stop( true ); } ); QUnit.test( "stop( queue, ..., ... ) - Stop single queues", function( assert ) { assert.expect( 3 ); var saved, foo = jQuery( "#foo" ).css( { width: 200, height: 200 } ); foo.animate( { width: 400 }, { duration: fxInterval * 50, complete: function() { assert.equal( parseFloat( foo.css( "width" ) ), 400, "Animation completed for standard queue" ); assert.equal( parseFloat( foo.css( "height" ) ), saved, "Height was not changed after the second stop" ); } } ); foo.animate( { height: 400 }, { duration: fxInterval * 100, queue: "height" } ).dequeue( "height" ).stop( "height", false, true ); assert.equal( parseFloat( foo.css( "height" ) ), 400, "Height was stopped with gotoEnd" ); foo.animate( { height: 200 }, { duration: fxInterval * 100, queue: "height" } ).dequeue( "height" ).stop( "height", false, false ); saved = parseFloat( foo.css( "height" ) ); this.clock.tick( fxInterval * 50 ); } ); QUnit[ QUnit.jQuerySelectors ? "test" : "skip" ]( "toggle()", function( assert ) { assert.expect( 6 ); var x = jQuery( "#foo" ); assert.ok( x.is( ":visible" ), "is visible" ); x.toggle(); assert.ok( x.is( ":hidden" ), "is hidden" ); x.toggle(); assert.ok( x.is( ":visible" ), "is visible again" ); x.toggle( true ); assert.ok( x.is( ":visible" ), "is visible" ); x.toggle( false ); assert.ok( x.is( ":hidden" ), "is hidden" ); x.toggle( true ); assert.ok( x.is( ":visible" ), "is visible again" ); } ); QUnit.test( "jQuery.fx.prototype.cur() - <1.8 Back Compat", function( assert ) { assert.expect( 7 ); var div = jQuery( "<div></div>" ).appendTo( "#qunit-fixture" ).css( { color: "#ABC", border: "5px solid black", left: "auto", marginBottom: "-11000px" } )[ 0 ]; assert.equal( ( new jQuery.fx( div, {}, "color" ) ).cur(), jQuery.css( div, "color" ), "Return the same value as jQuery.css for complex properties (bug trac-7912)" ); assert.strictEqual( ( new jQuery.fx( div, {}, "borderLeftWidth" ) ).cur(), 5, "Return simple values parsed as Float" ); // backgroundPosition actually returns 0% 0% in most browser // this fakes a "" return // hook now gets called twice because Tween will grab the current // value as it is being newed jQuery.cssHooks.backgroundPosition = { get: function() { assert.ok( true, "hook used" ); return ""; } }; assert.strictEqual( ( new jQuery.fx( div, {}, "backgroundPosition" ) ).cur(), 0, "Return 0 when jQuery.css returns an empty string" ); delete jQuery.cssHooks.backgroundPosition; assert.strictEqual( ( new jQuery.fx( div, {}, "left" ) ).cur(), 0, "Return 0 when jQuery.css returns 'auto'" ); assert.equal( ( new jQuery.fx( div, {}, "marginBottom" ) ).cur(), -11000, "support negative values < -10000 (bug trac-7193)" ); jQuery( div ).remove(); } ); QUnit.test( "Overflow and Display", function( assert ) { assert.expect( 4 ); var testClass = jQuery.makeTest( "Overflow and Display" ) .addClass( "overflow inline" ), testStyle = jQuery.makeTest( "Overflow and Display (inline style)" ) .css( { overflow: "visible", display: "inline" } ), done = function() { assert.equal( jQuery.css( this, "overflow" ), "visible", "Overflow should be 'visible'" ); assert.equal( jQuery.css( this, "display" ), "inline", "Display should be 'inline'" ); }; testClass.add( testStyle ) .addClass( "widewidth" ) .text( "Some sample text." ) .before( "text before" ) .after( "text after" ) .animate( { opacity: 0.5 }, "slow", done ); this.clock.tick( 600 + fxInterval ); } ); jQuery.each( { "CSS Auto": function( elem, prop ) { jQuery( elem ).addClass( "auto" + prop ) .text( "This is a long string of text." ); return ""; }, "JS Auto": function( elem, prop ) { jQuery( elem ).css( prop, "" ) .text( "This is a long string of text." ); return ""; }, "CSS 100": function( elem, prop ) { jQuery( elem ).addClass( "large" + prop ); return ""; }, "JS 100": function( elem, prop ) { jQuery( elem ).css( prop, prop === "opacity" ? 1 : "100px" ); return prop === "opacity" ? 1 : 100; }, "CSS 50": function( elem, prop ) { jQuery( elem ).addClass( "med" + prop ); return ""; }, "JS 50": function( elem, prop ) { jQuery( elem ).css( prop, prop === "opacity" ? 0.50 : "50px" ); return prop === "opacity" ? 0.5 : 50; }, "CSS 0": function( elem, prop ) { jQuery( elem ).addClass( "no" + prop ); return ""; }, "JS 0": function( elem, prop ) { jQuery( elem ).css( prop, prop === "opacity" ? 0 : "0px" ); return 0; } }, function( fn, f ) { jQuery.each( { "show": function( elem, prop ) { jQuery( elem ).hide().addClass( "wide" + prop ); return "show"; }, "hide": function( elem, prop ) { jQuery( elem ).addClass( "wide" + prop ); return "hide"; }, "100": function( elem, prop ) { jQuery( elem ).addClass( "wide" + prop ); return prop === "opacity" ? 1 : 100; }, "50": function( elem, prop ) { return prop === "opacity" ? 0.50 : 50; }, "0": function( elem ) { jQuery( elem ).addClass( "noback" ); return 0; } }, function( tn, t ) { QUnit.test( fn + " to " + tn, function( assert ) { var num, anim, elem = jQuery.makeTest( fn + " to " + tn ), t_w = t( elem, "width" ), f_w = f( elem, "width" ), t_h = t( elem, "height" ), f_h = f( elem, "height" ), t_o = t( elem, "opacity" ), f_o = f( elem, "opacity" ); if ( f_o === "" ) { f_o = 1; } num = 0; // TODO: uncrowd this if ( t_h === "show" ) { num++; } if ( t_w === "show" ) { num++; } if ( t_w === "hide" || t_w === "show" ) { num++; } if ( t_h === "hide" || t_h === "show" ) { num++; } if ( t_o === "hide" || t_o === "show" ) { num++; } if ( t_w === "hide" ) { num++; } if ( t_o.constructor === Number ) { num += 2; } if ( t_w.constructor === Number ) { num += 2; } if ( t_h.constructor === Number ) { num += 2; } assert.expect( num ); anim = { width: t_w, height: t_h, opacity: t_o }; elem.animate( anim, fxInterval * 5 ); jQuery.when( elem ).done( function( $elem ) { var cur_o, cur_w, cur_h, old_h, elem = $elem[ 0 ]; if ( t_w === "show" ) { assert.equal( $elem.css( "display" ), "block", "Showing, display should block: " + elem.style.display ); } if ( t_w === "hide" || t_w === "show" ) { assert.ok( f_w === "" ? elem.style.width === f_w : elem.style.width.indexOf( f_w ) === 0, "Width must be reset to " + f_w + ": " + elem.style.width ); } if ( t_h === "hide" || t_h === "show" ) { assert.ok( f_h === "" ? elem.style.height === f_h : elem.style.height.indexOf( f_h ) === 0, "Height must be reset to " + f_h + ": " + elem.style.height ); } cur_o = jQuery.style( elem, "opacity" ); if ( f_o !== jQuery.css( elem, "opacity" ) ) { f_o = f( elem, "opacity" ); } if ( t_o === "hide" || t_o === "show" ) { assert.equal( cur_o, f_o, "Opacity must be reset to " + f_o + ": " + cur_o ); } if ( t_w === "hide" ) { assert.equal( elem.style.display, "none", "Hiding, display should be none: " + elem.style.display ); } if ( t_o.constructor === Number ) { assert.equal( cur_o, t_o, "Final opacity should be " + t_o + ": " + cur_o ); assert.ok( jQuery.css( elem, "opacity" ) !== "" || cur_o === t_o, "Opacity should be explicitly set to " + t_o + ", is instead: " + cur_o ); } if ( t_w.constructor === Number ) { assert.equal( elem.style.width, t_w + "px", "Final width should be " + t_w + ": " + elem.style.width ); cur_w = jQuery.css( elem, "width" ); assert.ok( elem.style.width !== "" || cur_w === t_w, "Width should be explicitly set to " + t_w + ", is instead: " + cur_w ); } if ( t_h.constructor === Number ) { assert.equal( elem.style.height, t_h + "px", "Final height should be " + t_h + ": " + elem.style.height ); cur_h = jQuery.css( elem, "height" ); assert.ok( elem.style.height !== "" || cur_h === t_h, "Height should be explicitly set to " + t_h + ", is instead: " + cur_h ); } if ( t_h === "show" ) { old_h = jQuery.css( elem, "height" ); jQuery( elem ).append( "<br/>Some more text<br/>and some more..." ); if ( /Auto/.test( fn ) ) { assert.notEqual( jQuery.css( elem, "height" ), old_h, "Make sure height is auto." ); } else { assert.equal( jQuery.css( elem, "height" ), old_h, "Make sure height is not auto." ); } } // manually remove generated element jQuery( elem ).remove(); } ); this.clock.tick( fxInterval * 10 ); } ); } ); } ); QUnit.test( "Effects chaining", function( assert ) { var remaining = 16, props = [ "opacity", "height", "width", "display", "overflow" ], setup = function( name, selector ) { var $el = jQuery( selector ); return $el.data( getProps( $el[ 0 ] ) ).data( "name", name ); }, check = function() { var data = jQuery.data( this ), name = data.name; delete data.name; assert.deepEqual( getProps( this ), data, name ); jQuery.removeData( this ); }, getProps = function( el ) { var obj = {}; jQuery.each( props, function( i, prop ) { obj[ prop ] = prop === "overflow" && el.style[ prop ] || jQuery.css( el, prop ); } ); return obj; }; assert.expect( remaining );
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
true
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/test/unit/css.js
test/unit/css.js
if ( includesModule( "css" ) ) { QUnit.module( "css", { afterEach: moduleTeardown } ); QUnit.test( "css(String|Hash)", function( assert ) { assert.expect( 42 ); assert.equal( jQuery( "#qunit-fixture" ).css( "display" ), "block", "Check for css property \"display\"" ); var $child, div, div2, child, prctval, checkval, old; $child = jQuery( "#nothiddendivchild" ).css( { "width": "20%", "height": "20%" } ); assert.notEqual( $child.css( "width" ), "20px", "Retrieving a width percentage on the child of a hidden div returns percentage" ); assert.notEqual( $child.css( "height" ), "20px", "Retrieving a height percentage on the child of a hidden div returns percentage" ); div = jQuery( "<div></div>" ); // These should be "auto" (or some better value) // temporarily provide "0px" for backwards compat assert.equal( div.css( "width" ), "0px", "Width on disconnected node." ); assert.equal( div.css( "height" ), "0px", "Height on disconnected node." ); div.css( { "width": 4, "height": 4 } ); assert.equal( div.css( "width" ), "4px", "Width on disconnected node." ); assert.equal( div.css( "height" ), "4px", "Height on disconnected node." ); div2 = jQuery( "<div style='display:none;'><input type='text' style='height:20px;'/><textarea style='height:20px;'></textarea><div style='height:20px;'></div></div>" ).appendTo( "body" ); assert.equal( div2.find( "input" ).css( "height" ), "20px", "Height on hidden input." ); assert.equal( div2.find( "textarea" ).css( "height" ), "20px", "Height on hidden textarea." ); assert.equal( div2.find( "div" ).css( "height" ), "20px", "Height on hidden div." ); div2.remove(); // handle negative numbers by setting to zero trac-11604 jQuery( "#nothiddendiv" ).css( { "width": 1, "height": 1 } ); jQuery( "#nothiddendiv" ).css( { "overflow": "hidden", "width": -1, "height": -1 } ); assert.equal( parseFloat( jQuery( "#nothiddendiv" ).css( "width" ) ), 0, "Test negative width set to 0" ); assert.equal( parseFloat( jQuery( "#nothiddendiv" ).css( "height" ) ), 0, "Test negative height set to 0" ); assert.equal( jQuery( "<div style='display: none;'></div>" ).css( "display" ), "none", "Styles on disconnected nodes" ); jQuery( "#floatTest" ).css( { "float": "right" } ); assert.equal( jQuery( "#floatTest" ).css( "float" ), "right", "Modified CSS float using \"float\": Assert float is right" ); jQuery( "#floatTest" ).css( { "font-size": "30px" } ); assert.equal( jQuery( "#floatTest" ).css( "font-size" ), "30px", "Modified CSS font-size: Assert font-size is 30px" ); jQuery.each( "0,0.25,0.5,0.75,1".split( "," ), function( i, n ) { jQuery( "#foo" ).css( { "opacity": n } ); assert.equal( jQuery( "#foo" ).css( "opacity" ), parseFloat( n ), "Assert opacity is " + parseFloat( n ) + " as a String" ); jQuery( "#foo" ).css( { "opacity": parseFloat( n ) } ); assert.equal( jQuery( "#foo" ).css( "opacity" ), parseFloat( n ), "Assert opacity is " + parseFloat( n ) + " as a Number" ); } ); jQuery( "#foo" ).css( { "opacity": "" } ); assert.equal( jQuery( "#foo" ).css( "opacity" ), "1", "Assert opacity is 1 when set to an empty String" ); assert.equal( jQuery( "#empty" ).css( "opacity" ), "0", "Assert opacity is accessible" ); jQuery( "#empty" ).css( { "opacity": "1" } ); assert.equal( jQuery( "#empty" ).css( "opacity" ), "1", "Assert opacity is taken from style attribute when set" ); div = jQuery( "#nothiddendiv" ); child = jQuery( "#nothiddendivchild" ); assert.equal( parseInt( div.css( "fontSize" ), 10 ), 16, "Verify fontSize px set." ); assert.equal( parseInt( div.css( "font-size" ), 10 ), 16, "Verify fontSize px set." ); assert.equal( parseInt( child.css( "fontSize" ), 10 ), 16, "Verify fontSize px set." ); assert.equal( parseInt( child.css( "font-size" ), 10 ), 16, "Verify fontSize px set." ); child.css( "height", "100%" ); assert.equal( child[ 0 ].style.height, "100%", "Make sure the height is being set correctly." ); child.attr( "class", "em" ); assert.equal( parseInt( child.css( "fontSize" ), 10 ), 32, "Verify fontSize em set." ); // Have to verify this as the result depends upon the browser's CSS // support for font-size percentages child.attr( "class", "prct" ); prctval = parseInt( child.css( "fontSize" ), 10 ); checkval = 0; if ( prctval === 16 || prctval === 24 ) { checkval = prctval; } assert.equal( prctval, checkval, "Verify fontSize % set." ); assert.equal( typeof child.css( "width" ), "string", "Make sure that a string width is returned from css('width')." ); old = child[ 0 ].style.height; // Test NaN child.css( "height", parseFloat( "zoo" ) ); assert.equal( child[ 0 ].style.height, old, "Make sure height isn't changed on NaN." ); // Test null child.css( "height", null ); assert.equal( child[ 0 ].style.height, old, "Make sure height isn't changed on null." ); old = child[ 0 ].style.fontSize; // Test NaN child.css( "font-size", parseFloat( "zoo" ) ); assert.equal( child[ 0 ].style.fontSize, old, "Make sure font-size isn't changed on NaN." ); // Test null child.css( "font-size", null ); assert.equal( child[ 0 ].style.fontSize, old, "Make sure font-size isn't changed on null." ); assert.strictEqual( child.css( "x-fake" ), undefined, "Make sure undefined is returned from css(nonexistent)." ); div = jQuery( "<div></div>" ).css( { position: "absolute", "z-index": 1000 } ).appendTo( "#qunit-fixture" ); assert.strictEqual( div.css( "z-index" ), "1000", "Make sure that a string z-index is returned from css('z-index') (trac-14432)." ); } ); QUnit.test( "css() explicit and relative values", function( assert ) { assert.expect( 29 ); var $elem = jQuery( "#nothiddendiv" ); $elem.css( { "width": 1, "height": 1, "paddingLeft": "1px", "opacity": 1 } ); assert.equal( $elem.css( "width" ), "1px", "Initial css set or width/height works (hash)" ); assert.equal( $elem.css( "paddingLeft" ), "1px", "Initial css set of paddingLeft works (hash)" ); assert.equal( $elem.css( "opacity" ), "1", "Initial css set of opacity works (hash)" ); $elem.css( { width: "+=9" } ); assert.equal( $elem.css( "width" ), "10px", "'+=9' on width (hash)" ); $elem.css( { "width": "-=9" } ); assert.equal( $elem.css( "width" ), "1px", "'-=9' on width (hash)" ); $elem.css( { "width": "+=9px" } ); assert.equal( $elem.css( "width" ), "10px", "'+=9px' on width (hash)" ); $elem.css( { "width": "-=9px" } ); assert.equal( $elem.css( "width" ), "1px", "'-=9px' on width (hash)" ); $elem.css( "width", "+=9" ); assert.equal( $elem.css( "width" ), "10px", "'+=9' on width (params)" ); $elem.css( "width", "-=9" ); assert.equal( $elem.css( "width" ), "1px", "'-=9' on width (params)" ); $elem.css( "width", "+=9px" ); assert.equal( $elem.css( "width" ), "10px", "'+=9px' on width (params)" ); $elem.css( "width", "-=9px" ); assert.equal( $elem.css( "width" ), "1px", "'-=9px' on width (params)" ); $elem.css( "width", "-=-9px" ); assert.equal( $elem.css( "width" ), "10px", "'-=-9px' on width (params)" ); $elem.css( "width", "+=-9px" ); assert.equal( $elem.css( "width" ), "1px", "'+=-9px' on width (params)" ); $elem.css( { "paddingLeft": "+=4" } ); assert.equal( $elem.css( "paddingLeft" ), "5px", "'+=4' on paddingLeft (hash)" ); $elem.css( { "paddingLeft": "-=4" } ); assert.equal( $elem.css( "paddingLeft" ), "1px", "'-=4' on paddingLeft (hash)" ); $elem.css( { "paddingLeft": "+=4px" } ); assert.equal( $elem.css( "paddingLeft" ), "5px", "'+=4px' on paddingLeft (hash)" ); $elem.css( { "paddingLeft": "-=4px" } ); assert.equal( $elem.css( "paddingLeft" ), "1px", "'-=4px' on paddingLeft (hash)" ); $elem.css( { "padding-left": "+=4" } ); assert.equal( $elem.css( "paddingLeft" ), "5px", "'+=4' on padding-left (hash)" ); $elem.css( { "padding-left": "-=4" } ); assert.equal( $elem.css( "paddingLeft" ), "1px", "'-=4' on padding-left (hash)" ); $elem.css( { "padding-left": "+=4px" } ); assert.equal( $elem.css( "paddingLeft" ), "5px", "'+=4px' on padding-left (hash)" ); $elem.css( { "padding-left": "-=4px" } ); assert.equal( $elem.css( "paddingLeft" ), "1px", "'-=4px' on padding-left (hash)" ); $elem.css( "paddingLeft", "+=4" ); assert.equal( $elem.css( "paddingLeft" ), "5px", "'+=4' on paddingLeft (params)" ); $elem.css( "paddingLeft", "-=4" ); assert.equal( $elem.css( "paddingLeft" ), "1px", "'-=4' on paddingLeft (params)" ); $elem.css( "padding-left", "+=4px" ); assert.equal( $elem.css( "paddingLeft" ), "5px", "'+=4px' on padding-left (params)" ); $elem.css( "padding-left", "-=4px" ); assert.equal( $elem.css( "paddingLeft" ), "1px", "'-=4px' on padding-left (params)" ); $elem.css( { "opacity": "-=0.5" } ); assert.equal( $elem.css( "opacity" ), "0.5", "'-=0.5' on opacity (hash)" ); $elem.css( { "opacity": "+=0.5" } ); assert.equal( $elem.css( "opacity" ), "1", "'+=0.5' on opacity (hash)" ); $elem.css( "opacity", "-=0.5" ); assert.equal( $elem.css( "opacity" ), "0.5", "'-=0.5' on opacity (params)" ); $elem.css( "opacity", "+=0.5" ); assert.equal( $elem.css( "opacity" ), "1", "'+=0.5' on opacity (params)" ); } ); QUnit.test( "css() non-px relative values (gh-1711)", function( assert ) { assert.expect( 17 ); var cssCurrent, units = {}, $child = jQuery( "#nothiddendivchild" ), add = function( prop, val, unit ) { var difference, adjustment = ( val < 0 ? "-=" : "+=" ) + Math.abs( val ) + unit, message = prop + ": " + adjustment, cssOld = cssCurrent, expected = cssOld + val * units[ prop ][ unit ]; // Apply change $child.css( prop, adjustment ); cssCurrent = parseFloat( $child.css( prop ) ); message += " (actual " + round( cssCurrent, 2 ) + "px, expected " + round( expected, 2 ) + "px)"; // Require a difference of no more than one pixel difference = Math.abs( cssCurrent - expected ); assert.ok( difference <= 1, message ); }, getUnits = function( prop ) { units[ prop ] = { "px": 1, "em": parseFloat( $child.css( prop, "100em" ).css( prop ) ) / 100, "pt": parseFloat( $child.css( prop, "100pt" ).css( prop ) ) / 100, "pc": parseFloat( $child.css( prop, "100pc" ).css( prop ) ) / 100, "cm": parseFloat( $child.css( prop, "100cm" ).css( prop ) ) / 100, "mm": parseFloat( $child.css( prop, "100mm" ).css( prop ) ) / 100, "%": parseFloat( $child.css( prop, "500%" ).css( prop ) ) / 500 }; }, round = function( num, fractionDigits ) { var base = Math.pow( 10, fractionDigits ); return Math.round( num * base ) / base; }; jQuery( "#nothiddendiv" ).css( { height: 1, padding: 0, width: 400 } ); $child.css( { height: 1, padding: 0 } ); getUnits( "width" ); cssCurrent = parseFloat( $child.css( "width", "50%" ).css( "width" ) ); add( "width", 25, "%" ); add( "width", -50, "%" ); add( "width", 10, "em" ); add( "width", 10, "pt" ); add( "width", -2.3, "pt" ); add( "width", 5, "pc" ); add( "width", -5, "em" ); add( "width", +2, "cm" ); add( "width", -15, "mm" ); add( "width", 21, "px" ); getUnits( "lineHeight" ); cssCurrent = parseFloat( $child.css( "lineHeight", "1em" ).css( "lineHeight" ) ); add( "lineHeight", 50, "%" ); add( "lineHeight", 2, "em" ); add( "lineHeight", -10, "px" ); add( "lineHeight", 20, "pt" ); add( "lineHeight", 30, "pc" ); add( "lineHeight", 1, "cm" ); add( "lineHeight", -44, "mm" ); } ); QUnit.test( "css() mismatched relative values with bounded styles (gh-2144)", function( assert ) { assert.expect( 1 ); var $container = jQuery( "<div></div>" ) .css( { position: "absolute", width: "400px", fontSize: "4px" } ) .appendTo( "#qunit-fixture" ), $el = jQuery( "<div></div>" ) .css( { position: "absolute", left: "50%", right: "50%" } ) .appendTo( $container ); $el.css( "right", "-=25em" ); assert.equal( Math.round( parseFloat( $el.css( "right" ) ) ), 100, "Constraints do not interfere with unit conversion" ); } ); QUnit.test( "css(String, Object)", function( assert ) { assert.expect( 19 ); var j, div, display, ret, success; jQuery( "#floatTest" ).css( "float", "left" ); assert.equal( jQuery( "#floatTest" ).css( "float" ), "left", "Modified CSS float using \"float\": Assert float is left" ); jQuery( "#floatTest" ).css( "font-size", "20px" ); assert.equal( jQuery( "#floatTest" ).css( "font-size" ), "20px", "Modified CSS font-size: Assert font-size is 20px" ); jQuery.each( "0,0.25,0.5,0.75,1".split( "," ), function( i, n ) { jQuery( "#foo" ).css( "opacity", n ); assert.equal( jQuery( "#foo" ).css( "opacity" ), parseFloat( n ), "Assert opacity is " + parseFloat( n ) + " as a String" ); jQuery( "#foo" ).css( "opacity", parseFloat( n ) ); assert.equal( jQuery( "#foo" ).css( "opacity" ), parseFloat( n ), "Assert opacity is " + parseFloat( n ) + " as a Number" ); } ); jQuery( "#foo" ).css( "opacity", "" ); assert.equal( jQuery( "#foo" ).css( "opacity" ), "1", "Assert opacity is 1 when set to an empty String" ); // using contents will get comments regular, text, and comment nodes j = jQuery( "#nonnodes" ).contents(); j.css( "overflow", "visible" ); assert.equal( j.css( "overflow" ), "visible", "Check node,textnode,comment css works" ); assert.equal( jQuery( "#t2037 .hidden" ).css( "display" ), "none", "Make sure browser thinks it is hidden" ); div = jQuery( "#nothiddendiv" ); display = div.css( "display" ); ret = div.css( "display", undefined ); assert.equal( ret, div, "Make sure setting undefined returns the original set." ); assert.equal( div.css( "display" ), display, "Make sure that the display wasn't changed." ); success = true; try { jQuery( "#foo" ).css( "backgroundColor", "rgba(0, 0, 0, 0.1)" ); } catch ( e ) { success = false; } assert.ok( success, "Setting RGBA values does not throw Error (trac-5509)" ); jQuery( "#foo" ).css( "font", "7px/21px sans-serif" ); assert.strictEqual( jQuery( "#foo" ).css( "line-height" ), "21px", "Set font shorthand property (trac-14759)" ); } ); QUnit.test( "css(String, Object) with negative values", function( assert ) { assert.expect( 4 ); jQuery( "#nothiddendiv" ).css( "margin-top", "-10px" ); jQuery( "#nothiddendiv" ).css( "margin-left", "-10px" ); assert.equal( jQuery( "#nothiddendiv" ).css( "margin-top" ), "-10px", "Ensure negative top margins work." ); assert.equal( jQuery( "#nothiddendiv" ).css( "margin-left" ), "-10px", "Ensure negative left margins work." ); jQuery( "#nothiddendiv" ).css( "position", "absolute" ); jQuery( "#nothiddendiv" ).css( "top", "-20px" ); jQuery( "#nothiddendiv" ).css( "left", "-20px" ); assert.equal( jQuery( "#nothiddendiv" ).css( "top" ), "-20px", "Ensure negative top values work." ); assert.equal( jQuery( "#nothiddendiv" ).css( "left" ), "-20px", "Ensure negative left values work." ); } ); QUnit.test( "css(Array)", function( assert ) { assert.expect( 2 ); var expectedMany = { "overflow": "visible", "width": "16px" }, expectedSingle = { "width": "16px" }, elem = jQuery( "<div></div>" ).appendTo( "#qunit-fixture" ); assert.deepEqual( elem.css( expectedMany ).css( [ "overflow", "width" ] ), expectedMany, "Getting multiple element array" ); assert.deepEqual( elem.css( expectedSingle ).css( [ "width" ] ), expectedSingle, "Getting single element array" ); } ); QUnit.test( "css(String, Function)", function( assert ) { assert.expect( 3 ); var index, sizes = [ "10px", "20px", "30px" ]; jQuery( "<div id='cssFunctionTest'><div class='cssFunction'></div>" + "<div class='cssFunction'></div>" + "<div class='cssFunction'></div></div>" ) .appendTo( "body" ); index = 0; jQuery( "#cssFunctionTest div" ).css( "font-size", function() { var size = sizes[ index ]; index++; return size; } ); index = 0; jQuery( "#cssFunctionTest div" ).each( function() { var computedSize = jQuery( this ).css( "font-size" ), expectedSize = sizes[ index ]; assert.equal( computedSize, expectedSize, "Div #" + index + " should be " + expectedSize ); index++; } ); jQuery( "#cssFunctionTest" ).remove(); } ); QUnit.test( "css(String, Function) with incoming value", function( assert ) { assert.expect( 3 ); var index, sizes = [ "10px", "20px", "30px" ]; jQuery( "<div id='cssFunctionTest'><div class='cssFunction'></div>" + "<div class='cssFunction'></div>" + "<div class='cssFunction'></div></div>" ) .appendTo( "body" ); index = 0; jQuery( "#cssFunctionTest div" ).css( "font-size", function() { var size = sizes[ index ]; index++; return size; } ); index = 0; jQuery( "#cssFunctionTest div" ).css( "font-size", function( i, computedSize ) { var expectedSize = sizes[ index ]; assert.equal( computedSize, expectedSize, "Div #" + index + " should be " + expectedSize ); index++; return computedSize; } ); jQuery( "#cssFunctionTest" ).remove(); } ); QUnit.test( "css(Object) where values are Functions", function( assert ) { assert.expect( 3 ); var index, sizes = [ "10px", "20px", "30px" ]; jQuery( "<div id='cssFunctionTest'><div class='cssFunction'></div>" + "<div class='cssFunction'></div>" + "<div class='cssFunction'></div></div>" ) .appendTo( "body" ); index = 0; jQuery( "#cssFunctionTest div" ).css( { "fontSize": function() { var size = sizes[ index ]; index++; return size; } } ); index = 0; jQuery( "#cssFunctionTest div" ).each( function() { var computedSize = jQuery( this ).css( "font-size" ), expectedSize = sizes[ index ]; assert.equal( computedSize, expectedSize, "Div #" + index + " should be " + expectedSize ); index++; } ); jQuery( "#cssFunctionTest" ).remove(); } ); QUnit.test( "css(Object) where values are Functions with incoming values", function( assert ) { assert.expect( 3 ); var index, sizes = [ "10px", "20px", "30px" ]; jQuery( "<div id='cssFunctionTest'><div class='cssFunction'></div>" + "<div class='cssFunction'></div>" + "<div class='cssFunction'></div></div>" ) .appendTo( "body" ); index = 0; jQuery( "#cssFunctionTest div" ).css( { "fontSize": function() { var size = sizes[ index ]; index++; return size; } } ); index = 0; jQuery( "#cssFunctionTest div" ).css( { "font-size": function( i, computedSize ) { var expectedSize = sizes[ index ]; assert.equal( computedSize, expectedSize, "Div #" + index + " should be " + expectedSize ); index++; return computedSize; } } ); jQuery( "#cssFunctionTest" ).remove(); } ); QUnit.test( "show()", function( assert ) { assert.expect( 18 ); var hiddendiv, div, pass, test; hiddendiv = jQuery( "div.hidden" ); assert.equal( jQuery.css( hiddendiv[ 0 ], "display" ), "none", "hiddendiv is display: none" ); hiddendiv.css( "display", "block" ); assert.equal( jQuery.css( hiddendiv[ 0 ], "display" ), "block", "hiddendiv is display: block" ); hiddendiv.show(); assert.equal( jQuery.css( hiddendiv[ 0 ], "display" ), "block", "hiddendiv is display: block" ); hiddendiv.css( "display", "" ); pass = true; div = jQuery( "#qunit-fixture div" ); div.show().each( function() { if ( this.style.display === "none" ) { pass = false; } } ); assert.ok( pass, "Show" ); jQuery( "<div id='show-tests'>" + "<div><p><a href='#'></a></p><code></code><pre></pre><span></span></div>" + "<table><thead><tr><th></th></tr></thead><tbody><tr><td></td></tr></tbody></table>" + "<ul><li></li></ul></div>" ).appendTo( "#qunit-fixture" ).find( "*" ).css( "display", "none" ); test = { "div": "block", "p": "block", "a": "inline", "code": "inline", "pre": "block", "span": "inline", "table": "table", "thead": "table-header-group", "tbody": "table-row-group", "tr": "table-row", "th": "table-cell", "td": "table-cell", "ul": "block", "li": "list-item" }; jQuery.each( test, function( selector, expected ) { var elem = jQuery( selector, "#show-tests" ).show(); assert.equal( elem.css( "display" ), expected, "Show using correct display type for " + selector ); } ); // Make sure that showing or hiding a text node doesn't cause an error jQuery( "<div>test</div> text <span>test</span>" ).show().remove(); jQuery( "<div>test</div> text <span>test</span>" ).hide().remove(); } ); QUnit.test( "show/hide detached nodes", function( assert ) { assert.expect( 19 ); var div, span, tr; div = jQuery( "<div>" ).hide(); assert.equal( div.css( "display" ), "none", "hide() updates inline style of a detached div" ); div.appendTo( "#qunit-fixture" ); assert.equal( div.css( "display" ), "none", "A hidden-while-detached div is hidden after attachment" ); div.show(); assert.equal( div.css( "display" ), "block", "A hidden-while-detached div can be shown after attachment" ); div = jQuery( "<div class='hidden'>" ); div.show().appendTo( "#qunit-fixture" ); assert.equal( div.css( "display" ), "none", "A shown-while-detached div can be hidden by the CSS cascade" ); div = jQuery( "<div><div class='hidden'></div></div>" ).children( "div" ); div.show().appendTo( "#qunit-fixture" ); assert.equal( div.css( "display" ), "none", "A shown-while-detached div inside a visible div can be hidden by the CSS cascade" ); span = jQuery( "<span class='hidden'></span>" ); span.show().appendTo( "#qunit-fixture" ); assert.equal( span.css( "display" ), "none", "A shown-while-detached span can be hidden by the CSS cascade" ); div = jQuery( "div.hidden" ); div.detach().show(); assert.ok( !div[ 0 ].style.display, "show() does not update inline style of a cascade-hidden-before-detach div" ); div.appendTo( "#qunit-fixture" ); assert.equal( div.css( "display" ), "none", "A shown-while-detached cascade-hidden div is hidden after attachment" ); div.remove(); span = jQuery( "<span class='hidden'></span>" ); span.appendTo( "#qunit-fixture" ).detach().show().appendTo( "#qunit-fixture" ); assert.equal( span.css( "display" ), "none", "A shown-while-detached cascade-hidden span is hidden after attachment" ); span.remove(); div = jQuery( document.createElement( "div" ) ); div.show().appendTo( "#qunit-fixture" ); assert.ok( !div[ 0 ].style.display, "A shown-while-detached div has no inline style" ); assert.equal( div.css( "display" ), "block", "A shown-while-detached div has default display after attachment" ); div.remove(); div = jQuery( "<div style='display: none'>" ); div.show(); assert.equal( div[ 0 ].style.display, "", "show() updates inline style of a detached inline-hidden div" ); div.appendTo( "#qunit-fixture" ); assert.equal( div.css( "display" ), "block", "A shown-while-detached inline-hidden div has default display after attachment" ); div = jQuery( "<div><div style='display: none'></div></div>" ).children( "div" ); div.show().appendTo( "#qunit-fixture" ); assert.equal( div.css( "display" ), "block", "A shown-while-detached inline-hidden div inside a visible div has default display " + "after attachment" ); span = jQuery( "<span style='display: none'></span>" ); span.show(); assert.equal( span[ 0 ].style.display, "", "show() updates inline style of a detached inline-hidden span" ); span.appendTo( "#qunit-fixture" ); assert.equal( span.css( "display" ), "inline", "A shown-while-detached inline-hidden span has default display after attachment" ); div = jQuery( "<div style='display: inline'></div>" ); div.show().appendTo( "#qunit-fixture" ); assert.equal( div.css( "display" ), "inline", "show() does not update inline style of a detached inline-visible div" ); div.remove(); tr = jQuery( "<tr></tr>" ); jQuery( "#table" ).append( tr ); tr.detach().hide().show(); assert.ok( !tr[ 0 ].style.display, "Not-hidden detached tr elements have no inline style" ); tr.remove(); span = jQuery( "<span></span>" ).hide().show(); assert.ok( !span[ 0 ].style.display, "Not-hidden detached span elements have no inline style" ); span.remove(); } ); // Support: IE 11+ // IE doesn't support Shadow DOM. QUnit.testUnlessIE( "show/hide shadow child nodes", function( assert ) { assert.expect( 28 ); jQuery( "<div id='shadowHost'></div>" ).appendTo( "#qunit-fixture" ); var shadowHost = document.querySelector( "#shadowHost" ); var shadowRoot = shadowHost.attachShadow( { mode: "open" } ); shadowRoot.innerHTML = "" + "<style>.hidden{display: none;}</style>" + "<div class='hidden' id='shadowdiv'>" + " <p class='hidden' id='shadowp'>" + " <a href='#' class='hidden' id='shadowa'></a>" + " </p>" + " <code class='hidden' id='shadowcode'></code>" + " <pre class='hidden' id='shadowpre'></pre>" + " <span class='hidden' id='shadowspan'></span>" + "</div>" + "<table class='hidden' id='shadowtable'>" + " <thead class='hidden' id='shadowthead'>" + " <tr class='hidden' id='shadowtr'>" + " <th class='hidden' id='shadowth'></th>" + " </tr>" + " </thead>" + " <tbody class='hidden' id='shadowtbody'>" + " <tr class='hidden'>" + " <td class='hidden' id='shadowtd'></td>" + " </tr>" + " </tbody>" + "</table>" + "<ul class='hidden' id='shadowul'>" + " <li class='hidden' id='shadowli'></li>" + "</ul>"; var test = { "div": "block", "p": "block", "a": "inline", "code": "inline", "pre": "block", "span": "inline", "table": "table", "thead": "table-header-group", "tbody": "table-row-group", "tr": "table-row", "th": "table-cell", "td": "table-cell", "ul": "block", "li": "list-item" }; jQuery.each( test, function( selector, expected ) { var shadowChild = shadowRoot.querySelector( "#shadow" + selector ); var $shadowChild = jQuery( shadowChild ); assert.strictEqual( $shadowChild.css( "display" ), "none", "is hidden" ); $shadowChild.show(); assert.strictEqual( $shadowChild.css( "display" ), expected, "Show using correct display type for " + selector ); } ); } ); QUnit.test( "hide hidden elements (bug trac-7141)", function( assert ) { assert.expect( 3 ); var div = jQuery( "<div style='display:none'></div>" ).appendTo( "#qunit-fixture" ); assert.equal( div.css( "display" ), "none", "Element is hidden by default" ); div.hide(); assert.ok( !jQuery._data( div, "olddisplay" ), "olddisplay is undefined after hiding an already-hidden element" ); div.show(); assert.equal( div.css( "display" ), "block", "Show a double-hidden element" ); div.remove(); } ); QUnit.test( "show() after hide() should always set display to initial value (trac-14750)", function( assert ) { assert.expect( 1 ); var div = jQuery( "<div></div>" ), fixture = jQuery( "#qunit-fixture" ); fixture.append( div ); div.css( "display", "inline" ).hide().show().css( "display", "list-item" ).hide().show(); assert.equal( div.css( "display" ), "list-item", "should get last set display value" ); } ); QUnit.test( "show/hide 3.0, default display", function( assert ) { assert.expect( 36 ); var i, $elems = jQuery( "<div></div>" ) .appendTo( "#qunit-fixture" ) .html( "<div data-expected-display='block'></div>" + "<span data-expected-display='inline'></span>" + "<ul><li data-expected-display='list-item'></li></ul>" ) .find( "[data-expected-display]" ); $elems.each( function() { var $elem = jQuery( this ), name = this.nodeName, expected = this.getAttribute( "data-expected-display" ), sequence = []; if ( this.className ) { name += "." + this.className; } if ( this.getAttribute( "style" ) ) { name += "[style='" + this.getAttribute( "style" ) + "']"; } name += " "; for ( i = 0; i < 3; i++ ) { sequence.push( ".show()" ); $elem.show(); assert.equal( $elem.css( "display" ), expected, name + sequence.join( "" ) + " computed" ); assert.equal( this.style.display, "", name + sequence.join( "" ) + " inline" ); sequence.push( ".hide()" ); $elem.hide(); assert.equal( $elem.css( "display" ), "none", name + sequence.join( "" ) + " computed" ); assert.equal( this.style.display, "none", name + sequence.join( "" ) + " inline" ); } } ); } ); QUnit.test( "show/hide 3.0, default body display", function( assert ) { assert.expect( 2 ); var hideBody = supportjQuery( "<style>body{display:none}</style>" ).appendTo( document.head ), body = jQuery( document.body ); assert.equal( body.css( "display" ), "none", "Correct initial display" ); body.show(); assert.equal( body.css( "display" ), "block", "Correct display after .show()" ); hideBody.remove(); } ); QUnit.test( "show/hide 3.0, cascade display", function( assert ) { assert.expect( 36 ); var i, $elems = jQuery( "<div></div>" ) .appendTo( "#qunit-fixture" ) .html( "<span class='block'></span><div class='inline'></div><div class='list-item'></div>" ) .children(); $elems.each( function() { var $elem = jQuery( this ), name = this.nodeName, sequence = []; if ( this.className ) { name += "." + this.className; } if ( this.getAttribute( "style" ) ) { name += "[style='" + this.getAttribute( "style" ) + "']"; } name += " "; for ( i = 0; i < 3; i++ ) { sequence.push( ".show()" ); $elem.show(); assert.equal( $elem.css( "display" ), this.className, name + sequence.join( "" ) + " computed" ); assert.equal( this.style.display, "", name + sequence.join( "" ) + " inline" ); sequence.push( ".hide()" ); $elem.hide(); assert.equal( $elem.css( "display" ), "none", name + sequence.join( "" ) + " computed" ); assert.equal( this.style.display, "none", name + sequence.join( "" ) + " inline" ); } } ); } ); QUnit.test( "show/hide 3.0, inline display", function( assert ) { assert.expect( 96 ); var i, $elems = jQuery( "<div></div>" ) .appendTo( "#qunit-fixture" ) .html( "<span data-expected-display='block' style='display:block'></span>" + "<span class='list-item' data-expected-display='block' style='display:block'></span>" + "<div data-expected-display='inline' style='display:inline'></div>" + "<div class='list-item' data-expected-display='inline' style='display:inline'></div>" + "<ul>" + "<li data-expected-display='block' style='display:block'></li>" + "<li class='inline' data-expected-display='block' style='display:block'></li>" + "<li data-expected-display='inline' style='display:inline'></li>" + "<li class='block' data-expected-display='inline' style='display:inline'></li>" + "</ul>" ) .find( "[data-expected-display]" ); $elems.each( function() { var $elem = jQuery( this ), name = this.nodeName, expected = this.getAttribute( "data-expected-display" ), sequence = []; if ( this.className ) { name += "." + this.className; } if ( this.getAttribute( "style" ) ) { name += "[style='" + this.getAttribute( "style" ) + "']"; } name += " "; for ( i = 0; i < 3; i++ ) { sequence.push( ".show()" ); $elem.show(); assert.equal( $elem.css( "display" ), expected, name + sequence.join( "" ) + " computed" ); assert.equal( this.style.display, expected, name + sequence.join( "" ) + " inline" ); sequence.push( ".hide()" ); $elem.hide(); assert.equal( $elem.css( "display" ), "none", name + sequence.join( "" ) + " computed" ); assert.equal( this.style.display, "none", name + sequence.join( "" ) + " inline" ); } } ); } ); QUnit.test( "show/hide 3.0, cascade hidden", function( assert ) { assert.expect( 72 ); var i, $elems = jQuery( "<div></div>" ) .appendTo( "#qunit-fixture" ) .html( "<div class='hidden' data-expected-display='block'></div>" + "<div class='hidden' data-expected-display='block' style='display:none'></div>" + "<span class='hidden' data-expected-display='inline'></span>" + "<span class='hidden' data-expected-display='inline' style='display:none'></span>" + "<ul>" + "<li class='hidden' data-expected-display='list-item'></li>" + "<li class='hidden' data-expected-display='list-item' style='display:none'></li>" + "</ul>" ) .find( "[data-expected-display]" ); $elems.each( function() { var $elem = jQuery( this ), name = this.nodeName, expected = this.getAttribute( "data-expected-display" ), sequence = []; if ( this.className ) { name += "." + this.className; } if ( this.getAttribute( "style" ) ) { name += "[style='" + this.getAttribute( "style" ) + "']"; } name += " "; for ( i = 0; i < 3; i++ ) { sequence.push( ".hide()" ); $elem.hide(); assert.equal( $elem.css( "display" ), "none", name + sequence.join( "" ) + " computed" ); assert.equal( this.style.display, "none", name + sequence.join( "" ) + " inline" ); sequence.push( ".show()" ); $elem.show(); assert.equal( $elem.css( "display" ), expected, name + sequence.join( "" ) + " computed" ); assert.equal( this.style.display, expected, name + sequence.join( "" ) + " inline" ); } } ); } );
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
true
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/test/unit/core.js
test/unit/core.js
QUnit.module( "core", { beforeEach: function() { this.sandbox = sinon.createSandbox(); }, afterEach: function() { this.sandbox.restore(); return moduleTeardown.apply( this, arguments ); } } ); QUnit.test( "Basic requirements", function( assert ) { assert.expect( 7 ); assert.ok( Array.prototype.push, "Array.push()" ); assert.ok( Function.prototype.apply, "Function.apply()" ); assert.ok( document.getElementById, "getElementById" ); assert.ok( document.getElementsByTagName, "getElementsByTagName" ); assert.ok( RegExp, "RegExp" ); assert.ok( jQuery, "jQuery" ); assert.ok( $, "$" ); } ); QUnit.test( "jQuery()", function( assert ) { var elem, i, obj = jQuery( "div" ), code = jQuery( "<code></code>" ), img = jQuery( "<img/>" ), div = jQuery( "<div></div><hr/><code></code><b/>" ), exec = false, expected = 23, attrObj = { "text": "test", "class": "test2", "id": "test3" }; // The $(html, props) signature can stealth-call any $.fn method, check for a // few here but beware of modular builds where these methods may be excluded. if ( includesModule( "deprecated" ) ) { expected++; attrObj.click = function() { assert.ok( exec, "Click executed." ); }; } if ( includesModule( "dimensions" ) ) { expected++; attrObj.width = 10; } if ( includesModule( "offset" ) ) { expected++; attrObj.offset = { "top": 1, "left": 1 }; } if ( includesModule( "css" ) ) { expected += 2; attrObj.css = { "paddingLeft": 1, "paddingRight": 1 }; } if ( includesModule( "attributes" ) ) { expected++; attrObj.attr = { "desired": "very" }; } assert.expect( expected ); // Basic constructor's behavior assert.equal( jQuery().length, 0, "jQuery() === jQuery([])" ); assert.equal( jQuery( undefined ).length, 0, "jQuery(undefined) === jQuery([])" ); assert.equal( jQuery( null ).length, 0, "jQuery(null) === jQuery([])" ); assert.equal( jQuery( "" ).length, 0, "jQuery('') === jQuery([])" ); assert.deepEqual( jQuery( obj ).get(), obj.get(), "jQuery(jQueryObj) == jQueryObj" ); // Invalid #id will throw an error (gh-1682) try { jQuery( "#" ); } catch ( e ) { assert.ok( true, "Threw an error on #id with no id" ); } // can actually yield more than one, when iframes are included, the window is an array as well assert.equal( jQuery( window ).length, 1, "Correct number of elements generated for jQuery(window)" ); /* // disabled since this test was doing nothing. i tried to fix it but i'm not sure // what the expected behavior should even be. FF returns "\n" for the text node // make sure this is handled var crlfContainer = jQuery('<p>\r\n</p>'); var x = crlfContainer.contents().get(0).nodeValue; assert.equal( x, what???, "Check for \\r and \\n in jQuery()" ); */ /* // Disabled until we add this functionality in var pass = true; try { jQuery("<div>Testing</div>").appendTo(document.getElementById("iframe").contentDocument.body); } catch(e){ pass = false; } assert.ok( pass, "jQuery('&lt;tag&gt;') needs optional document parameter to ease cross-frame DOM wrangling, see trac-968" );*/ assert.equal( code.length, 1, "Correct number of elements generated for code" ); assert.equal( code.parent().length, 0, "Make sure that the generated HTML has no parent." ); assert.equal( img.length, 1, "Correct number of elements generated for img" ); assert.equal( img.parent().length, 0, "Make sure that the generated HTML has no parent." ); assert.equal( div.length, 4, "Correct number of elements generated for div hr code b" ); assert.equal( div.parent().length, 0, "Make sure that the generated HTML has no parent." ); assert.equal( jQuery( [ 1, 2, 3 ] ).get( 1 ), 2, "Test passing an array to the factory" ); assert.equal( jQuery( document.body ).get( 0 ), jQuery( "body" ).get( 0 ), "Test passing an html node to the factory" ); elem = jQuery( " <em>hello</em>" )[ 0 ]; assert.equal( elem.nodeName.toLowerCase(), "em", "leading space" ); elem = jQuery( "\n\n<em>world</em>" )[ 0 ]; assert.equal( elem.nodeName.toLowerCase(), "em", "leading newlines" ); elem = jQuery( "<div></div>", attrObj ); if ( includesModule( "dimensions" ) ) { assert.equal( elem[ 0 ].style.width, "10px", "jQuery() quick setter width" ); } if ( includesModule( "offset" ) ) { assert.equal( elem[ 0 ].style.top, "1px", "jQuery() quick setter offset" ); } if ( includesModule( "css" ) ) { assert.equal( elem[ 0 ].style.paddingLeft, "1px", "jQuery quick setter css" ); assert.equal( elem[ 0 ].style.paddingRight, "1px", "jQuery quick setter css" ); } if ( includesModule( "attributes" ) ) { assert.equal( elem[ 0 ].getAttribute( "desired" ), "very", "jQuery quick setter attr" ); } assert.equal( elem[ 0 ].childNodes.length, 1, "jQuery quick setter text" ); assert.equal( elem[ 0 ].firstChild.nodeValue, "test", "jQuery quick setter text" ); assert.equal( elem[ 0 ].className, "test2", "jQuery() quick setter class" ); assert.equal( elem[ 0 ].id, "test3", "jQuery() quick setter id" ); exec = true; elem.trigger( "click" ); // manually clean up detached elements elem.remove(); for ( i = 0; i < 3; ++i ) { elem = jQuery( "<input type='text' value='TEST' />" ); } assert.equal( elem[ 0 ].defaultValue, "TEST", "Ensure cached nodes are cloned properly (Bug trac-6655)" ); elem = jQuery( "<input type='hidden'>", {} ); assert.strictEqual( elem[ 0 ].ownerDocument, document, "Empty attributes object is not interpreted as a document (trac-8950)" ); } ); QUnit.test( "jQuery(selector, context)", function( assert ) { assert.expect( 3 ); assert.deepEqual( jQuery( "div p", "#qunit-fixture" ).get(), q( "sndp", "en", "sap" ), "Basic selector with string as context" ); assert.deepEqual( jQuery( "div p", q( "qunit-fixture" )[ 0 ] ).get(), q( "sndp", "en", "sap" ), "Basic selector with element as context" ); assert.deepEqual( jQuery( "div p", jQuery( "#qunit-fixture" ) ).get(), q( "sndp", "en", "sap" ), "Basic selector with jQuery object as context" ); } ); QUnit.test( "globalEval", function( assert ) { assert.expect( 3 ); Globals.register( "globalEvalTest" ); jQuery.globalEval( "globalEvalTest = 1;" ); assert.equal( window.globalEvalTest, 1, "Test variable assignments are global" ); jQuery.globalEval( "var globalEvalTest = 2;" ); assert.equal( window.globalEvalTest, 2, "Test variable declarations are global" ); jQuery.globalEval( "this.globalEvalTest = 3;" ); assert.equal( window.globalEvalTest, 3, "Test context (this) is the window object" ); } ); QUnit.test( "globalEval with 'use strict'", function( assert ) { assert.expect( 1 ); Globals.register( "strictEvalTest" ); jQuery.globalEval( "'use strict'; var strictEvalTest = 1;" ); assert.equal( window.strictEvalTest, 1, "Test variable declarations are global (strict mode)" ); } ); QUnit.test( "globalEval execution after script injection (trac-7862)", function( assert ) { assert.expect( 1 ); var now, script = document.createElement( "script" ); script.src = baseURL + "mock.php?action=wait&wait=2&script=1"; now = Date.now(); document.body.appendChild( script ); jQuery.globalEval( "var strictEvalTest = " + Date.now() + ";" ); assert.ok( window.strictEvalTest - now < 500, "Code executed synchronously" ); } ); testIframe( "globalEval with custom document context", "core/globaleval-context.html", function( assert, framejQuery, frameWindow, frameDocument ) { assert.expect( 2 ); jQuery.globalEval( "window.scriptTest = true;", {}, frameDocument ); assert.ok( !window.scriptTest, "script executed in iframe context" ); assert.ok( frameWindow.scriptTest, "script executed in iframe context" ); } ); QUnit.test( "noConflict", function( assert ) { assert.expect( 7 ); var $$ = jQuery; assert.strictEqual( jQuery, jQuery.noConflict(), "noConflict returned the jQuery object" ); assert.strictEqual( window.jQuery, $$, "Make sure jQuery wasn't touched." ); assert.strictEqual( window.$, original$, "Make sure $ was reverted." ); jQuery = $ = $$; assert.strictEqual( jQuery.noConflict( true ), $$, "noConflict returned the jQuery object" ); assert.strictEqual( window.jQuery, originaljQuery, "Make sure jQuery was reverted." ); assert.strictEqual( window.$, original$, "Make sure $ was reverted." ); assert.ok( $$().pushStack( [] ), "Make sure that jQuery still works." ); window.jQuery = jQuery = $$; } ); QUnit.test( "isPlainObject", function( assert ) { var done = assert.async(); assert.expect( 23 ); var pass, iframe, doc, parentObj, childObj, deep, fn = function() {}; // The use case that we want to match assert.ok( jQuery.isPlainObject( {} ), "{}" ); assert.ok( jQuery.isPlainObject( new window.Object() ), "new Object" ); assert.ok( jQuery.isPlainObject( { constructor: fn } ), "plain object with constructor property" ); assert.ok( jQuery.isPlainObject( { constructor: "foo" } ), "plain object with primitive constructor property" ); parentObj = {}; childObj = Object.create( parentObj ); assert.ok( !jQuery.isPlainObject( childObj ), "Object.create({})" ); parentObj.foo = "bar"; assert.ok( !jQuery.isPlainObject( childObj ), "Object.create({...})" ); childObj.bar = "foo"; assert.ok( !jQuery.isPlainObject( childObj ), "extend(Object.create({...}), ...)" ); // Not objects shouldn't be matched assert.ok( !jQuery.isPlainObject( "" ), "string" ); assert.ok( !jQuery.isPlainObject( 0 ) && !jQuery.isPlainObject( 1 ), "number" ); assert.ok( !jQuery.isPlainObject( true ) && !jQuery.isPlainObject( false ), "boolean" ); assert.ok( !jQuery.isPlainObject( null ), "null" ); assert.ok( !jQuery.isPlainObject( undefined ), "undefined" ); // Arrays shouldn't be matched assert.ok( !jQuery.isPlainObject( [] ), "array" ); // Instantiated objects shouldn't be matched assert.ok( !jQuery.isPlainObject( new Date() ), "new Date" ); // Functions shouldn't be matched assert.ok( !jQuery.isPlainObject( fn ), "fn" ); // Again, instantiated objects shouldn't be matched assert.ok( !jQuery.isPlainObject( new fn() ), "new fn (no methods)" ); // Makes the function a little more realistic // (and harder to detect, incidentally) fn.prototype.someMethod = function() {}; // Again, instantiated objects shouldn't be matched assert.ok( !jQuery.isPlainObject( new fn() ), "new fn" ); // Instantiated objects with primitive constructors shouldn't be matched fn.prototype.constructor = "foo"; assert.ok( !jQuery.isPlainObject( new fn() ), "new fn with primitive constructor" ); // Deep object deep = { "foo": { "baz": true }, "foo2": document }; assert.ok( jQuery.isPlainObject( deep ), "Object with objects is still plain" ); // DOM Element assert.ok( !jQuery.isPlainObject( document.createElement( "div" ) ), "DOM Element" ); // Window assert.ok( !jQuery.isPlainObject( window ), "window" ); pass = false; try { jQuery.isPlainObject( window.location ); pass = true; } catch ( e ) {} assert.ok( pass, "Does not throw exceptions on host objects" ); // Objects from other windows should be matched Globals.register( "iframeDone" ); window.iframeDone = function( otherObject, detail ) { window.iframeDone = undefined; iframe.parentNode.removeChild( iframe ); assert.ok( jQuery.isPlainObject( new otherObject() ), "new otherObject" + ( detail ? " - " + detail : "" ) ); done(); }; try { iframe = jQuery( "#qunit-fixture" )[ 0 ].appendChild( document.createElement( "iframe" ) ); doc = iframe.contentDocument || iframe.contentWindow.document; doc.open(); doc.write( "<body onload='window.parent.iframeDone(Object);'>" ); doc.close(); } catch ( e ) { window.iframeDone( Object, "iframes not supported" ); } } ); QUnit.testUnlessIE( "isPlainObject(Symbol)", function( assert ) { assert.expect( 2 ); assert.equal( jQuery.isPlainObject( Symbol() ), false, "Symbol" ); assert.equal( jQuery.isPlainObject( Object( Symbol() ) ), false, "Symbol inside an object" ); } ); QUnit.test( "isPlainObject(localStorage)", function( assert ) { assert.expect( 1 ); assert.equal( jQuery.isPlainObject( localStorage ), false ); } ); QUnit.testUnlessIE( "isPlainObject(Object.assign(...))", function( assert ) { assert.expect( 1 ); var parentObj = { foo: "bar" }; var childObj = Object.assign( Object.create( parentObj ), { bar: "foo" } ); assert.ok( !jQuery.isPlainObject( childObj ), "isPlainObject(Object.assign(...))" ); } ); QUnit.test( "isXMLDoc - HTML", function( assert ) { assert.expect( 4 ); assert.ok( !jQuery.isXMLDoc( document ), "HTML document" ); assert.ok( !jQuery.isXMLDoc( document.documentElement ), "HTML documentElement" ); assert.ok( !jQuery.isXMLDoc( document.body ), "HTML Body Element" ); var body, iframe = document.createElement( "iframe" ); document.body.appendChild( iframe ); try { body = jQuery( iframe ).contents()[ 0 ]; try { assert.ok( !jQuery.isXMLDoc( body ), "Iframe body element" ); } catch ( e ) { assert.ok( false, "Iframe body element exception" ); } } catch ( e ) { assert.ok( true, "Iframe body element - iframe not working correctly" ); } document.body.removeChild( iframe ); } ); QUnit.test( "isXMLDoc - embedded SVG", function( assert ) { assert.expect( 6 ); var htmlTree = jQuery( "<div>" + "<svg xmlns='http://www.w3.org/2000/svg' version='1.1' height='1' width='1'>" + "<desc></desc>" + "</svg>" + "</div>" )[ 0 ]; assert.strictEqual( jQuery.isXMLDoc( htmlTree ), false, "disconnected div element" ); assert.strictEqual( jQuery.isXMLDoc( htmlTree.firstChild ), true, "disconnected HTML-embedded SVG root element" ); assert.strictEqual( jQuery.isXMLDoc( htmlTree.firstChild.firstChild ), true, "disconnected HTML-embedded SVG child element" ); document.getElementById( "qunit-fixture" ).appendChild( htmlTree ); assert.strictEqual( jQuery.isXMLDoc( htmlTree ), false, "connected div element" ); assert.strictEqual( jQuery.isXMLDoc( htmlTree.firstChild ), true, "connected HTML-embedded SVG root element" ); assert.strictEqual( jQuery.isXMLDoc( htmlTree.firstChild.firstChild ), true, "disconnected HTML-embedded SVG child element" ); } ); QUnit.test( "isXMLDoc - XML", function( assert ) { assert.expect( 8 ); var xml = createDashboardXML(); var svg = jQuery.parseXML( "<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" " + "\"http://www.w3.org/Gaphics/SVG/1.1/DTD/svg11.dtd\">" + "<svg version='1.1' xmlns='http://www.w3.org/2000/svg'><desc/></svg>" ); assert.ok( jQuery.isXMLDoc( xml ), "XML document" ); assert.ok( jQuery.isXMLDoc( xml.documentElement ), "XML documentElement" ); assert.ok( jQuery.isXMLDoc( xml.documentElement.firstChild ), "XML child element" ); assert.ok( jQuery.isXMLDoc( jQuery( "tab", xml )[ 0 ] ), "XML tab Element" ); assert.ok( jQuery.isXMLDoc( svg ), "SVG document" ); assert.ok( jQuery.isXMLDoc( svg.documentElement ), "SVG documentElement" ); assert.ok( jQuery.isXMLDoc( svg.documentElement.firstChild ), "SVG child element" ); assert.ok( jQuery.isXMLDoc( jQuery( "desc", svg )[ 0 ] ), "XML desc Element" ); } ); QUnit.test( "isXMLDoc - falsy", function( assert ) { assert.expect( 5 ); assert.strictEqual( jQuery.isXMLDoc( undefined ), false, "undefined" ); assert.strictEqual( jQuery.isXMLDoc( null ), false, "null" ); assert.strictEqual( jQuery.isXMLDoc( false ), false, "false" ); assert.strictEqual( jQuery.isXMLDoc( 0 ), false, "0" ); assert.strictEqual( jQuery.isXMLDoc( "" ), false, "\"\"" ); } ); QUnit.test( "XSS via location.hash", function( assert ) { var done = assert.async(); assert.expect( 1 ); jQuery._check9521 = function( x ) { assert.ok( x, "script called from #id-like selector with inline handler" ); jQuery( "#check9521" ).remove(); delete jQuery._check9521; done(); }; try { // This throws an error because it's processed like an id jQuery( "#<img id='check9521' src='no-such-.gif' onerror='jQuery._check9521(false)'>" ).appendTo( "#qunit-fixture" ); } catch ( err ) { jQuery._check9521( true ); } } ); QUnit.test( "jQuery('html')", function( assert ) { assert.expect( 18 ); var s, div, j; jQuery.foo = false; s = jQuery( "<script>jQuery.foo='test';</script>" )[ 0 ]; assert.ok( s, "Creating a script" ); assert.ok( !jQuery.foo, "Make sure the script wasn't executed prematurely" ); jQuery( "body" ).append( "<script>jQuery.foo='test';</script>" ); assert.ok( jQuery.foo, "Executing a script's contents in the right context" ); // Test multi-line HTML div = jQuery( "<div>\r\nsome text\n<p>some p</p>\nmore text\r\n</div>" )[ 0 ]; assert.equal( div.nodeName.toUpperCase(), "DIV", "Make sure we're getting a div." ); assert.equal( div.firstChild.nodeType, 3, "Text node." ); assert.equal( div.lastChild.nodeType, 3, "Text node." ); assert.equal( div.childNodes[ 1 ].nodeType, 1, "Paragraph." ); assert.equal( div.childNodes[ 1 ].firstChild.nodeType, 3, "Paragraph text." ); assert.ok( jQuery( "<link rel='stylesheet'/>" )[ 0 ], "Creating a link" ); assert.ok( !jQuery( "<script></script>" )[ 0 ].parentNode, "Create a script" ); assert.ok( jQuery( "<input/>" ).attr( "type", "hidden" ), "Create an input and set the type." ); j = jQuery( "<span>hi</span> there <!-- mon ami -->" ); assert.ok( j.length >= 2, "Check node,textnode,comment creation (some browsers delete comments)" ); assert.ok( !jQuery( "<option>test</option>" )[ 0 ].selected, "Make sure that options are auto-selected trac-2050" ); assert.ok( jQuery( "<div></div>" )[ 0 ], "Create a div with closing tag." ); assert.ok( jQuery( "<table></table>" )[ 0 ], "Create a table with closing tag." ); assert.equal( jQuery( "element[attribute='<div></div>']" ).length, 0, "When html is within brackets, do not recognize as html." ); //equal( jQuery( "element[attribute=<div></div>]" ).length, 0, // "When html is within brackets, do not recognize as html." ); if ( QUnit.jQuerySelectors ) { assert.equal( jQuery( "element:not(<div></div>)" ).length, 0, "When html is within parens, do not recognize as html." ); } else { assert.ok( "skip", "Complex :not not supported in selector-native" ); } assert.equal( jQuery( "\\<div\\>" ).length, 0, "Ignore escaped html characters" ); } ); QUnit.test( "jQuery(element with non-alphanumeric name)", function( assert ) { assert.expect( 36 ); jQuery.each( [ "-", ":" ], function( i, symbol ) { jQuery.each( [ "thead", "tbody", "tfoot", "colgroup", "caption", "tr", "th", "td" ], function( j, tag ) { var tagName = tag + symbol + "test"; var el = jQuery( "<" + tagName + "></" + tagName + ">" ); assert.ok( el[ 0 ], "Create a " + tagName + " element" ); assert.ok( el[ 0 ].nodeName === tagName.toUpperCase(), tagName + " element has expected node name" ); } ); var tagName = [ "tr", "multiple", "symbol" ].join( symbol ); var el = jQuery( "<" + tagName + "></" + tagName + ">" ); assert.ok( el[ 0 ], "Create a " + tagName + " element" ); assert.ok( el[ 0 ].nodeName === tagName.toUpperCase(), tagName + " element has expected node name" ); } ); } ); QUnit.test( "jQuery('massive html trac-7990')", function( assert ) { assert.expect( 3 ); var i, li = "<li>very very very very large html string</li>", html = [ "<ul>" ]; for ( i = 0; i < 30000; i += 1 ) { html[ html.length ] = li; } html[ html.length ] = "</ul>"; html = jQuery( html.join( "" ) )[ 0 ]; assert.equal( html.nodeName.toLowerCase(), "ul" ); assert.equal( html.firstChild.nodeName.toLowerCase(), "li" ); assert.equal( html.childNodes.length, 30000 ); } ); QUnit.test( "jQuery('html', context)", function( assert ) { assert.expect( 1 ); var $div = jQuery( "<div></div>" )[ 0 ], $span = jQuery( "<span></span>", $div ); assert.equal( $span.length, 1, "verify a span created with a div context works, trac-1763" ); } ); QUnit.test( "jQuery(selector, xml).text(str) - loaded via xml document", function( assert ) { assert.expect( 2 ); var xml = createDashboardXML(), // tests for trac-1419 where ie was a problem tab = jQuery( "tab", xml ).eq( 0 ); assert.equal( tab.text(), "blabla", "verify initial text correct" ); tab.text( "newtext" ); assert.equal( tab.text(), "newtext", "verify new text correct" ); } ); QUnit.test( "end()", function( assert ) { assert.expect( 3 ); assert.equal( "Yahoo", jQuery( "#yahoo" ).parent().end().text(), "check for end" ); assert.ok( jQuery( "#yahoo" ).end(), "check for end with nothing to end" ); var x = jQuery( "#yahoo" ); x.parent(); assert.equal( "Yahoo", jQuery( "#yahoo" ).text(), "check for non-destructive behavior" ); } ); QUnit.test( "length", function( assert ) { assert.expect( 1 ); assert.equal( jQuery( "#qunit-fixture p" ).length, 6, "Get Number of Elements Found" ); } ); QUnit.test( "get()", function( assert ) { assert.expect( 1 ); assert.deepEqual( jQuery( "#qunit-fixture p" ).get(), q( "firstp", "ap", "sndp", "en", "sap", "first" ), "Get All Elements" ); } ); QUnit.test( "toArray()", function( assert ) { assert.expect( 1 ); assert.deepEqual( jQuery( "#qunit-fixture p" ).toArray(), q( "firstp", "ap", "sndp", "en", "sap", "first" ), "Convert jQuery object to an Array" ); } ); QUnit.test( "inArray()", function( assert ) { assert.expect( 19 ); var selections = { p: q( "firstp", "sap", "ap", "first" ), em: q( "siblingnext", "siblingfirst" ), div: q( "qunit-testrunner-toolbar", "nothiddendiv", "nothiddendivchild", "foo" ), a: q( "mozilla", "groups", "google", "john1" ), empty: [] }, tests = { p: { elem: jQuery( "#ap" )[ 0 ], index: 2 }, em: { elem: jQuery( "#siblingfirst" )[ 0 ], index: 1 }, div: { elem: jQuery( "#nothiddendiv" )[ 0 ], index: 1 }, a: { elem: jQuery( "#john1" )[ 0 ], index: 3 } }, falseTests = { p: jQuery( "#liveSpan1" )[ 0 ], em: jQuery( "#nothiddendiv" )[ 0 ], empty: "" }; jQuery.each( tests, function( key, obj ) { assert.equal( jQuery.inArray( obj.elem, selections[ key ] ), obj.index, "elem is in the array of selections of its tag" ); // Third argument (fromIndex) assert.equal( !!~jQuery.inArray( obj.elem, selections[ key ], 5 ), false, "elem is NOT in the array of selections given a starting index greater than its position" ); assert.equal( !!~jQuery.inArray( obj.elem, selections[ key ], 1 ), true, "elem is in the array of selections given a starting index less than or equal to its position" ); assert.equal( !!~jQuery.inArray( obj.elem, selections[ key ], -3 ), true, "elem is in the array of selections given a negative index" ); } ); jQuery.each( falseTests, function( key, elem ) { assert.equal( !!~jQuery.inArray( elem, selections[ key ] ), false, "elem is NOT in the array of selections" ); } ); } ); QUnit.test( "get(Number)", function( assert ) { assert.expect( 2 ); assert.equal( jQuery( "#qunit-fixture p" ).get( 0 ), document.getElementById( "firstp" ), "Get A Single Element" ); assert.strictEqual( jQuery( "#firstp" ).get( 1 ), undefined, "Try get with index larger elements count" ); } ); QUnit.test( "get(-Number)", function( assert ) { assert.expect( 2 ); assert.equal( jQuery( "p" ).get( -1 ), document.getElementById( "first" ), "Get a single element with negative index" ); assert.strictEqual( jQuery( "#firstp" ).get( -2 ), undefined, "Try get with index negative index larger then elements count" ); } ); QUnit.test( "each(Function)", function( assert ) { assert.expect( 1 ); var div, pass, i; div = jQuery( "div" ); div.each( function() { this.foo = "zoo"; } ); pass = true; for ( i = 0; i < div.length; i++ ) { if ( div.get( i ).foo !== "zoo" ) { pass = false; } } assert.ok( pass, "Execute a function, Relative" ); } ); QUnit.test( "slice()", function( assert ) { assert.expect( 7 ); var $links = jQuery( "#ap a" ); assert.deepEqual( $links.slice( 1, 2 ).get(), q( "groups" ), "slice(1,2)" ); assert.deepEqual( $links.slice( 1 ).get(), q( "groups", "anchor1", "mozilla" ), "slice(1)" ); assert.deepEqual( $links.slice( 0, 3 ).get(), q( "google", "groups", "anchor1" ), "slice(0,3)" ); assert.deepEqual( $links.slice( -1 ).get(), q( "mozilla" ), "slice(-1)" ); assert.deepEqual( $links.eq( 1 ).get(), q( "groups" ), "eq(1)" ); assert.deepEqual( $links.eq( "2" ).get(), q( "anchor1" ), "eq('2')" ); assert.deepEqual( $links.eq( -1 ).get(), q( "mozilla" ), "eq(-1)" ); } ); QUnit.test( "first()/last()", function( assert ) { assert.expect( 4 ); var $links = jQuery( "#ap a" ), $none = jQuery( "asdf" ); assert.deepEqual( $links.first().get(), q( "google" ), "first()" ); assert.deepEqual( $links.last().get(), q( "mozilla" ), "last()" ); assert.deepEqual( $none.first().get(), [], "first() none" ); assert.deepEqual( $none.last().get(), [], "last() none" ); } ); QUnit.test( "even()/odd()", function( assert ) { assert.expect( 4 ); var $links = jQuery( "#ap a" ), $none = jQuery( "asdf" ); assert.deepEqual( $links.even().get(), q( "google", "anchor1" ), "even()" ); assert.deepEqual( $links.odd().get(), q( "groups", "mozilla" ), "odd()" ); assert.deepEqual( $none.even().get(), [], "even() none" ); assert.deepEqual( $none.odd().get(), [], "odd() none" ); } ); QUnit.test( "map()", function( assert ) { assert.expect( 2 ); assert.deepEqual( jQuery( "#ap" ).map( function() { return jQuery( this ).find( "a" ).get(); } ).get(), q( "google", "groups", "anchor1", "mozilla" ), "Array Map" ); assert.deepEqual( jQuery( "#ap > a" ).map( function() { return this.parentNode; } ).get(), q( "ap", "ap", "ap" ), "Single Map" ); } ); QUnit.test( "jQuery.map", function( assert ) { assert.expect( 28 ); var i, label, result, callback; result = jQuery.map( [ 3, 4, 5 ], function( v, k ) { return k; } ); assert.equal( result.join( "" ), "012", "Map the keys from an array" ); result = jQuery.map( [ 3, 4, 5 ], function( v ) { return v; } ); assert.equal( result.join( "" ), "345", "Map the values from an array" ); result = jQuery.map( { a: 1, b: 2 }, function( v, k ) { return k; } ); assert.equal( result.join( "" ), "ab", "Map the keys from an object" ); result = jQuery.map( { a: 1, b: 2 }, function( v ) { return v; } ); assert.equal( result.join( "" ), "12", "Map the values from an object" ); result = jQuery.map( [ "a", undefined, null, "b" ], function( v ) { return v; } ); assert.equal( result.join( "" ), "ab", "Array iteration does not include undefined/null results" ); result = jQuery.map( { a: "a", b: undefined, c: null, d: "b" }, function( v ) { return v; } ); assert.equal( result.join( "" ), "ab", "Object iteration does not include undefined/null results" ); result = { Zero: function() {}, One: function( a ) { a = a; }, Two: function( a, b ) { a = a; b = b; } }; callback = function( v, k ) { assert.equal( k, "foo", label + "-argument function treated like object" ); }; for ( i in result ) { label = i; result[ i ].foo = "bar"; jQuery.map( result[ i ], callback ); } result = { "undefined": undefined, "null": null, "false": false, "true": true, "empty string": "", "nonempty string": "string", "string \"0\"": "0", "negative": -1, "excess": 1 }; callback = function( v, k ) { assert.equal( k, "length", "Object with " + label + " length treated like object" ); }; for ( i in result ) { label = i; jQuery.map( { length: result[ i ] }, callback ); } result = { "sparse Array": Array( 4 ), "length: 1 plain object": { length: 1, "0": true }, "length: 2 plain object": { length: 2, "0": true, "1": true }, NodeList: document.getElementsByTagName( "html" ) }; callback = function( v, k ) { if ( result[ label ] ) { delete result[ label ]; assert.equal( k, "0", label + " treated like array" ); } }; for ( i in result ) { label = i; jQuery.map( result[ i ], callback ); } result = false; jQuery.map( { length: 0 }, function() { result = true; } ); assert.ok( !result, "length: 0 plain object treated like array" ); result = false; jQuery.map( document.getElementsByTagName( "asdf" ), function() { result = true; } ); assert.ok( !result, "empty NodeList treated like array" ); result = jQuery.map( Array( 4 ), function( v, k ) { return k % 2 ? k : [ k, k, k ]; } ); assert.equal( result.join( "" ), "00012223", "Array results flattened (trac-2616)" ); result = jQuery.map( [ [ [ 1, 2 ], 3 ], 4 ], function( v, k ) { return v; } ); assert.equal( result.length, 3, "Array flatten only one level down" ); assert.ok( Array.isArray( result[ 0 ] ), "Array flatten only one level down" ); // Support: IE 11+ // IE doesn't have Array#flat so it'd fail the test. if ( !QUnit.isIE ) { result = jQuery.map( Array( 300000 ), function( v, k ) { return k; } ); assert.equal( result.length, 300000, "Able to map 300000 records without any problems (gh-4320)" ); } else { assert.ok( "skip", "Array#flat isn't supported in IE" ); } } ); QUnit.test( "jQuery.merge()", function( assert ) { assert.expect( 10 ); assert.deepEqual( jQuery.merge( [], [] ), [], "Empty arrays" ); assert.deepEqual( jQuery.merge( [ 1 ], [ 2 ] ), [ 1, 2 ], "Basic (single-element)" ); assert.deepEqual( jQuery.merge( [ 1, 2 ], [ 3, 4 ] ), [ 1, 2, 3, 4 ], "Basic (multiple-element)" ); assert.deepEqual( jQuery.merge( [ 1, 2 ], [] ), [ 1, 2 ], "Second empty" ); assert.deepEqual( jQuery.merge( [], [ 1, 2 ] ), [ 1, 2 ], "First empty" ); // Fixed at [5998], trac-3641 assert.deepEqual( jQuery.merge( [ -2, -1 ], [ 0, 1, 2 ] ), [ -2, -1, 0, 1, 2 ], "Second array including a zero (falsy)" ); // After fixing trac-5527 assert.deepEqual( jQuery.merge( [], [ null, undefined ] ), [ null, undefined ], "Second array including null and undefined values" ); assert.deepEqual( jQuery.merge( { length: 0 }, [ 1, 2 ] ), { length: 2, 0: 1, 1: 2 }, "First array like" ); assert.deepEqual( jQuery.merge( [ 1, 2 ], { length: 1, 0: 3 } ), [ 1, 2, 3 ], "Second array like" ); assert.deepEqual( jQuery.merge( [], document.getElementById( "lengthtest" ).getElementsByTagName( "input" ) ), [ document.getElementById( "length" ), document.getElementById( "idTest" ) ], "Second NodeList" ); } ); QUnit.test( "jQuery.grep()", function( assert ) { assert.expect( 8 ); var searchCriterion = function( value ) { return value % 2 === 0; }; assert.deepEqual( jQuery.grep( [], searchCriterion ), [], "Empty array" ); assert.deepEqual( jQuery.grep( new Array( 4 ), searchCriterion ), [], "Sparse array" ); assert.deepEqual( jQuery.grep( [ 1, 2, 3, 4, 5, 6 ], searchCriterion ), [ 2, 4, 6 ], "Satisfying elements present" ); assert.deepEqual( jQuery.grep( [ 1, 3, 5, 7 ], searchCriterion ), [], "Satisfying elements absent" ); assert.deepEqual( jQuery.grep( [ 1, 2, 3, 4, 5, 6 ], searchCriterion, true ), [ 1, 3, 5 ], "Satisfying elements present and grep inverted" ); assert.deepEqual( jQuery.grep( [ 1, 3, 5, 7 ], searchCriterion, true ), [ 1, 3, 5, 7 ], "Satisfying elements absent and grep inverted" ); assert.deepEqual( jQuery.grep( [ 1, 2, 3, 4, 5, 6 ], searchCriterion, false ), [ 2, 4, 6 ], "Satisfying elements present but grep explicitly uninverted" ); assert.deepEqual( jQuery.grep( [ 1, 3, 5, 7 ], searchCriterion, false ), [], "Satisfying elements absent and grep explicitly uninverted" ); } ); QUnit.test( "jQuery.grep(Array-like)", function( assert ) { assert.expect( 7 ); var searchCriterion = function( value ) { return value % 2 === 0; }; assert.deepEqual( jQuery.grep( { length: 0 }, searchCriterion ), [], "Empty array-like" ); assert.deepEqual( jQuery.grep( { 0: 1, 1: 2, 2: 3, 3: 4, 4: 5, 5: 6, length: 6 }, searchCriterion ), [ 2, 4, 6 ], "Satisfying elements present and array-like object used" ); assert.deepEqual( jQuery.grep( { 0: 1, 1: 3, 2: 5, 3: 7, length: 4 }, searchCriterion ), [], "Satisfying elements absent and Array-like object used" ); assert.deepEqual( jQuery.grep( { 0: 1, 1: 2, 2: 3, 3: 4, 4: 5, 5: 6, length: 6 }, searchCriterion, true ), [ 1, 3, 5 ], "Satisfying elements present, array-like object used, and grep inverted" ); assert.deepEqual( jQuery.grep( { 0: 1, 1: 3, 2: 5, 3: 7, length: 4 }, searchCriterion, true ), [ 1, 3, 5, 7 ], "Satisfying elements absent, array-like object used, and grep inverted" ); assert.deepEqual( jQuery.grep( { 0: 1, 1: 2, 2: 3, 3: 4, 4: 5, 5: 6, length: 6 }, searchCriterion, false ), [ 2, 4, 6 ], "Satisfying elements present, Array-like object used, but grep explicitly uninverted" ); assert.deepEqual( jQuery.grep( { 0: 1, 1: 3, 2: 5, 3: 7, length: 4 }, searchCriterion, false ), [], "Satisfying elements absent, Array-like object used, and grep explicitly uninverted" ); } );
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
true
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/test/unit/wrap.js
test/unit/wrap.js
( function() { if ( !includesModule( "wrap" ) ) { return; } QUnit.module( "wrap", { afterEach: moduleTeardown } ); // See test/unit/manipulation.js for explanation about these 2 functions function manipulationBareObj( value ) { return value; } function manipulationFunctionReturningObj( value ) { return function() { return value; }; } function testWrap( val, assert ) { assert.expect( 18 ); var defaultText, result, j; defaultText = "Try them out:"; result = jQuery( "#first" ).wrap( val( "<div class='red'><span></span></div>" ) ).text(); assert.equal( defaultText, result, "Check for wrapping of on-the-fly html" ); assert.ok( jQuery( "#first" ).parent().parent().is( ".red" ), "Check if wrapper has class 'red'" ); result = jQuery( "#first" ).wrap( val( document.getElementById( "empty" ) ) ).parent(); assert.ok( result.is( "ol" ), "Check for element wrapping" ); assert.equal( result.text(), defaultText, "Check for element wrapping" ); jQuery( "#check1" ).on( "click", function() { var checkbox = this; assert.ok( checkbox.checked, "Checkbox's state is erased after wrap() action, see trac-769" ); jQuery( checkbox ).wrap( val( "<div id='c1' style='display:none;'></div>" ) ); assert.ok( checkbox.checked, "Checkbox's state is erased after wrap() action, see trac-769" ); } ).prop( "checked", false )[ 0 ].click(); // using contents will get comments regular, text, and comment nodes j = jQuery( "#nonnodes" ).contents(); j.wrap( val( "<i></i>" ) ); assert.equal( jQuery( "#nonnodes > i" ).length, 3, "Check node,textnode,comment wraps ok" ); assert.equal( jQuery( "#nonnodes > i" ).text(), j.text(), "Check node,textnode,comment wraps doesn't hurt text" ); j = jQuery( "<label></label>" ).wrap( val( "<li></li>" ) ); assert.equal( j[ 0 ] .nodeName.toUpperCase(), "LABEL", "Element is a label" ); assert.equal( j[ 0 ].parentNode.nodeName.toUpperCase(), "LI", "Element has been wrapped" ); // Wrap an element containing a text node j = jQuery( "<span></span>" ).wrap( "<div>test</div>" ); assert.equal( j[ 0 ].previousSibling.nodeType, 3, "Make sure the previous node is a text element" ); assert.equal( j[ 0 ].parentNode.nodeName.toUpperCase(), "DIV", "And that we're in the div element." ); // Try to wrap an element with multiple elements (should fail) j = jQuery( "<div><span></span></div>" ).children().wrap( "<p></p><div></div>" ); assert.equal( j[ 0 ].parentNode.parentNode.childNodes.length, 1, "There should only be one element wrapping." ); assert.equal( j.length, 1, "There should only be one element (no cloning)." ); assert.equal( j[ 0 ].parentNode.nodeName.toUpperCase(), "P", "The span should be in the paragraph." ); // Wrap an element with a jQuery set j = jQuery( "<span></span>" ).wrap( jQuery( "<div></div>" ) ); assert.equal( j[ 0 ].parentNode.nodeName.toLowerCase(), "div", "Wrapping works." ); // Wrap an element with a jQuery set and event result = jQuery( "<div></div>" ).on( "click", function() { assert.ok( true, "Event triggered." ); // Remove handlers on detached elements result.off(); jQuery( this ).off(); } ); j = jQuery( "<span></span>" ).wrap( result ); assert.equal( j[ 0 ].parentNode.nodeName.toLowerCase(), "div", "Wrapping works." ); j.parent().trigger( "click" ); } QUnit.test( "wrap(String|Element)", function( assert ) { testWrap( manipulationBareObj, assert ); } ); QUnit.test( "wrap(Function)", function( assert ) { testWrap( manipulationFunctionReturningObj, assert ); } ); QUnit.test( "wrap(Function) with index (trac-10177)", function( assert ) { var expectedIndex = 0, targets = jQuery( "#qunit-fixture p" ); assert.expect( targets.length ); targets.wrap( function( i ) { assert.equal( i, expectedIndex, "Check if the provided index (" + i + ") is as expected (" + expectedIndex + ")" ); expectedIndex++; return "<div id='wrap_index_'" + i + "'></div>"; } ); } ); QUnit.test( "wrap(String) consecutive elements (trac-10177)", function( assert ) { var targets = jQuery( "#qunit-fixture p" ); assert.expect( targets.length * 2 ); targets.wrap( "<div class='wrapper'></div>" ); targets.each( function() { var $this = jQuery( this ); assert.ok( $this.parent().is( ".wrapper" ), "Check each elements parent is correct (.wrapper)" ); assert.equal( $this.siblings().length, 0, "Each element should be wrapped individually" ); } ); } ); QUnit.test( "wrapAll(String)", function( assert ) { assert.expect( 5 ); var prev, p, result; prev = jQuery( "#firstp" )[ 0 ].previousSibling; p = jQuery( "#firstp,#first" )[ 0 ].parentNode; result = jQuery( "#firstp,#first" ).wrapAll( "<div class='red'><div class='tmp'></div></div>" ); assert.equal( result.parent().length, 1, "Check for wrapping of on-the-fly html" ); assert.ok( jQuery( "#first" ).parent().parent().is( ".red" ), "Check if wrapper has class 'red'" ); assert.ok( jQuery( "#firstp" ).parent().parent().is( ".red" ), "Check if wrapper has class 'red'" ); assert.equal( jQuery( "#first" ).parent().parent()[ 0 ].previousSibling, prev, "Correct Previous Sibling" ); assert.equal( jQuery( "#first" ).parent().parent()[ 0 ].parentNode, p, "Correct Parent" ); } ); QUnit.test( "wrapAll(Function)", function( assert ) { assert.expect( 5 ); var prev = jQuery( "#firstp" )[ 0 ].previousSibling, p = jQuery( "#firstp,#first" )[ 0 ].parentNode, result = jQuery( "#firstp,#first" ).wrapAll( function() { return "<div class='red'><div class='tmp'></div></div>"; } ); assert.equal( result.parent().length, 1, "Check for wrapping of on-the-fly html" ); assert.ok( jQuery( "#first" ).parent().parent().is( ".red" ), "Check if wrapper has class 'red'" ); assert.ok( jQuery( "#firstp" ).parent().parent().is( ".red" ), "Check if wrapper has class 'red'" ); assert.ok( jQuery( "#first" ).parent().parent().parent().is( p ), "Correct Parent" ); assert.strictEqual( jQuery( "#first" ).parent().parent()[ 0 ].previousSibling, prev, "Correct Previous Sibling" ); } ); QUnit.test( "wrapAll(Function) check execution characteristics", function( assert ) { assert.expect( 3 ); var i = 0; jQuery( "non-existent" ).wrapAll( function() { i++; return ""; } ); assert.ok( !i, "should not execute function argument if target element does not exist" ); jQuery( "#firstp" ).wrapAll( function( index ) { assert.strictEqual( this, jQuery( "#firstp" )[ 0 ], "context must be the first found element" ); assert.strictEqual( index, undefined, "index argument should not be included in function execution" ); } ); } ); QUnit.test( "wrapAll(Element)", function( assert ) { assert.expect( 3 ); var prev, p; prev = jQuery( "#firstp" )[ 0 ].previousSibling; p = jQuery( "#first" )[ 0 ].parentNode; jQuery( "#firstp,#first" ).wrapAll( document.getElementById( "empty" ) ); assert.equal( jQuery( "#first" ).parent()[ 0 ], jQuery( "#firstp" ).parent()[ 0 ], "Same Parent" ); assert.equal( jQuery( "#first" ).parent()[ 0 ].previousSibling, prev, "Correct Previous Sibling" ); assert.equal( jQuery( "#first" ).parent()[ 0 ].parentNode, p, "Correct Parent" ); } ); QUnit.test( "wrapInner(String)", function( assert ) { assert.expect( 6 ); var num; num = jQuery( "#first" ).children().length; jQuery( "#first" ).wrapInner( "<div class='red'><div id='tmp'></div></div>" ); assert.equal( jQuery( "#first" ).children().length, 1, "Only one child" ); assert.ok( jQuery( "#first" ).children().is( ".red" ), "Verify Right Element" ); assert.equal( jQuery( "#first" ).children().children().children().length, num, "Verify Elements Intact" ); num = jQuery( "#first" ).html( "foo<div>test</div><div>test2</div>" ).children().length; jQuery( "#first" ).wrapInner( "<div class='red'><div id='tmp'></div></div>" ); assert.equal( jQuery( "#first" ).children().length, 1, "Only one child" ); assert.ok( jQuery( "#first" ).children().is( ".red" ), "Verify Right Element" ); assert.equal( jQuery( "#first" ).children().children().children().length, num, "Verify Elements Intact" ); } ); QUnit.test( "wrapInner(Element)", function( assert ) { assert.expect( 5 ); var num, div = jQuery( "<div></div>" ); num = jQuery( "#first" ).children().length; jQuery( "#first" ).wrapInner( document.getElementById( "empty" ) ); assert.equal( jQuery( "#first" ).children().length, 1, "Only one child" ); assert.ok( jQuery( "#first" ).children().is( "#empty" ), "Verify Right Element" ); assert.equal( jQuery( "#first" ).children().children().length, num, "Verify Elements Intact" ); div.wrapInner( "<span></span>" ); assert.equal( div.children().length, 1, "The contents were wrapped." ); assert.equal( div.children()[ 0 ].nodeName.toLowerCase(), "span", "A span was inserted." ); } ); QUnit.test( "wrapInner(Function) returns String", function( assert ) { assert.expect( 6 ); var num, val = manipulationFunctionReturningObj; num = jQuery( "#first" ).children().length; jQuery( "#first" ).wrapInner( val( "<div class='red'><div id='tmp'></div></div>" ) ); assert.equal( jQuery( "#first" ).children().length, 1, "Only one child" ); assert.ok( jQuery( "#first" ).children().is( ".red" ), "Verify Right Element" ); assert.equal( jQuery( "#first" ).children().children().children().length, num, "Verify Elements Intact" ); num = jQuery( "#first" ).html( "foo<div>test</div><div>test2</div>" ).children().length; jQuery( "#first" ).wrapInner( val( "<div class='red'><div id='tmp'></div></div>" ) ); assert.equal( jQuery( "#first" ).children().length, 1, "Only one child" ); assert.ok( jQuery( "#first" ).children().is( ".red" ), "Verify Right Element" ); assert.equal( jQuery( "#first" ).children().children().children().length, num, "Verify Elements Intact" ); } ); QUnit.test( "wrapInner(Function) returns Element", function( assert ) { assert.expect( 5 ); var num, val = manipulationFunctionReturningObj, div = jQuery( "<div></div>" ); num = jQuery( "#first" ).children().length; jQuery( "#first" ).wrapInner( val( document.getElementById( "empty" ) ) ); assert.equal( jQuery( "#first" ).children().length, 1, "Only one child" ); assert.ok( jQuery( "#first" ).children().is( "#empty" ), "Verify Right Element" ); assert.equal( jQuery( "#first" ).children().children().length, num, "Verify Elements Intact" ); div.wrapInner( val( "<span></span>" ) ); assert.equal( div.children().length, 1, "The contents were wrapped." ); assert.equal( div.children()[ 0 ].nodeName.toLowerCase(), "span", "A span was inserted." ); } ); QUnit.test( "unwrap()", function( assert ) { assert.expect( 9 ); jQuery( "body" ).append( " <div id='unwrap' style='display: none;'> <div id='unwrap1'>" + " <span class='unwrap'>a</span> <span class='unwrap'>b</span> </div> <div id='unwrap2'>" + " <span class='unwrap'>c</span> <span class='unwrap'>d</span> </div> <div id='unwrap3'>" + " <b><span class='unwrap unwrap3'>e</span></b>" + " <b><span class='unwrap unwrap3'>f</span></b> </div> </div>" ); var abcd = jQuery( "#unwrap1 > span, #unwrap2 > span" ).get(), abcdef = jQuery( "#unwrap span" ).get(); assert.equal( jQuery( "#unwrap1 span" ).add( "#unwrap2 span:first-child" ).unwrap().length, 3, "make #unwrap1 and #unwrap2 go away" ); assert.deepEqual( jQuery( "#unwrap > span" ).get(), abcd, "all four spans should still exist" ); assert.deepEqual( jQuery( "#unwrap3 span" ).unwrap().get(), jQuery( "#unwrap3 > span" ).get(), "make all b in #unwrap3 go away" ); assert.deepEqual( jQuery( "#unwrap3 span" ).unwrap().get(), jQuery( "#unwrap > span.unwrap3" ).get(), "make #unwrap3 go away" ); assert.deepEqual( jQuery( "#unwrap" ).children().get(), abcdef, "#unwrap only contains 6 child spans" ); assert.deepEqual( jQuery( "#unwrap > span" ).unwrap().get(), jQuery( "body > span.unwrap" ).get(), "make the 6 spans become children of body" ); assert.deepEqual( jQuery( "body > span.unwrap" ).unwrap().get(), jQuery( "body > span.unwrap" ).get(), "can't unwrap children of body" ); assert.deepEqual( jQuery( "body > span.unwrap" ).unwrap().get(), abcdef, "can't unwrap children of body" ); assert.deepEqual( jQuery( "body > span.unwrap" ).get(), abcdef, "body contains 6 .unwrap child spans" ); jQuery( "body > span.unwrap" ).remove(); } ); QUnit.test( "unwrap( selector )", function( assert ) { assert.expect( 5 ); jQuery( "body" ).append( " <div id='unwrap' style='display: none;'> <div id='unwrap1'>" + "<span class='unwrap'>a</span> <span class='unwrap'>b</span> </div>" + " <div id='unwrap2'> <span class='unwrap'>c</span> <span class='unwrap'>d</span>" + " </div> </div>" ); // Shouldn't unwrap, no match jQuery( "#unwrap1 span" ) .unwrap( "#unwrap2" ); assert.equal( jQuery( "#unwrap1" ).length, 1, "still wrapped" ); // Shouldn't unwrap, no match jQuery( "#unwrap1 span" ) .unwrap( "span" ); assert.equal( jQuery( "#unwrap1" ).length, 1, "still wrapped" ); // Unwraps jQuery( "#unwrap1 span" ) .unwrap( "#unwrap1" ); assert.equal( jQuery( "#unwrap1" ).length, 0, "unwrapped match" ); // Check return values assert.deepEqual( jQuery( "#unwrap2 span" ).get(), jQuery( "#unwrap2 span" ).unwrap( "quote" ).get(), "return on unmatched unwrap" ); assert.deepEqual( jQuery( "#unwrap2 span" ).get(), jQuery( "#unwrap2 span" ).unwrap( "#unwrap2" ).get(), "return on matched unwrap" ); jQuery( "body > span.unwrap" ).remove(); } ); QUnit.test( "jQuery(<tag>) & wrap[Inner/All]() handle unknown elems (trac-10667)", function( assert ) { assert.expect( 2 ); var $wraptarget = jQuery( "<div id='wrap-target'>Target</div>" ).appendTo( "#qunit-fixture" ), $section = jQuery( "<section>" ).appendTo( "#qunit-fixture" ); $wraptarget.wrapAll( "<aside style='background-color:green'></aside>" ); assert.notEqual( $wraptarget.parent( "aside" ).get( 0 ).style.backgroundColor, "transparent", "HTML5 elements created with wrapAll inherit styles" ); assert.notEqual( $section.get( 0 ).style.backgroundColor, "transparent", "HTML5 elements create with jQuery( string ) inherit styles" ); } ); QUnit.test( "wrapping scripts (trac-10470)", function( assert ) { assert.expect( 2 ); var script = document.createElement( "script" ); script.text = script.textContent = "QUnit.assert.ok( !document.eval10470, 'script evaluated once' ); document.eval10470 = true;"; document.eval10470 = false; jQuery( "#qunit-fixture" ).empty()[ 0 ].appendChild( script ); jQuery( "#qunit-fixture script" ).wrap( "<b></b>" ); assert.strictEqual( script.parentNode, jQuery( "#qunit-fixture > b" )[ 0 ], "correctly wrapped" ); jQuery( script ).remove(); } ); } )();
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
false
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/test/unit/callbacks.js
test/unit/callbacks.js
QUnit.module( "callbacks", { afterEach: moduleTeardown } ); ( function() { if ( !includesModule( "callbacks" ) ) { return; } ( function() { var output, addToOutput = function( string ) { return function() { output += string; }; }, outputA = addToOutput( "A" ), outputB = addToOutput( "B" ), outputC = addToOutput( "C" ), /* eslint-disable key-spacing */ tests = { "": "XABC X XABCABCC X XBB X XABA X XX", "once": "XABC X X X X X XABA X XX", "memory": "XABC XABC XABCABCCC XA XBB XB XABA XC XX", "unique": "XABC X XABCA X XBB X XAB X X", "stopOnFalse": "XABC X XABCABCC X XBB X XA X XX", "once memory": "XABC XABC X XA X XA XABA XC XX", "once unique": "XABC X X X X X XAB X X", "once stopOnFalse": "XABC X X X X X XA X XX", "memory unique": "XABC XA XABCA XA XBB XB XAB XC X", "memory stopOnFalse": "XABC XABC XABCABCCC XA XBB XB XA X XX", "unique stopOnFalse": "XABC X XABCA X XBB X XA X X" }, filters = { "no filter": undefined, "filter": function( fn ) { return function() { return fn.apply( this, arguments ); }; } }; function showFlags( flags ) { if ( typeof flags === "string" ) { return "'" + flags + "'"; } var output = [], key; for ( key in flags ) { output.push( "'" + key + "': " + flags[ key ] ); } return "{ " + output.join( ", " ) + " }"; } jQuery.each( tests, function( strFlags, resultString ) { var objectFlags = {}; jQuery.each( strFlags.split( " " ), function() { if ( this.length ) { objectFlags[ this ] = true; } } ); jQuery.each( filters, function( filterLabel ) { jQuery.each( { "string": strFlags, "object": objectFlags }, function( flagsTypes, flags ) { QUnit.test( "jQuery.Callbacks( " + showFlags( flags ) + " ) - " + filterLabel, function( assert ) { assert.expect( 29 ); var cblist, results = resultString.split( /\s+/ ); // Basic binding and firing output = "X"; cblist = jQuery.Callbacks( flags ); assert.strictEqual( cblist.locked(), false, ".locked() initially false" ); assert.strictEqual( cblist.disabled(), false, ".disabled() initially false" ); assert.strictEqual( cblist.fired(), false, ".fired() initially false" ); cblist.add( function( str ) { output += str; } ); assert.strictEqual( cblist.fired(), false, ".fired() still false after .add" ); cblist.fire( "A" ); assert.strictEqual( output, "XA", "Basic binding and firing" ); assert.strictEqual( cblist.fired(), true, ".fired() detects firing" ); output = "X"; cblist.disable(); cblist.add( function( str ) { output += str; } ); assert.strictEqual( output, "X", "Adding a callback after disabling" ); cblist.fire( "A" ); assert.strictEqual( output, "X", "Firing after disabling" ); assert.strictEqual( cblist.disabled(), true, ".disabled() becomes true" ); assert.strictEqual( cblist.locked(), true, "disabling locks" ); // Emptying while firing (trac-13517) cblist = jQuery.Callbacks( flags ); cblist.add( cblist.empty ); cblist.add( function() { assert.ok( false, "not emptied" ); } ); cblist.fire(); // Disabling while firing cblist = jQuery.Callbacks( flags ); cblist.add( cblist.disable ); cblist.add( function() { assert.ok( false, "not disabled" ); } ); cblist.fire(); // Basic binding and firing (context, arguments) output = "X"; cblist = jQuery.Callbacks( flags ); cblist.add( function() { assert.equal( this, window, "Basic binding and firing (context)" ); output += Array.prototype.join.call( arguments, "" ); } ); cblist.fireWith( window, [ "A", "B" ] ); assert.strictEqual( output, "XAB", "Basic binding and firing (arguments)" ); // fireWith with no arguments output = ""; cblist = jQuery.Callbacks( flags ); cblist.add( function() { assert.equal( this, window, "fireWith with no arguments (context is window)" ); assert.strictEqual( arguments.length, 0, "fireWith with no arguments (no arguments)" ); } ); cblist.fireWith(); // Basic binding, removing and firing output = "X"; cblist = jQuery.Callbacks( flags ); cblist.add( outputA, outputB, outputC ); cblist.remove( outputB, outputC ); cblist.fire(); assert.strictEqual( output, "XA", "Basic binding, removing and firing" ); // Empty output = "X"; cblist = jQuery.Callbacks( flags ); cblist.add( outputA ); cblist.add( outputB ); cblist.add( outputC ); cblist.empty(); cblist.fire(); assert.strictEqual( output, "X", "Empty" ); // Locking output = "X"; cblist = jQuery.Callbacks( flags ); cblist.add( function( str ) { output += str; } ); cblist.lock(); cblist.add( function( str ) { output += str; } ); cblist.fire( "A" ); cblist.add( function( str ) { output += str; } ); assert.strictEqual( output, "X", "Lock early" ); assert.strictEqual( cblist.locked(), true, "Locking reflected in accessor" ); // Locking while firing (gh-1990) output = "X"; cblist = jQuery.Callbacks( flags ); cblist.add( cblist.lock ); cblist.add( function( str ) { output += str; } ); cblist.fire( "A" ); assert.strictEqual( output, "XA", "Locking doesn't abort execution (gh-1990)" ); // Ordering output = "X"; cblist = jQuery.Callbacks( flags ); cblist.add( function() { cblist.add( outputC ); outputA(); }, outputB ); cblist.fire(); assert.strictEqual( output, results.shift(), "Proper ordering" ); // Add and fire again output = "X"; cblist.add( function() { cblist.add( outputC ); outputA(); }, outputB ); assert.strictEqual( output, results.shift(), "Add after fire" ); output = "X"; cblist.fire(); assert.strictEqual( output, results.shift(), "Fire again" ); // Multiple fire output = "X"; cblist = jQuery.Callbacks( flags ); cblist.add( function( str ) { output += str; } ); cblist.fire( "A" ); assert.strictEqual( output, "XA", "Multiple fire (first fire)" ); output = "X"; cblist.add( function( str ) { output += str; } ); assert.strictEqual( output, results.shift(), "Multiple fire (first new callback)" ); output = "X"; cblist.fire( "B" ); assert.strictEqual( output, results.shift(), "Multiple fire (second fire)" ); output = "X"; cblist.add( function( str ) { output += str; } ); assert.strictEqual( output, results.shift(), "Multiple fire (second new callback)" ); // Return false output = "X"; cblist = jQuery.Callbacks( flags ); cblist.add( outputA, function() { return false; }, outputB ); cblist.add( outputA ); cblist.fire(); assert.strictEqual( output, results.shift(), "Callback returning false" ); // Add another callback (to control lists with memory do not fire anymore) output = "X"; cblist.add( outputC ); assert.strictEqual( output, results.shift(), "Adding a callback after one returned false" ); // Callbacks are not iterated output = ""; function handler() { output += "X"; } handler.method = function() { output += "!"; }; cblist = jQuery.Callbacks( flags ); cblist.add( handler ); cblist.add( handler ); cblist.fire(); assert.strictEqual( output, results.shift(), "No callback iteration" ); } ); } ); } ); } ); } )(); QUnit.test( "jQuery.Callbacks( options ) - options are copied", function( assert ) { assert.expect( 1 ); var options = { "unique": true }, cb = jQuery.Callbacks( options ), count = 0, fn = function() { assert.ok( !( count++ ), "called once" ); }; options.unique = false; cb.add( fn, fn ); cb.fire(); } ); QUnit.test( "jQuery.Callbacks.fireWith - arguments are copied", function( assert ) { assert.expect( 1 ); var cb = jQuery.Callbacks( "memory" ), args = [ "hello" ]; cb.fireWith( null, args ); args[ 0 ] = "world"; cb.add( function( hello ) { assert.strictEqual( hello, "hello", "arguments are copied internally" ); } ); } ); QUnit.test( "jQuery.Callbacks.remove - should remove all instances", function( assert ) { assert.expect( 1 ); var cb = jQuery.Callbacks(); function fn() { assert.ok( false, "function wasn't removed" ); } cb.add( fn, fn, function() { assert.ok( true, "end of test" ); } ).remove( fn ).fire(); } ); QUnit.test( "jQuery.Callbacks.has", function( assert ) { assert.expect( 13 ); var cb = jQuery.Callbacks(); function getA() { return "A"; } function getB() { return "B"; } function getC() { return "C"; } cb.add( getA, getB, getC ); assert.strictEqual( cb.has(), true, "No arguments to .has() returns whether callback function(s) are attached or not" ); assert.strictEqual( cb.has( getA ), true, "Check if a specific callback function is in the Callbacks list" ); cb.remove( getB ); assert.strictEqual( cb.has( getB ), false, "Remove a specific callback function and make sure its no longer there" ); assert.strictEqual( cb.has( getA ), true, "Remove a specific callback function and make sure other callback function is still there" ); cb.empty(); assert.strictEqual( cb.has(), false, "Empty list and make sure there are no callback function(s)" ); assert.strictEqual( cb.has( getA ), false, "Check for a specific function in an empty() list" ); cb.add( getA, getB, function() { assert.strictEqual( cb.has(), true, "Check if list has callback function(s) from within a callback function" ); assert.strictEqual( cb.has( getA ), true, "Check if list has a specific callback from within a callback function" ); } ).fire(); assert.strictEqual( cb.has(), true, "Callbacks list has callback function(s) after firing" ); cb.disable(); assert.strictEqual( cb.has(), false, "disabled() list has no callback functions (returns false)" ); assert.strictEqual( cb.has( getA ), false, "Check for a specific function in a disabled() list" ); cb = jQuery.Callbacks( "unique" ); cb.add( getA ); cb.add( getA ); assert.strictEqual( cb.has(), true, "Check if unique list has callback function(s) attached" ); cb.lock(); assert.strictEqual( cb.has(), false, "locked() list is empty and returns false" ); } ); QUnit.test( "jQuery.Callbacks() - adding a string doesn't cause a stack overflow", function( assert ) { assert.expect( 1 ); jQuery.Callbacks().add( "hello world" ); assert.ok( true, "no stack overflow" ); } ); QUnit.test( "jQuery.Callbacks() - disabled callback doesn't fire (gh-1790)", function( assert ) { assert.expect( 1 ); var cb = jQuery.Callbacks(), fired = false, shot = function() { fired = true; }; cb.disable(); cb.empty(); cb.add( shot ); cb.fire(); assert.ok( !fired, "Disabled callback function didn't fire" ); } ); QUnit.test( "jQuery.Callbacks() - list with memory stays locked (gh-3469)", function( assert ) { assert.expect( 3 ); var cb = jQuery.Callbacks( "memory" ), fired = 0, count1 = function() { fired += 1; }, count2 = function() { fired += 10; }; cb.add( count1 ); cb.fire(); assert.equal( fired, 1, "Pre-lock() fire" ); cb.lock(); cb.add( count2 ); assert.equal( fired, 11, "Post-lock() add" ); cb.fire(); assert.equal( fired, 11, "Post-lock() fire ignored" ); } ); } )();
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
false
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/test/unit/basic.js
test/unit/basic.js
QUnit.module( "basic", { afterEach: moduleTeardown } ); if ( includesModule( "ajax" ) ) { QUnit.test( "ajax", function( assert ) { assert.expect( 4 ); var done = assert.async( 3 ); jQuery.ajax( { type: "GET", url: url( "mock.php?action=name&name=foo" ), success: function( msg ) { assert.strictEqual( msg, "bar", "Check for GET" ); done(); } } ); jQuery.ajax( { type: "POST", url: url( "mock.php?action=name" ), data: "name=peter", success: function( msg ) { assert.strictEqual( msg, "pan", "Check for POST" ); done(); } } ); jQuery( "#first" ).load( url( "name.html" ), function() { assert.ok( /^ERROR/.test( jQuery( "#first" ).text() ), "Check if content was injected into the DOM" ); done(); } ); } ); } if ( includesModule( "attributes" ) ) { QUnit.test( "attributes", function( assert ) { assert.expect( 6 ); var a = jQuery( "<a></a>" ).appendTo( "#qunit-fixture" ), input = jQuery( "<input/>" ).appendTo( "#qunit-fixture" ); assert.strictEqual( a.attr( "foo", "bar" ).attr( "foo" ), "bar", ".attr getter/setter" ); assert.strictEqual( a.removeAttr( "foo" ).attr( "foo" ), undefined, ".removeAttr" ); assert.strictEqual( a.prop( "href", "#5" ).prop( "href" ), location.href.replace( /\#.*$/, "" ) + "#5", ".prop getter/setter" ); a.addClass( "abc def ghj" ).removeClass( "def ghj" ); assert.strictEqual( a.hasClass( "abc" ), true, ".(add|remove|has)Class, class present" ); assert.strictEqual( a.hasClass( "def" ), false, ".(add|remove|has)Class, class missing" ); assert.strictEqual( input.val( "xyz" ).val(), "xyz", ".val getter/setter" ); } ); } if ( includesModule( "css" ) ) { QUnit.test( "css", function( assert ) { assert.expect( 1 ); var div = jQuery( "<div></div>" ).appendTo( "#qunit-fixture" ); assert.strictEqual( div.css( "width", "50px" ).css( "width" ), "50px", ".css getter/setter" ); } ); } if ( includesModule( "css" ) ) { QUnit.test( "show/hide", function( assert ) { assert.expect( 2 ); var div = jQuery( "<div></div>" ).appendTo( "#qunit-fixture" ); div.hide(); assert.strictEqual( div.css( "display" ), "none", "div hidden" ); div.show(); assert.strictEqual( div.css( "display" ), "block", "div shown" ); } ); } QUnit.test( "core", function( assert ) { assert.expect( 17 ); var elem = jQuery( "<div></div><span></span>" ); assert.strictEqual( elem.length, 2, "Correct number of elements" ); assert.ok( jQuery.isPlainObject( { "a": 2 } ), "jQuery.isPlainObject(object)" ); assert.ok( !jQuery.isPlainObject( "foo" ), "jQuery.isPlainObject(String)" ); assert.ok( jQuery.isXMLDoc( jQuery.parseXML( "<?xml version='1.0' encoding='UTF-8'?><foo bar='baz'></foo>" ) ), "jQuery.isXMLDoc" ); assert.strictEqual( jQuery.inArray( 3, [ "a", 6, false, 3, {} ] ), 3, "jQuery.inArray - true" ); assert.strictEqual( jQuery.inArray( 3, [ "a", 6, false, "3", {} ] ), -1, "jQuery.inArray - false" ); assert.strictEqual( elem.get( 1 ), elem[ 1 ], ".get" ); assert.strictEqual( elem.first()[ 0 ], elem[ 0 ], ".first" ); assert.strictEqual( elem.last()[ 0 ], elem[ 1 ], ".last" ); assert.deepEqual( jQuery.map( [ "a", "b", "c" ], function( v, k ) { return k + v; } ), [ "0a", "1b", "2c" ], "jQuery.map" ); assert.deepEqual( jQuery.merge( [ 1, 2 ], [ "a", "b" ] ), [ 1, 2, "a", "b" ], "jQuery.merge" ); assert.deepEqual( jQuery.grep( [ 1, 2, 3 ], function( value ) { return value % 2 !== 0; } ), [ 1, 3 ], "jQuery.grep" ); assert.deepEqual( jQuery.extend( { a: 2 }, { b: 3 } ), { a: 2, b: 3 }, "jQuery.extend" ); jQuery.each( [ 0, 2 ], function( k, v ) { assert.strictEqual( k * 2, v, "jQuery.each" ); } ); assert.deepEqual( jQuery.makeArray( { 0: "a", 1: "b", 2: "c", length: 3 } ), [ "a", "b", "c" ], "jQuery.makeArray" ); assert.strictEqual( jQuery.parseHTML( "<div></div><span></span>" ).length, 2, "jQuery.parseHTML" ); } ); if ( includesModule( "data" ) ) { QUnit.test( "data", function( assert ) { assert.expect( 4 ); var elem = jQuery( "<div data-c='d'></div>" ).appendTo( "#qunit-fixture" ); assert.ok( !jQuery.hasData( elem[ 0 ] ), "jQuery.hasData - false" ); assert.strictEqual( elem.data( "a", "b" ).data( "a" ), "b", ".data getter/setter" ); assert.strictEqual( elem.data( "c" ), "d", ".data from data-* attributes" ); assert.ok( jQuery.hasData( elem[ 0 ] ), "jQuery.hasData - true" ); } ); } if ( includesModule( "dimensions" ) ) { QUnit.test( "dimensions", function( assert ) { assert.expect( 3 ); var elem = jQuery( "<div style='margin: 10px; padding: 7px; border: 2px solid black;'></div> " ).appendTo( "#qunit-fixture" ); assert.strictEqual( elem.width( 50 ).width(), 50, ".width getter/setter" ); assert.strictEqual( elem.innerWidth(), 64, ".innerWidth getter" ); assert.strictEqual( elem.outerWidth(), 68, ".outerWidth getter" ); } ); } if ( includesModule( "event" ) ) { QUnit.test( "event", function( assert ) { assert.expect( 1 ); var elem = jQuery( "<div></div>" ).appendTo( "#qunit-fixture" ); elem .on( "click", function() { assert.ok( false, "click should not fire" ); } ) .off( "click" ) .trigger( "click" ) .on( "click", function() { assert.ok( true, "click should fire" ); } ) .trigger( "click" ); } ); } if ( includesModule( "manipulation" ) ) { QUnit.test( "manipulation", function( assert ) { assert.expect( 5 ); var child, elem1 = jQuery( "<div><span></span></div>" ).appendTo( "#qunit-fixture" ), elem2 = jQuery( "<div></div>" ).appendTo( "#qunit-fixture" ); assert.strictEqual( elem1.text( "foo" ).text(), "foo", ".html getter/setter" ); assert.strictEqual( elem1.html( "<span></span>" ).html(), "<span></span>", ".html getter/setter" ); assert.strictEqual( elem1.append( elem2 )[ 0 ].childNodes[ elem1[ 0 ].childNodes.length - 1 ], elem2[ 0 ], ".append" ); assert.strictEqual( elem1.prepend( elem2 )[ 0 ].childNodes[ 0 ], elem2[ 0 ], ".prepend" ); child = elem1.find( "span" ); child.after( "<a></a>" ); child.before( "<b></b>" ); assert.strictEqual( elem1.html(), "<div></div><b></b><span></span><a></a>", ".after/.before" ); } ); } if ( includesModule( "offset" ) ) { // Support: jsdom 13.2+ // jsdom returns 0 for offset-related properties QUnit[ /jsdom\//.test( navigator.userAgent ) ? "skip" : "test" ]( "offset", function( assert ) { assert.expect( 3 ); var parent = jQuery( "<div style='position:fixed;top:20px;'></div>" ).appendTo( "#qunit-fixture" ), elem = jQuery( "<div style='position:absolute;top:5px;'></div>" ).appendTo( parent ); assert.strictEqual( elem.offset().top, 25, ".offset getter" ); assert.strictEqual( elem.position().top, 5, ".position getter" ); assert.strictEqual( elem.offsetParent()[ 0 ], parent[ 0 ], ".offsetParent" ); } ); } QUnit.test( "selector", function( assert ) { assert.expect( 2 ); var elem = jQuery( "<div><span class='a'></span><span class='b'><a></a></span></div>" ) .appendTo( "#qunit-fixture" ); assert.strictEqual( elem.find( ".a a" ).length, 0, ".find - no result" ); assert.strictEqual( elem.find( "span.b a" )[ 0 ].nodeName, "A", ".find - one result" ); } ); if ( includesModule( "serialize" ) ) { QUnit.test( "serialize", function( assert ) { assert.expect( 2 ); var params = { "someName": [ 1, 2, 3 ], "regularThing": "blah" }; assert.strictEqual( jQuery.param( params ), "someName%5B%5D=1&someName%5B%5D=2&someName%5B%5D=3&regularThing=blah", "jQuery.param" ); assert.strictEqual( jQuery( "#form" ).serialize(), "action=Test&radio2=on&check=on&hidden=&foo%5Bbar%5D=&name=name&search=search" + "&select1=&select2=3&select3=1&select3=2&select5=3", "form serialization as query string" ); } ); } QUnit.test( "traversing", function( assert ) { assert.expect( 12 ); var elem = jQuery( "<div><a><b><em></em></b></a><i></i><span></span>foo</div>" ) .appendTo( "#qunit-fixture" ); assert.strictEqual( elem.find( "em" ).parent()[ 0 ].nodeName, "B", ".parent" ); assert.strictEqual( elem.find( "em" ).parents()[ 1 ].nodeName, "A", ".parents" ); assert.strictEqual( elem.find( "em" ).parentsUntil( "div" ).length, 2, ".parentsUntil" ); assert.strictEqual( elem.find( "i" ).next()[ 0 ].nodeName, "SPAN", ".next" ); assert.strictEqual( elem.find( "i" ).prev()[ 0 ].nodeName, "A", ".prev" ); assert.strictEqual( elem.find( "a" ).nextAll()[ 1 ].nodeName, "SPAN", ".nextAll" ); assert.strictEqual( elem.find( "span" ).prevAll()[ 1 ].nodeName, "A", ".prevAll" ); assert.strictEqual( elem.find( "a" ).nextUntil( "span" ).length, 1, ".nextUntil" ); assert.strictEqual( elem.find( "span" ).prevUntil( "a" ).length, 1, ".prevUntil" ); assert.strictEqual( elem.find( "i" ).siblings().length, 2, ".siblings" ); assert.strictEqual( elem.children()[ 2 ].nodeName, "SPAN", ".children" ); assert.strictEqual( elem.contents()[ 3 ].nodeType, 3, ".contents" ); } ); if ( includesModule( "wrap" ) ) { QUnit.test( "wrap", function( assert ) { assert.expect( 3 ); var elem = jQuery( "<div><a><b></b></a><a></a></div>" ); elem.find( "b" ).wrap( "<span>" ); assert.strictEqual( elem.html(), "<a><span><b></b></span></a><a></a>", ".wrap" ); elem.find( "span" ).wrapInner( "<em>" ); assert.strictEqual( elem.html(), "<a><span><em><b></b></em></span></a><a></a>", ".wrapInner" ); elem.find( "a" ).wrapAll( "<i>" ); assert.strictEqual( elem.html(), "<i><a><span><em><b></b></em></span></a><a></a></i>", ".wrapAll" ); } ); }
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
false
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/test/unit/support.js
test/unit/support.js
QUnit.module( "support", { afterEach: moduleTeardown } ); var computedSupport = getComputedSupport( jQuery.support ); function getComputedSupport( support ) { var prop, result = {}; for ( prop in support ) { if ( typeof support[ prop ] === "function" ) { result[ prop ] = support[ prop ](); } else { result[ prop ] = support[ prop ]; } } return result; } if ( includesModule( "css" ) ) { testIframe( "body background is not lost if set prior to loading jQuery (trac-9239)", "support/bodyBackground.html", function( assert, jQuery, window, document, color, support ) { assert.expect( 2 ); var okValue = { "#000000": true, "rgb(0, 0, 0)": true }; assert.ok( okValue[ color ], "color was not reset (" + color + ")" ); assert.deepEqual( jQuery.extend( {}, support ), computedSupport, "Same support properties" ); } ); } // This test checks CSP only for browsers with "Content-Security-Policy" header support // i.e. no IE testIframe( "Check CSP (https://developer.mozilla.org/en-US/docs/Security/CSP) restrictions", "mock.php?action=cspFrame", function( assert, jQuery, window, document, support ) { var done = assert.async(); assert.expect( 2 ); assert.deepEqual( jQuery.extend( {}, support ), computedSupport, "No violations of CSP polices" ); supportjQuery.get( baseURL + "support/csp.log" ).done( function( data ) { assert.equal( data, "", "No log request should be sent" ); supportjQuery.get( baseURL + "mock.php?action=cspClean" ).done( done ); } ); } ); testIframe( "Verify correctness of support tests with bootstrap CSS on the page", "support/bootstrap.html", function( assert, jQuery, window, document, bodyStyle, support ) { assert.expect( 2 ); assert.strictEqual( bodyStyle.boxSizing, "border-box", "border-box applied on body by Bootstrap" ); assert.deepEqual( jQuery.extend( {}, support ), computedSupport, "Same support properties" ); } ); testIframe( "Verify correctness of support tests with CSS zoom on the root element", "support/zoom.html", function( assert, jQuery, window, document, htmlStyle, support ) { assert.expect( 1 ); assert.deepEqual( jQuery.extend( {}, support ), computedSupport, "Same support properties" ); } ); ( function() { var expected, userAgent = window.navigator.userAgent, expectedMap = { ie_11: { reliableColDimensions: 11, reliableTrDimensions: false }, chrome: { reliableColDimensions: true, reliableTrDimensions: true }, safari: { reliableColDimensions: false, reliableTrDimensions: true }, firefox: { reliableColDimensions: false, reliableTrDimensions: false }, ios: { reliableColDimensions: false, reliableTrDimensions: true } }; if ( QUnit.isIE ) { expected = expectedMap.ie_11; } else if ( /\b(?:headless)?chrome\//i.test( userAgent ) ) { // Catches Edge, Chrome on Android & Opera as well. expected = expectedMap.chrome; } else if ( /\bfirefox\//i.test( userAgent ) ) { expected = expectedMap.firefox; } else if ( /\biphone os \d+_/i.test( userAgent ) ) { expected = expectedMap.ios; } else if ( /\bversion\/\d+(?:\.\d+)+ safari/i.test( userAgent ) ) { if ( navigator.maxTouchPoints > 1 ) { expected = expectedMap.ios; } else { expected = expectedMap.safari; } } QUnit.test( "Verify that support tests resolve as expected per browser", function( assert ) { if ( !expected ) { assert.expect( 1 ); assert.ok( false, "Known client: " + userAgent ); } var i, prop, j = 0; for ( prop in computedSupport ) { j++; } // Add an assertion per undefined support prop as it may // not even exist on computedSupport but we still want to run // the check. for ( prop in expected ) { if ( expected[ prop ] === undefined ) { j++; } } assert.expect( j ); for ( i in expected ) { assert.equal( computedSupport[ i ], expected[ i ], "jQuery.support['" + i + "']: " + computedSupport[ i ] + ", expected['" + i + "']: " + expected[ i ] + ";\nUser Agent: " + navigator.userAgent ); } } ); QUnit.test( "Verify support tests are failing in one of tested browsers", function( assert ) { var prop, browserKey, supportTestName, i = 0, supportProps = {}, failingSupportProps = {}; for ( prop in computedSupport ) { i++; } // Add an assertion per undefined support prop as it may // not even exist on computedSupport but we still want to run // the check. for ( prop in expected ) { if ( expected[ prop ] === undefined ) { i++; } } assert.expect( i ); // Record all support props and the failing ones and ensure every test // is failing at least once. for ( browserKey in expectedMap ) { for ( supportTestName in expectedMap[ browserKey ] ) { supportProps[ supportTestName ] = true; if ( !expectedMap[ browserKey ][ supportTestName ] ) { failingSupportProps[ supportTestName ] = true; } } } for ( supportTestName in supportProps ) { assert.ok( failingSupportProps[ supportTestName ], "jQuery.support['" + supportTestName + "'] is expected to fail at least in one browser" ); } } ); } )();
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
false
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/test/unit/ready.js
test/unit/ready.js
QUnit.module( "ready" ); ( function() { var notYetReady, noEarlyExecution, whenified = jQuery.when && jQuery.when( jQuery.ready ), promisified = Promise.resolve( jQuery.ready ), start = new Date(), order = [], args = {}; notYetReady = !jQuery.isReady; QUnit.test( "jQuery.isReady", function( assert ) { assert.expect( 2 ); assert.equal( notYetReady, true, "jQuery.isReady should not be true before DOM ready" ); assert.equal( jQuery.isReady, true, "jQuery.isReady should be true once DOM is ready" ); } ); // Create an event handler. function makeHandler( testId ) { // When returned function is executed, push testId onto `order` array // to ensure execution order. Also, store event handler arg to ensure // the correct arg is being passed into the event handler. return function( arg ) { order.push( testId ); args[ testId ] = arg; }; } function throwError( num ) { // Not a global QUnit failure var onerror = window.onerror; window.onerror = function() { window.onerror = onerror; }; throw new Error( "Ready error " + num ); } // Bind to the ready event in every possible way. jQuery( makeHandler( "a" ) ); jQuery( document ).ready( makeHandler( "b" ) ); jQuery.ready.then( makeHandler( "c" ) ); // Throw in some errors jQuery( function() { throwError( 1 ); } ); jQuery( function() { throwError( 2 ); } ); // Bind again to ensure that the errors didn't lock everything up jQuery( makeHandler( "d" ) ); jQuery( document ).ready( makeHandler( "e" ) ); jQuery.ready.then( makeHandler( "f" ) ); noEarlyExecution = order.length === 0; // This assumes that QUnit tests are run on DOM ready! QUnit.test( "jQuery ready", function( assert ) { assert.expect( 10 ); assert.ok( noEarlyExecution, "Handlers bound to DOM ready should not execute before DOM ready" ); // Ensure execution order. assert.deepEqual( order, [ "a", "b", "c", "d", "e", "f" ], "Bound DOM ready handlers should execute in bind order" ); // Ensure handler argument is correct. assert.equal( args.a, jQuery, "Argument passed to fn in jQuery( fn ) should be jQuery" ); assert.equal( args.b, jQuery, "Argument passed to fn in jQuery(document).ready( fn ) should be jQuery" ); order = []; // Now that the ready event has fired, again bind to the ready event. // These ready handlers should execute asynchronously. var done = assert.async(); jQuery( makeHandler( "g" ) ); jQuery( document ).ready( makeHandler( "h" ) ); jQuery.ready.then( makeHandler( "i" ) ); window.setTimeout( function() { assert.equal( order.shift(), "g", "Event handler should execute immediately, but async" ); assert.equal( args.g, jQuery, "Argument passed to fn in jQuery( fn ) should be jQuery" ); assert.equal( order.shift(), "h", "Event handler should execute immediately, but async" ); assert.equal( args.h, jQuery, "Argument passed to fn in jQuery(document).ready( fn ) should be jQuery" ); assert.equal( order.shift(), "i", "Event handler should execute immediately, but async" ); assert.equal( args.h, jQuery, "Argument passed to fn in jQuery.ready.then( fn ) should be jQuery" ); done(); } ); } ); QUnit[ includesModule( "deferred" ) ? "test" : "skip" ]( "jQuery.when(jQuery.ready)", function( assert ) { assert.expect( 2 ); var done = assert.async( 2 ); whenified.then( function() { assert.ok( jQuery.isReady, "jQuery.when Deferred resolved" ); done(); } ); jQuery.when( jQuery.ready ).then( function() { assert.ok( jQuery.isReady, "jQuery.when Deferred resolved" ); done(); } ); } ); QUnit.test( "Promise.resolve(jQuery.ready)", function( assert ) { assert.expect( 2 ); var done = assert.async( 2 ); promisified.then( function() { assert.ok( jQuery.isReady, "Native promised resolved" ); done(); } ); Promise.resolve( jQuery.ready ).then( function() { assert.ok( jQuery.isReady, "Native promised resolved" ); done(); } ); } ); QUnit.test( "Error in ready callback does not halt all future executions (gh-1823)", function( assert ) { assert.expect( 1 ); var done = assert.async(); jQuery( function() { throwError( 3 ); } ); jQuery( function() { assert.ok( true, "Subsequent handler called" ); done(); } ); } ); // jQuery.holdReady is deprecated, skip the test if it was excluded. if ( includesModule( "deprecated" ) ) { testIframe( "holdReady test needs to be a standalone test since it deals with DOM ready", "readywait.html", function( assert, jQuery, window, document, releaseCalled ) { assert.expect( 2 ); var now = new Date(); assert.ok( now - start >= 300, "Needs to have waited at least half a second" ); assert.ok( releaseCalled, "The release function was called, which resulted in ready" ); } ); } } )();
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
false
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/test/unit/ajax.js
test/unit/ajax.js
QUnit.module( "ajax", { afterEach: function() { jQuery( document ).off( "ajaxStart ajaxStop ajaxSend ajaxComplete ajaxError ajaxSuccess" ); moduleTeardown.apply( this, arguments ); } } ); ( function() { QUnit.test( "Unit Testing Environment", function( assert ) { assert.expect( 2 ); assert.ok( hasPHP, "Running in an environment with PHP support. The AJAX tests only run if the environment supports PHP!" ); assert.ok( !isLocal, "Unit tests are not ran from file:// (especially in Chrome. If you must test from file:// with Chrome, run it with the --allow-file-access-from-files flag!)" ); } ); if ( !includesModule( "ajax" ) || ( isLocal && !hasPHP ) ) { return; } function addGlobalEvents( expected, assert ) { return function() { expected = expected || ""; jQuery( document ).on( "ajaxStart ajaxStop ajaxSend ajaxComplete ajaxError ajaxSuccess", function( e ) { assert.ok( expected.indexOf( e.type ) !== -1, e.type ); } ); }; } //----------- jQuery.ajax() testIframe( "XMLHttpRequest - Attempt to block tests because of dangling XHR requests (IE)", "ajax/unreleasedXHR.html", function( assert ) { assert.expect( 1 ); assert.ok( true, "done" ); } ); ajaxTest( "jQuery.ajax() - success callbacks", 8, function( assert ) { return { setup: addGlobalEvents( "ajaxStart ajaxStop ajaxSend ajaxComplete ajaxSuccess", assert ), url: url( "name.html" ), beforeSend: function() { assert.ok( true, "beforeSend" ); }, success: function() { assert.ok( true, "success" ); }, complete: function() { assert.ok( true, "complete" ); } }; } ); ajaxTest( "jQuery.ajax() - success callbacks - (url, options) syntax", 8, function( assert ) { return { setup: addGlobalEvents( "ajaxStart ajaxStop ajaxSend ajaxComplete ajaxSuccess", assert ), create: function( options ) { return jQuery.ajax( url( "name.html" ), options ); }, beforeSend: function() { assert.ok( true, "beforeSend" ); }, success: function() { assert.ok( true, "success" ); }, complete: function() { assert.ok( true, "complete" ); } }; } ); jQuery.each( [ " - Same Domain", " - Cross Domain" ], function( crossDomain, label ) { ajaxTest( "jQuery.ajax() - custom attributes for script tag" + label, 5, function( assert ) { return { create: function( options ) { var xhr; options.crossDomain = crossDomain; options.method = "POST"; options.dataType = "script"; options.scriptAttrs = { id: "jquery-ajax-test", async: "async" }; xhr = jQuery.ajax( url( "mock.php?action=script" ), options ); assert.equal( jQuery( "#jquery-ajax-test" ).attr( "async" ), "async", "attr value" ); return xhr; }, beforeSend: function( _jqXhr, settings ) { assert.strictEqual( settings.type, "GET", "Type changed to GET" ); }, success: function() { assert.ok( true, "success" ); }, complete: function() { assert.ok( true, "complete" ); } }; } ); ajaxTest( "jQuery.ajax() - headers for script transport" + label, 3, function( assert ) { return { create: function( options ) { Globals.register( "corsCallback" ); window.corsCallback = function( response ) { assert.strictEqual( response.headers[ "x-custom-test-header" ], "test value", "Custom header sent" ); }; options.crossDomain = crossDomain; options.dataType = "script"; options.headers = { "x-custom-test-header": "test value" }; return jQuery.ajax( url( "mock.php?action=script&callback=corsCallback" ), options ); }, success: function() { assert.ok( true, "success" ); }, complete: function() { assert.ok( true, "complete" ); } }; } ); ajaxTest( "jQuery.ajax() - scriptAttrs winning over headers" + label, 4, function( assert ) { return { create: function( options ) { var xhr; Globals.register( "corsCallback" ); window.corsCallback = function( response ) { assert.ok( !response.headers[ "x-custom-test-header" ], "headers losing with scriptAttrs" ); }; options.crossDomain = crossDomain; options.dataType = "script"; options.scriptAttrs = { id: "jquery-ajax-test", async: "async" }; options.headers = { "x-custom-test-header": "test value" }; xhr = jQuery.ajax( url( "mock.php?action=script&callback=corsCallback" ), options ); assert.equal( jQuery( "#jquery-ajax-test" ).attr( "async" ), "async", "attr value" ); return xhr; }, success: function() { assert.ok( true, "success" ); }, complete: function() { assert.ok( true, "complete" ); } }; } ); } ); ajaxTest( "jQuery.ajax() - execute JS when dataType option is provided", 3, function( assert ) { return { create: function( options ) { Globals.register( "corsCallback" ); options.crossDomain = true; options.dataType = "script"; return jQuery.ajax( url( "mock.php?action=script&header=ecma" ), options ); }, success: function() { assert.ok( true, "success" ); }, complete: function() { assert.ok( true, "complete" ); } }; } ); jQuery.each( [ " - Same Domain", " - Cross Domain" ], function( crossDomain, label ) { ajaxTest( "jQuery.ajax() - do not execute JS (gh-2432, gh-4822) " + label, 1, function( assert ) { return { url: url( "mock.php?action=script&header" ), crossDomain: crossDomain, success: function() { assert.ok( true, "success" ); } }; } ); } ); ajaxTest( "jQuery.ajax() - success callbacks (late binding)", 8, function( assert ) { return { setup: addGlobalEvents( "ajaxStart ajaxStop ajaxSend ajaxComplete ajaxSuccess", assert ), url: url( "name.html" ), beforeSend: function() { assert.ok( true, "beforeSend" ); }, success: true, afterSend: function( request ) { request.always( function() { assert.ok( true, "complete" ); } ).done( function() { assert.ok( true, "success" ); } ).fail( function() { assert.ok( false, "error" ); } ); } }; } ); ajaxTest( "jQuery.ajax() - success callbacks (oncomplete binding)", 8, function( assert ) { return { setup: addGlobalEvents( "ajaxStart ajaxStop ajaxSend ajaxComplete ajaxSuccess", assert ), url: url( "name.html" ), beforeSend: function() { assert.ok( true, "beforeSend" ); }, success: true, complete: function( xhr ) { xhr.always( function() { assert.ok( true, "complete" ); } ).done( function() { assert.ok( true, "success" ); } ).fail( function() { assert.ok( false, "error" ); } ); } }; } ); ajaxTest( "jQuery.ajax() - error callbacks", 8, function( assert ) { return { setup: addGlobalEvents( "ajaxStart ajaxStop ajaxSend ajaxComplete ajaxError", assert ), url: url( "mock.php?action=wait&wait=5" ), beforeSend: function() { assert.ok( true, "beforeSend" ); }, afterSend: function( request ) { request.abort(); }, error: function() { assert.ok( true, "error" ); }, complete: function() { assert.ok( true, "complete" ); } }; } ); ajaxTest( "jQuery.ajax() - textStatus and errorThrown values", 4, function( assert ) { return [ { url: url( "mock.php?action=wait&wait=5" ), error: function( _, textStatus, errorThrown ) { assert.strictEqual( textStatus, "abort", "textStatus is 'abort' for abort" ); assert.strictEqual( errorThrown, "abort", "errorThrown is 'abort' for abort" ); }, afterSend: function( request ) { request.abort(); } }, { url: url( "mock.php?action=wait&wait=5" ), error: function( _, textStatus, errorThrown ) { assert.strictEqual( textStatus, "mystatus", "textStatus is 'mystatus' for abort('mystatus')" ); assert.strictEqual( errorThrown, "mystatus", "errorThrown is 'mystatus' for abort('mystatus')" ); }, afterSend: function( request ) { request.abort( "mystatus" ); } } ]; } ); ajaxTest( "jQuery.ajax() - responseText on error", 1, function( assert ) { return { url: url( "mock.php?action=error" ), error: function( xhr ) { assert.strictEqual( xhr.responseText, "plain text message", "Test jqXHR.responseText is filled for HTTP errors" ); } }; } ); QUnit.test( "jQuery.ajax() - retry with jQuery.ajax( this )", function( assert ) { assert.expect( 2 ); var previousUrl, firstTime = true, done = assert.async(); jQuery.ajax( { url: url( "mock.php?action=error" ), error: function() { if ( firstTime ) { firstTime = false; jQuery.ajax( this ); } else { assert.ok( true, "Test retrying with jQuery.ajax(this) works" ); jQuery.ajax( { url: url( "mock.php?action=error&x=2" ), beforeSend: function() { if ( !previousUrl ) { previousUrl = this.url; } else { assert.strictEqual( this.url, previousUrl, "url parameters are not re-appended" ); done(); return false; } }, error: function() { jQuery.ajax( this ); } } ); } } } ); } ); ajaxTest( "jQuery.ajax() - headers", 8, function( assert ) { return { setup: function() { jQuery( document ).on( "ajaxSend", function( evt, xhr ) { xhr.setRequestHeader( "ajax-send", "test" ); } ); }, url: url( "mock.php?action=headers&keys=siMPle|SometHing-elsE|OthEr|Nullable|undefined|Empty|ajax-send" ), headers: supportjQuery.extend( { "siMPle": "value", "SometHing-elsE": "other value", "OthEr": "something else", "Nullable": null, "undefined": undefined // Support: IE 9 - 11+ // IE can receive empty headers but not send them. }, QUnit.isIE ? {} : { "Empty": "" } ), success: function( data, _, xhr ) { var i, requestHeaders = jQuery.extend( this.headers, { "ajax-send": "test" } ), tmp = []; for ( i in requestHeaders ) { tmp.push( i, ": ", requestHeaders[ i ] + "", "\n" ); } tmp = tmp.join( "" ); assert.strictEqual( data, tmp, "Headers were sent" ); assert.strictEqual( xhr.getResponseHeader( "Sample-Header" ), "Hello World", "Sample header received" ); assert.ok( data.indexOf( "undefined" ) < 0, "Undefined header value was not sent" ); assert.strictEqual( xhr.getResponseHeader( "Empty-Header" ), "", "Empty header received" ); assert.strictEqual( xhr.getResponseHeader( "Sample-Header2" ), "Hello World 2", "Second sample header received" ); assert.strictEqual( xhr.getResponseHeader( "List-Header" ), "Item 1, Item 2", "List header received" ); assert.strictEqual( xhr.getResponseHeader( "constructor" ), "prototype collision (constructor)", "constructor header received" ); assert.strictEqual( xhr.getResponseHeader( "__proto__" ), null, "Undefined __proto__ header not received" ); } }; } ); ajaxTest( "jQuery.ajax() - Accept header", 1, function( assert ) { return { url: url( "mock.php?action=headers&keys=accept" ), headers: { Accept: "very wrong accept value" }, beforeSend: function( xhr ) { xhr.setRequestHeader( "Accept", "*/*" ); }, success: function( data ) { assert.strictEqual( data, "accept: */*\n", "Test Accept header is set to last value provided" ); } }; } ); ajaxTest( "jQuery.ajax() - contentType", 2, function( assert ) { return [ { url: url( "mock.php?action=headers&keys=content-type" ), contentType: "test", success: function( data ) { assert.strictEqual( data, "content-type: test\n", "Test content-type is sent when options.contentType is set" ); } }, { url: url( "mock.php?action=headers&keys=content-type" ), contentType: false, success: function( data ) { // Some server/interpreter combinations always supply a Content-Type to scripts data = data || "content-type: \n"; assert.strictEqual( data, "content-type: \n", "Test content-type is not set when options.contentType===false" ); } } ]; } ); ajaxTest( "jQuery.ajax() - protocol-less urls", 1, function( assert ) { return { url: "//somedomain.com", beforeSend: function( xhr, settings ) { assert.equal( settings.url, location.protocol + "//somedomain.com", "Make sure that the protocol is added." ); return false; }, error: true }; } ); ajaxTest( "jQuery.ajax() - URL fragment component preservation", 5, function( assert ) { return [ { url: baseURL + "name.html#foo", beforeSend: function( xhr, settings ) { assert.equal( settings.url, baseURL + "name.html#foo", "hash preserved for request with no query component." ); return false; }, error: true }, { url: baseURL + "name.html?abc#foo", beforeSend: function( xhr, settings ) { assert.equal( settings.url, baseURL + "name.html?abc#foo", "hash preserved for request with query component." ); return false; }, error: true }, { url: baseURL + "name.html?abc#foo", data: { "test": 123 }, beforeSend: function( xhr, settings ) { assert.equal( settings.url, baseURL + "name.html?abc&test=123#foo", "hash preserved for request with query component and data." ); return false; }, error: true }, { url: baseURL + "name.html?abc#foo", data: [ { name: "test", value: 123 }, { name: "devo", value: "hat" } ], beforeSend: function( xhr, settings ) { assert.equal( settings.url, baseURL + "name.html?abc&test=123&devo=hat#foo", "hash preserved for request with query component and array data." ); return false; }, error: true }, { url: baseURL + "name.html?abc#brownies", data: { "devo": "hat" }, cache: false, beforeSend: function( xhr, settings ) { // Clear the cache-buster param value var url = settings.url.replace( /_=[^&#]+/, "_=" ); assert.equal( url, baseURL + "name.html?abc&devo=hat&_=#brownies", "hash preserved for cache-busting request with query component and data." ); return false; }, error: true } ]; } ); ajaxTest( "jQuery.ajax() - traditional param encoding", 4, function( assert ) { return [ { url: "/", traditional: true, data: { "devo": "hat", "answer": 42, "quux": "a space" }, beforeSend: function( xhr, settings ) { assert.equal( settings.url, "/?devo=hat&answer=42&quux=a%20space", "Simple case" ); return false; }, error: true }, { url: "/", traditional: true, data: { "a": [ 1, 2, 3 ], "b[]": [ "b1", "b2" ] }, beforeSend: function( xhr, settings ) { assert.equal( settings.url, "/?a=1&a=2&a=3&b%5B%5D=b1&b%5B%5D=b2", "Arrays" ); return false; }, error: true }, { url: "/", traditional: true, data: { "a": [ [ 1, 2 ], [ 3, 4 ], 5 ] }, beforeSend: function( xhr, settings ) { assert.equal( settings.url, "/?a=1%2C2&a=3%2C4&a=5", "Nested arrays" ); return false; }, error: true }, { url: "/", traditional: true, data: { "a": [ "w", [ [ "x", "y" ], "z" ] ] }, cache: false, beforeSend: function( xhr, settings ) { var url = settings.url.replace( /\d{3,}/, "" ); assert.equal( url, "/?a=w&a=x%2Cy%2Cz&_=", "Cache-buster" ); return false; }, error: true } ]; } ); ajaxTest( "jQuery.ajax() - cross-domain detection", 8, function( assert ) { function request( url, title, crossDomainOrOptions ) { return jQuery.extend( { dataType: "jsonp", url: url, beforeSend: function( _, s ) { assert.ok( crossDomainOrOptions === false ? !s.crossDomain : s.crossDomain, title ); return false; }, error: true }, crossDomainOrOptions ); } var loc = document.location, samePort = loc.port || ( loc.protocol === "http:" ? 80 : 443 ), otherPort = loc.port === 666 ? 667 : 666, otherProtocol = loc.protocol === "http:" ? "https:" : "http:"; return [ request( loc.protocol + "//" + loc.hostname + ":" + samePort, "Test matching ports are not detected as cross-domain", false ), request( otherProtocol + "//" + loc.host, "Test different protocols are detected as cross-domain" ), request( "app:/path", "Adobe AIR app:/ URL detected as cross-domain" ), request( loc.protocol + "//example.invalid:" + ( loc.port || 80 ), "Test different hostnames are detected as cross-domain" ), request( loc.protocol + "//" + loc.hostname + ":" + otherPort, "Test different ports are detected as cross-domain" ), request( "about:blank", "Test about:blank is detected as cross-domain" ), request( loc.protocol + "//" + loc.host, "Test forced crossDomain is detected as cross-domain", { crossDomain: true } ), request( " https://otherdomain.com", "Cross-domain url with leading space is detected as cross-domain" ) ]; } ); ajaxTest( "jQuery.ajax() - abort", 9, function( assert ) { return { setup: addGlobalEvents( "ajaxStart ajaxStop ajaxSend ajaxError ajaxComplete", assert ), url: url( "mock.php?action=wait&wait=5" ), beforeSend: function() { assert.ok( true, "beforeSend" ); }, afterSend: function( xhr ) { assert.strictEqual( xhr.readyState, 1, "XHR readyState indicates successful dispatch" ); xhr.abort(); assert.strictEqual( xhr.readyState, 0, "XHR readyState indicates successful abortion" ); }, error: true, complete: function() { assert.ok( true, "complete" ); } }; } ); ajaxTest( "jQuery.ajax() - native abort", 2, function( assert ) { return { url: url( "mock.php?action=wait&wait=1" ), xhr: function() { var xhr = new window.XMLHttpRequest(); setTimeout( function() { xhr.abort(); }, 100 ); return xhr; }, error: function( xhr, msg ) { assert.strictEqual( msg, "error", "Native abort triggers error callback" ); }, complete: function() { assert.ok( true, "complete" ); } }; } ); ajaxTest( "jQuery.ajax() - native timeout", 2, function( assert ) { return { url: url( "mock.php?action=wait&wait=1" ), xhr: function() { var xhr = new window.XMLHttpRequest(); xhr.timeout = 1; return xhr; }, error: function( xhr, msg ) { assert.strictEqual( msg, "error", "Native timeout triggers error callback" ); }, complete: function() { assert.ok( true, "complete" ); } }; } ); ajaxTest( "jQuery.ajax() - events with context", 12, function( assert ) { var context = document.createElement( "div" ); function event( e ) { assert.equal( this, context, e.type ); } function callback( msg ) { return function() { assert.equal( this, context, "context is preserved on callback " + msg ); }; } return { setup: function() { jQuery( context ).appendTo( "#foo" ) .on( "ajaxSend", event ) .on( "ajaxComplete", event ) .on( "ajaxError", event ) .on( "ajaxSuccess", event ); }, requests: [ { url: url( "name.html" ), context: context, beforeSend: callback( "beforeSend" ), success: callback( "success" ), complete: callback( "complete" ) }, { url: url( "404.txt" ), context: context, beforeSend: callback( "beforeSend" ), error: callback( "error" ), complete: callback( "complete" ) } ] }; } ); ajaxTest( "jQuery.ajax() - events without context", 3, function( assert ) { function nocallback( msg ) { return function() { assert.equal( typeof this.url, "string", "context is settings on callback " + msg ); }; } return { url: url( "404.txt" ), beforeSend: nocallback( "beforeSend" ), error: nocallback( "error" ), complete: nocallback( "complete" ) }; } ); ajaxTest( "trac-15118 - jQuery.ajax() - function without jQuery.event", 1, function( assert ) { var holder; return { url: url( "mock.php?action=json" ), setup: function() { holder = jQuery.event; delete jQuery.event; }, complete: function() { assert.ok( true, "Call can be made without jQuery.event" ); jQuery.event = holder; }, success: true }; } ); ajaxTest( "trac-15160 - jQuery.ajax() - request manually aborted in ajaxSend", 3, function( assert ) { return { setup: function() { jQuery( document ).on( "ajaxSend", function( e, jqXHR ) { jqXHR.abort(); } ); jQuery( document ).on( "ajaxError ajaxComplete", function( e, jqXHR ) { assert.equal( jqXHR.statusText, "abort", "jqXHR.statusText equals abort on global ajaxComplete and ajaxError events" ); } ); }, url: url( "name.html" ), error: true, complete: function() { assert.ok( true, "complete" ); } }; } ); ajaxTest( "jQuery.ajax() - context modification", 1, function( assert ) { return { url: url( "name.html" ), context: {}, beforeSend: function() { this.test = "foo"; }, afterSend: function() { assert.strictEqual( this.context.test, "foo", "Make sure the original object is maintained." ); }, success: true }; } ); ajaxTest( "jQuery.ajax() - context modification through ajaxSetup", 3, function( assert ) { var obj = {}; return { setup: function() { jQuery.ajaxSetup( { context: obj } ); assert.strictEqual( jQuery.ajaxSettings.context, obj, "Make sure the context is properly set in ajaxSettings." ); }, requests: [ { url: url( "name.html" ), success: function() { assert.strictEqual( this, obj, "Make sure the original object is maintained." ); } }, { url: url( "name.html" ), context: {}, success: function() { assert.ok( this !== obj, "Make sure overriding context is possible." ); } } ] }; } ); ajaxTest( "jQuery.ajax() - disabled globals", 3, function( assert ) { return { setup: addGlobalEvents( "", assert ), global: false, url: url( "name.html" ), beforeSend: function() { assert.ok( true, "beforeSend" ); }, success: function() { assert.ok( true, "success" ); }, complete: function() { assert.ok( true, "complete" ); } }; } ); ajaxTest( "jQuery.ajax() - xml: non-namespace elements inside namespaced elements", 3, function( assert ) { return { url: url( "with_fries.xml" ), dataType: "xml", success: function( resp ) { assert.equal( jQuery( "properties", resp ).length, 1, "properties in responseXML" ); assert.equal( jQuery( "jsconf", resp ).length, 1, "jsconf in responseXML" ); assert.equal( jQuery( "thing", resp ).length, 2, "things in responseXML" ); } }; } ); ajaxTest( "jQuery.ajax() - xml: non-namespace elements inside namespaced elements (over JSONP)", 3, function( assert ) { return { url: url( "mock.php?action=xmlOverJsonp" ), dataType: "jsonp xml", success: function( resp ) { assert.equal( jQuery( "properties", resp ).length, 1, "properties in responseXML" ); assert.equal( jQuery( "jsconf", resp ).length, 1, "jsconf in responseXML" ); assert.equal( jQuery( "thing", resp ).length, 2, "things in responseXML" ); } }; } ); ajaxTest( "jQuery.ajax() - HEAD requests", 2, function( assert ) { return [ { url: url( "name.html" ), type: "HEAD", success: function( data, status, xhr ) { assert.ok( /Date/i.test( xhr.getAllResponseHeaders() ), "No Date in HEAD response" ); } }, { url: url( "name.html" ), data: { "whip_it": "good" }, type: "HEAD", success: function( data, status, xhr ) { assert.ok( /Date/i.test( xhr.getAllResponseHeaders() ), "No Date in HEAD response with data" ); } } ]; } ); ajaxTest( "jQuery.ajax() - beforeSend", 1, function( assert ) { return { url: url( "name.html" ), beforeSend: function() { this.check = true; }, success: function() { assert.ok( this.check, "check beforeSend was executed" ); } }; } ); ajaxTest( "jQuery.ajax() - beforeSend, cancel request manually", 2, function( assert ) { return { create: function() { return jQuery.ajax( { url: url( "name.html" ), beforeSend: function( xhr ) { assert.ok( true, "beforeSend got called, canceling" ); xhr.abort(); }, success: function() { assert.ok( false, "request didn't get canceled" ); }, complete: function() { assert.ok( false, "request didn't get canceled" ); }, error: function() { assert.ok( false, "request didn't get canceled" ); } } ); }, fail: function( _, reason ) { assert.strictEqual( reason, "canceled", "canceled request must fail with 'canceled' status text" ); } }; } ); ajaxTest( "jQuery.ajax() - dataType html", 5, function( assert ) { return { setup: function() { Globals.register( "testFoo" ); Globals.register( "testBar" ); }, dataType: "html", url: url( "mock.php?action=testHTML&baseURL=" + baseURL ), success: function( data ) { assert.ok( data.match( /^html text/ ), "Check content for datatype html" ); jQuery( "#ap" ).html( data ); assert.strictEqual( window.testFoo, "foo", "Check if script was evaluated for datatype html" ); assert.strictEqual( window.testBar, "bar", "Check if script src was evaluated for datatype html" ); } }; } ); ajaxTest( "jQuery.ajax() - do execute scripts if JSONP from unsuccessful responses", 1, function( assert ) { var testMsg = "Unsuccessful JSONP requests should have a JSON body"; return { dataType: "jsonp", url: url( "mock.php?action=errorWithScript" ), // error is the significant assertion error: function( xhr ) { var expected = { "status": 404, "msg": "Not Found" }; assert.deepEqual( xhr.responseJSON, expected, testMsg ); } }; } ); ajaxTest( "jQuery.ajax() - do not execute scripts from unsuccessful responses (gh-4250)", 11, function( assert ) { var globalEval = jQuery.globalEval; var failConverters = { "text script": function() { assert.ok( false, "No converter for unsuccessful response" ); } }; function request( title, options ) { var testMsg = title + ": expected file missing status"; return jQuery.extend( { beforeSend: function() { jQuery.globalEval = function() { assert.ok( false, "Should not eval" ); }; }, complete: function() { jQuery.globalEval = globalEval; }, // error is the significant assertion error: function( xhr ) { assert.strictEqual( xhr.status, 404, testMsg ); }, success: function() { assert.ok( false, "Unanticipated success" ); } }, options ); } return [ request( "HTML reply", { url: url( "404.txt" ) } ), request( "HTML reply with dataType", { dataType: "script", url: url( "404.txt" ) } ), request( "script reply", { url: url( "mock.php?action=errorWithScript&withScriptContentType" ) } ), request( "non-script reply", { url: url( "mock.php?action=errorWithScript" ) } ), request( "script reply with dataType", { dataType: "script", url: url( "mock.php?action=errorWithScript&withScriptContentType" ) } ), request( "non-script reply with dataType", { dataType: "script", url: url( "mock.php?action=errorWithScript" ) } ), request( "script reply with converter", { converters: failConverters, url: url( "mock.php?action=errorWithScript&withScriptContentType" ) } ), request( "non-script reply with converter", { converters: failConverters, url: url( "mock.php?action=errorWithScript" ) } ), request( "script reply with converter and dataType", { converters: failConverters, dataType: "script", url: url( "mock.php?action=errorWithScript&withScriptContentType" ) } ), request( "non-script reply with converter and dataType", { converters: failConverters, dataType: "script", url: url( "mock.php?action=errorWithScript" ) } ), request( "JSONP reply with dataType", { dataType: "jsonp", url: url( "mock.php?action=errorWithScript" ), beforeSend: function() { jQuery.globalEval = function( response ) { assert.ok( /"status": 404, "msg": "Not Found"/.test( response ), "Error object returned" ); }; } } ) ]; } ); ajaxTest( "jQuery.ajax() - synchronous request", 1, function( assert ) { return { url: url( "json_obj.js" ), dataType: "text", async: false, success: true, afterSend: function( xhr ) { assert.ok( /^\{ "data"/.test( xhr.responseText ), "check returned text" ); } }; } ); ajaxTest( "jQuery.ajax() - synchronous request with callbacks", 2, function( assert ) { return { url: url( "json_obj.js" ), async: false, dataType: "text", success: true, afterSend: function( xhr ) { var result; xhr.done( function( data ) { assert.ok( true, "success callback executed" ); result = data; } ); assert.ok( /^\{ "data"/.test( result ), "check returned text" ); } }; } ); QUnit.test( "jQuery.ajax(), jQuery.get[Script|JSON](), jQuery.post(), pass-through request object", function( assert ) { assert.expect( 8 ); var done = assert.async(); var target = "name.html", successCount = 0, errorCount = 0, errorEx = "", success = function() { successCount++; }; jQuery( document ).on( "ajaxError.passthru", function( e, xml ) { errorCount++; errorEx += ": " + xml.status; } ); jQuery( document ).one( "ajaxStop", function() { assert.equal( successCount, 5, "Check all ajax calls successful" ); assert.equal( errorCount, 0, "Check no ajax errors (status" + errorEx + ")" ); jQuery( document ).off( "ajaxError.passthru" ); done(); } ); Globals.register( "testBar" ); assert.ok( jQuery.get( url( target ), success ), "get" ); assert.ok( jQuery.post( url( target ), success ), "post" ); assert.ok( jQuery.getScript( url( "mock.php?action=testbar" ), success ), "script" ); assert.ok( jQuery.getJSON( url( "json_obj.js" ), success ), "json" ); assert.ok( jQuery.ajax( { url: url( target ), success: success } ), "generic" ); } ); ajaxTest( "jQuery.ajax() - cache", 28, function( assert ) { var re = /_=(.*?)(&|$)/g, rootUrl = baseURL + "text.txt"; function request( url, title ) { return { url: url, cache: false, beforeSend: function() { var parameter, tmp; // URL sanity check assert.equal( this.url.indexOf( rootUrl ), 0, "root url not mangled: " + this.url ); assert.equal( /\&.*\?/.test( this.url ), false, "parameter delimiters in order" ); while ( ( tmp = re.exec( this.url ) ) ) { assert.strictEqual( parameter, undefined, title + ": only one 'no-cache' parameter" ); parameter = tmp[ 1 ]; assert.notStrictEqual( parameter, "tobereplaced555", title + ": parameter (if it was there) was replaced" ); } return false; }, error: true }; } return [ request( rootUrl, "no query" ), request( rootUrl + "?", "empty query" ), request( rootUrl + "?pizza=true", "1 parameter" ), request( rootUrl + "?_=tobereplaced555", "_= parameter" ), request( rootUrl + "?pizza=true&_=tobereplaced555", "1 parameter and _=" ), request( rootUrl + "?_=tobereplaced555&tv=false", "_= and 1 parameter" ), request( rootUrl + "?name=David&_=tobereplaced555&washere=true", "2 parameters surrounding _=" ) ]; } ); jQuery.each( [ " - Same Domain", " - Cross Domain" ], function( crossDomain, label ) { ajaxTest( "jQuery.ajax() - JSONP - Query String (?n)" + label, 4, function( assert ) { return [ { url: baseURL + "mock.php?action=jsonp&callback=?", dataType: "jsonp", crossDomain: crossDomain, success: function( data ) { assert.ok( data.data, "JSON results returned (GET, url callback)" ); } }, { url: baseURL + "mock.php?action=jsonp&callback=??", dataType: "jsonp", crossDomain: crossDomain, success: function( data ) { assert.ok( data.data, "JSON results returned (GET, url context-free callback)" ); } }, { url: baseURL + "mock.php/???action=jsonp", dataType: "jsonp", crossDomain: crossDomain, success: function( data ) { assert.ok( data.data, "JSON results returned (GET, REST-like)" ); } }, {
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
true
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/test/unit/data.js
test/unit/data.js
QUnit.module( "data", { afterEach: moduleTeardown } ); QUnit.test( "expando", function( assert ) { assert.expect( 1 ); assert.equal( jQuery.expando !== undefined, true, "jQuery is exposing the expando" ); } ); QUnit.test( "jQuery.data & removeData, expected returns", function( assert ) { assert.expect( 4 ); var elem = document.body; assert.equal( jQuery.data( elem, "hello", "world" ), "world", "jQuery.data( elem, key, value ) returns value" ); assert.equal( jQuery.data( elem, "hello" ), "world", "jQuery.data( elem, key ) returns value" ); assert.deepEqual( jQuery.data( elem, { goodnight: "moon" } ), { goodnight: "moon" }, "jQuery.data( elem, obj ) returns obj" ); assert.equal( jQuery.removeData( elem, "hello" ), undefined, "jQuery.removeData( elem, key, value ) returns undefined" ); } ); QUnit.test( "jQuery._data & _removeData, expected returns", function( assert ) { assert.expect( 4 ); var elem = document.body; assert.equal( jQuery._data( elem, "hello", "world" ), "world", "jQuery._data( elem, key, value ) returns value" ); assert.equal( jQuery._data( elem, "hello" ), "world", "jQuery._data( elem, key ) returns value" ); assert.deepEqual( jQuery._data( elem, { goodnight: "moon" } ), { goodnight: "moon" }, "jQuery._data( elem, obj ) returns obj" ); assert.equal( jQuery._removeData( elem, "hello" ), undefined, "jQuery._removeData( elem, key, value ) returns undefined" ); } ); QUnit.test( "jQuery.hasData no side effects", function( assert ) { assert.expect( 1 ); var obj = {}; jQuery.hasData( obj ); assert.equal( Object.getOwnPropertyNames( obj ).length, 0, "No data expandos where added when calling jQuery.hasData(o)" ); } ); function dataTests( elem, assert ) { var dataObj, internalDataObj; assert.equal( jQuery.data( elem, "foo" ), undefined, "No data exists initially" ); assert.strictEqual( jQuery.hasData( elem ), false, "jQuery.hasData agrees no data exists initially" ); dataObj = jQuery.data( elem ); assert.equal( typeof dataObj, "object", "Calling data with no args gives us a data object reference" ); assert.strictEqual( jQuery.data( elem ), dataObj, "Calling jQuery.data returns the same data object when called multiple times" ); assert.strictEqual( jQuery.hasData( elem ), false, "jQuery.hasData agrees no data exists even when an empty data obj exists" ); dataObj.foo = "bar"; assert.equal( jQuery.data( elem, "foo" ), "bar", "Data is readable by jQuery.data when set directly on a returned data object" ); assert.strictEqual( jQuery.hasData( elem ), true, "jQuery.hasData agrees data exists when data exists" ); jQuery.data( elem, "foo", "baz" ); assert.equal( jQuery.data( elem, "foo" ), "baz", "Data can be changed by jQuery.data" ); assert.equal( dataObj.foo, "baz", "Changes made through jQuery.data propagate to referenced data object" ); jQuery.data( elem, "foo", undefined ); assert.equal( jQuery.data( elem, "foo" ), "baz", "Data is not unset by passing undefined to jQuery.data" ); jQuery.data( elem, "foo", null ); assert.strictEqual( jQuery.data( elem, "foo" ), null, "Setting null using jQuery.data works OK" ); jQuery.data( elem, "foo", "foo1" ); jQuery.data( elem, { "bar": "baz", "boom": "bloz" } ); assert.strictEqual( jQuery.data( elem, "foo" ), "foo1", "Passing an object extends the data object instead of replacing it" ); assert.equal( jQuery.data( elem, "boom" ), "bloz", "Extending the data object works" ); jQuery._data( elem, "foo", "foo2", true ); assert.equal( jQuery._data( elem, "foo" ), "foo2", "Setting internal data works" ); assert.equal( jQuery.data( elem, "foo" ), "foo1", "Setting internal data does not override user data" ); internalDataObj = jQuery._data( elem ); assert.ok( internalDataObj, "Internal data object exists" ); assert.notStrictEqual( dataObj, internalDataObj, "Internal data object is not the same as user data object" ); assert.strictEqual( elem.boom, undefined, "Data is never stored directly on the object" ); jQuery.removeData( elem, "foo" ); assert.strictEqual( jQuery.data( elem, "foo" ), undefined, "jQuery.removeData removes single properties" ); jQuery.removeData( elem ); assert.strictEqual( jQuery._data( elem ), internalDataObj, "jQuery.removeData does not remove internal data if it exists" ); jQuery.data( elem, "foo", "foo1" ); jQuery._data( elem, "foo", "foo2" ); assert.equal( jQuery.data( elem, "foo" ), "foo1", "(sanity check) Ensure data is set in user data object" ); assert.equal( jQuery._data( elem, "foo" ), "foo2", "(sanity check) Ensure data is set in internal data object" ); assert.strictEqual( jQuery._data( elem, jQuery.expando ), undefined, "Removing the last item in internal data destroys the internal data object" ); jQuery._data( elem, "foo", "foo2" ); assert.equal( jQuery._data( elem, "foo" ), "foo2", "(sanity check) Ensure data is set in internal data object" ); jQuery.removeData( elem, "foo" ); assert.equal( jQuery._data( elem, "foo" ), "foo2", "(sanity check) jQuery.removeData for user data does not remove internal data" ); } QUnit.test( "jQuery.data(div)", function( assert ) { assert.expect( 25 ); var div = document.createElement( "div" ); dataTests( div, assert ); } ); QUnit.test( "jQuery.data({})", function( assert ) { assert.expect( 25 ); dataTests( {}, assert ); } ); QUnit.test( "jQuery.data(window)", function( assert ) { assert.expect( 25 ); // remove bound handlers from window object to stop potential false positives caused by fix for trac-5280 in // transports/xhr.js jQuery( window ).off( "unload" ); dataTests( window, assert ); } ); QUnit.test( "jQuery.data(document)", function( assert ) { assert.expect( 25 ); dataTests( document, assert ); } ); QUnit.test( "jQuery.data(<embed>)", function( assert ) { assert.expect( 25 ); dataTests( document.createElement( "embed" ), assert ); } ); QUnit.test( "jQuery.data(object/flash)", function( assert ) { assert.expect( 25 ); var flash = document.createElement( "object" ); flash.setAttribute( "classid", "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" ); dataTests( flash, assert ); } ); // attempting to access the data of an undefined jQuery element should be undefined QUnit.test( "jQuery().data() === undefined (trac-14101)", function( assert ) { assert.expect( 2 ); assert.strictEqual( jQuery().data(), undefined ); assert.strictEqual( jQuery().data( "key" ), undefined ); } ); QUnit.test( ".data()", function( assert ) { assert.expect( 5 ); var div, dataObj, nodiv, obj; div = jQuery( "#foo" ); assert.strictEqual( div.data( "foo" ), undefined, "Make sure that missing result is undefined" ); div.data( "test", "success" ); dataObj = div.data(); assert.deepEqual( dataObj, { test: "success" }, "data() returns entire data object with expected properties" ); assert.strictEqual( div.data( "foo" ), undefined, "Make sure that missing result is still undefined" ); nodiv = jQuery( "#unfound" ); assert.equal( nodiv.data(), null, "data() on empty set returns null" ); obj = { foo: "bar" }; jQuery( obj ).data( "foo", "baz" ); dataObj = jQuery.extend( true, {}, jQuery( obj ).data() ); assert.deepEqual( dataObj, { "foo": "baz" }, "Retrieve data object from a wrapped JS object (trac-7524)" ); } ); function testDataTypes( $obj, assert ) { jQuery.each( { "null": null, "true": true, "false": false, "zero": 0, "one": 1, "empty string": "", "empty array": [], "array": [ 1 ], "empty object": {}, "object": { foo: "bar" }, "date": new Date(), "regex": /test/, "function": function() {} }, function( type, value ) { assert.strictEqual( $obj.data( "test", value ).data( "test" ), value, "Data set to " + type ); } ); } QUnit.test( "jQuery(Element).data(String, Object).data(String)", function( assert ) { assert.expect( 18 ); var parent = jQuery( "<div><div></div></div>" ), div = parent.children(); assert.strictEqual( div.data( "test" ), undefined, "No data exists initially" ); assert.strictEqual( div.data( "test", "success" ).data( "test" ), "success", "Data added" ); assert.strictEqual( div.data( "test", "overwritten" ).data( "test" ), "overwritten", "Data overwritten" ); assert.strictEqual( div.data( "test", undefined ).data( "test" ), "overwritten", ".data(key,undefined) does nothing but is chainable (trac-5571)" ); assert.strictEqual( div.data( "notexist" ), undefined, "No data exists for unset key" ); testDataTypes( div, assert ); parent.remove(); } ); QUnit.test( "jQuery(plain Object).data(String, Object).data(String)", function( assert ) { assert.expect( 16 ); // trac-3748 var $obj = jQuery( { exists: true } ); assert.strictEqual( $obj.data( "nothing" ), undefined, "Non-existent data returns undefined" ); assert.strictEqual( $obj.data( "exists" ), undefined, "Object properties are not returned as data" ); testDataTypes( $obj, assert ); // Clean up $obj.removeData(); assert.deepEqual( $obj[ 0 ], { exists: true }, "removeData does not clear the object" ); } ); QUnit.test( ".data(object) does not retain references. trac-13815", function( assert ) { assert.expect( 2 ); var $divs = jQuery( "<div></div><div></div>" ).appendTo( "#qunit-fixture" ); $divs.data( { "type": "foo" } ); $divs.eq( 0 ).data( "type", "bar" ); assert.equal( $divs.eq( 0 ).data( "type" ), "bar", "Correct updated value" ); assert.equal( $divs.eq( 1 ).data( "type" ), "foo", "Original value retained" ); } ); QUnit.test( "data-* attributes", function( assert ) { assert.expect( 46 ); var prop, i, l, metadata, elem, obj, obj2, check, num, num2, parseJSON = JSON.parse, div = jQuery( "<div>" ), child = jQuery( "<div data-myobj='old data' data-ignored=\"DOM\" data-other='test' data-foo-42='boosh'></div>" ), dummy = jQuery( "<div data-myobj='old data' data-ignored=\"DOM\" data-other='test' data-foo-42='boosh'></div>" ); assert.equal( div.data( "attr" ), undefined, "Check for non-existing data-attr attribute" ); div.attr( "data-attr", "exists" ); assert.equal( div.data( "attr" ), "exists", "Check for existing data-attr attribute" ); div.attr( "data-attr", "exists2" ); assert.equal( div.data( "attr" ), "exists", "Check that updates to data- don't update .data()" ); div.data( "attr", "internal" ).attr( "data-attr", "external" ); assert.equal( div.data( "attr" ), "internal", "Check for .data('attr') precedence (internal > external data-* attribute)" ); div.remove(); child.appendTo( "#qunit-fixture" ); assert.equal( child.data( "myobj" ), "old data", "Value accessed from data-* attribute" ); assert.equal( child.data( "foo-42" ), "boosh", "camelCasing does not affect numbers (gh-1751)" ); child.data( "myobj", "replaced" ); assert.equal( child.data( "myobj" ), "replaced", "Original data overwritten" ); child.data( "ignored", "cache" ); assert.equal( child.data( "ignored" ), "cache", "Cached data used before DOM data-* fallback" ); obj = child.data(); obj2 = dummy.data(); check = [ "myobj", "ignored", "other", "foo-42" ]; num = 0; num2 = 0; dummy.remove(); for ( i = 0, l = check.length; i < l; i++ ) { assert.ok( obj[ check[ i ] ], "Make sure data- property exists when calling data-." ); assert.ok( obj2[ check[ i ] ], "Make sure data- property exists when calling data-." ); } for ( prop in obj ) { num++; } assert.equal( num, check.length, "Make sure that the right number of properties came through." ); /* eslint-disable-next-line no-unused-vars */ for ( prop in obj2 ) { num2++; } assert.equal( num2, check.length, "Make sure that the right number of properties came through." ); child.attr( "data-other", "newvalue" ); assert.equal( child.data( "other" ), "test", "Make sure value was pulled in properly from a .data()." ); // attribute parsing i = 0; JSON.parse = function() { i++; return parseJSON.apply( this, arguments ); }; child .attr( "data-true", "true" ) .attr( "data-false", "false" ) .attr( "data-five", "5" ) .attr( "data-point", "5.5" ) .attr( "data-pointe", "5.5E3" ) .attr( "data-grande", "5.574E9" ) .attr( "data-hexadecimal", "0x42" ) .attr( "data-pointbad", "5..5" ) .attr( "data-pointbad2", "-." ) .attr( "data-bigassnum", "123456789123456789123456789" ) .attr( "data-badjson", "{123}" ) .attr( "data-badjson2", "[abc]" ) .attr( "data-notjson", " {}" ) .attr( "data-notjson2", "[] " ) .attr( "data-empty", "" ) .attr( "data-space", " " ) .attr( "data-null", "null" ) .attr( "data-string", "test" ); assert.strictEqual( child.data( "true" ), true, "Primitive true read from attribute" ); assert.strictEqual( child.data( "false" ), false, "Primitive false read from attribute" ); assert.strictEqual( child.data( "five" ), 5, "Integer read from attribute" ); assert.strictEqual( child.data( "point" ), 5.5, "Floating-point number read from attribute" ); assert.strictEqual( child.data( "pointe" ), "5.5E3", "Exponential-notation number read from attribute as string" ); assert.strictEqual( child.data( "grande" ), "5.574E9", "Big exponential-notation number read from attribute as string" ); assert.strictEqual( child.data( "hexadecimal" ), "0x42", "Hexadecimal number read from attribute as string" ); assert.strictEqual( child.data( "pointbad" ), "5..5", "Extra-point non-number read from attribute as string" ); assert.strictEqual( child.data( "pointbad2" ), "-.", "No-digit non-number read from attribute as string" ); assert.strictEqual( child.data( "bigassnum" ), "123456789123456789123456789", "Bad bigass number read from attribute as string" ); assert.strictEqual( child.data( "badjson" ), "{123}", "Bad JSON object read from attribute as string" ); assert.strictEqual( child.data( "badjson2" ), "[abc]", "Bad JSON array read from attribute as string" ); assert.strictEqual( child.data( "notjson" ), " {}", "JSON object with leading non-JSON read from attribute as string" ); assert.strictEqual( child.data( "notjson2" ), "[] ", "JSON array with trailing non-JSON read from attribute as string" ); assert.strictEqual( child.data( "empty" ), "", "Empty string read from attribute" ); assert.strictEqual( child.data( "space" ), " ", "Whitespace string read from attribute" ); assert.strictEqual( child.data( "null" ), null, "Primitive null read from attribute" ); assert.strictEqual( child.data( "string" ), "test", "Typical string read from attribute" ); assert.equal( i, 2, "Correct number of JSON parse attempts when reading from attributes" ); JSON.parse = parseJSON; child.remove(); // tests from metadata plugin function testData( index, elem ) { switch ( index ) { case 0: assert.equal( jQuery( elem ).data( "foo" ), "bar", "Check foo property" ); assert.equal( jQuery( elem ).data( "bar" ), "baz", "Check baz property" ); break; case 1: assert.equal( jQuery( elem ).data( "test" ), "bar", "Check test property" ); assert.equal( jQuery( elem ).data( "bar" ), "baz", "Check bar property" ); break; case 2: assert.equal( jQuery( elem ).data( "zoooo" ), "bar", "Check zoooo property" ); assert.deepEqual( jQuery( elem ).data( "bar" ), { "test": "baz" }, "Check bar property" ); break; case 3: assert.equal( jQuery( elem ).data( "number" ), true, "Check number property" ); assert.deepEqual( jQuery( elem ).data( "stuff" ), [ 2, 8 ], "Check stuff property" ); break; default: assert.ok( false, [ "Assertion failed on index ", index, ", with data" ].join( "" ) ); } } metadata = "<ol><li class='test test2' data-foo='bar' data-bar='baz' data-arr='[1,2]'>Some stuff</li><li class='test test2' data-test='bar' data-bar='baz'>Some stuff</li><li class='test test2' data-zoooo='bar' data-bar='{\"test\":\"baz\"}'>Some stuff</li><li class='test test2' data-number=true data-stuff='[2,8]'>Some stuff</li></ol>"; elem = jQuery( metadata ).appendTo( "#qunit-fixture" ); elem.find( "li" ).each( testData ); elem.remove(); } ); QUnit.test( ".data(Object)", function( assert ) { assert.expect( 4 ); var obj, jqobj, div = jQuery( "<div></div>" ); div.data( { "test": "in", "test2": "in2" } ); assert.equal( div.data( "test" ), "in", "Verify setting an object in data" ); assert.equal( div.data( "test2" ), "in2", "Verify setting an object in data" ); obj = { test: "unset" }; jqobj = jQuery( obj ); jqobj.data( "test", "unset" ); jqobj.data( { "test": "in", "test2": "in2" } ); assert.equal( jQuery.data( obj ).test, "in", "Verify setting an object on an object extends the data object" ); assert.equal( obj.test2, undefined, "Verify setting an object on an object does not extend the object" ); // manually clean up detached elements div.remove(); } ); QUnit.test( "jQuery.removeData", function( assert ) { assert.expect( 10 ); var obj, div = jQuery( "#foo" )[ 0 ]; jQuery.data( div, "test", "testing" ); jQuery.removeData( div, "test" ); assert.equal( jQuery.data( div, "test" ), undefined, "Check removal of data" ); jQuery.data( div, "test2", "testing" ); jQuery.removeData( div ); assert.ok( !jQuery.data( div, "test2" ), "Make sure that the data property no longer exists." ); assert.ok( !div[ jQuery.expando ], "Make sure the expando no longer exists, as well." ); jQuery.data( div, { test3: "testing", test4: "testing" } ); jQuery.removeData( div, "test3 test4" ); assert.ok( !jQuery.data( div, "test3" ) || jQuery.data( div, "test4" ), "Multiple delete with spaces." ); jQuery.data( div, { test3: "testing", test4: "testing" } ); jQuery.removeData( div, [ "test3", "test4" ] ); assert.ok( !jQuery.data( div, "test3" ) || jQuery.data( div, "test4" ), "Multiple delete by array." ); jQuery.data( div, { "test3 test4": "testing", "test3": "testing" } ); jQuery.removeData( div, "test3 test4" ); assert.ok( !jQuery.data( div, "test3 test4" ), "Multiple delete with spaces deleted key with exact name" ); assert.ok( jQuery.data( div, "test3" ), "Left the partial matched key alone" ); obj = {}; jQuery.data( obj, "test", "testing" ); assert.equal( jQuery( obj ).data( "test" ), "testing", "verify data on plain object" ); jQuery.removeData( obj, "test" ); assert.equal( jQuery.data( obj, "test" ), undefined, "Check removal of data on plain object" ); jQuery.data( window, "BAD", true ); jQuery.removeData( window, "BAD" ); assert.ok( !jQuery.data( window, "BAD" ), "Make sure that the value was not still set." ); } ); QUnit.test( ".removeData()", function( assert ) { assert.expect( 6 ); var div = jQuery( "#foo" ); div.data( "test", "testing" ); div.removeData( "test" ); assert.equal( div.data( "test" ), undefined, "Check removal of data" ); div.data( "test", "testing" ); div.data( "test.foo", "testing2" ); div.removeData( "test.bar" ); assert.equal( div.data( "test.foo" ), "testing2", "Make sure data is intact" ); assert.equal( div.data( "test" ), "testing", "Make sure data is intact" ); div.removeData( "test" ); assert.equal( div.data( "test.foo" ), "testing2", "Make sure data is intact" ); assert.equal( div.data( "test" ), undefined, "Make sure data is intact" ); div.removeData( "test.foo" ); assert.equal( div.data( "test.foo" ), undefined, "Make sure data is intact" ); } ); QUnit.test( "JSON serialization (trac-8108)", function( assert ) { assert.expect( 1 ); var obj = { "foo": "bar" }; jQuery.data( obj, "hidden", true ); assert.equal( JSON.stringify( obj ), "{\"foo\":\"bar\"}", "Expando is hidden from JSON.stringify" ); } ); QUnit.test( ".data should follow html5 specification regarding camel casing", function( assert ) { assert.expect( 12 ); var div = jQuery( "<div id='myObject' data-w-t-f='ftw' data-big-a-little-a='bouncing-b' data-foo='a' data-foo-bar='b' data-foo-bar-baz='c'></div>" ) .prependTo( "body" ); assert.equal( div.data().wTF, "ftw", "Verify single letter data-* key" ); assert.equal( div.data().bigALittleA, "bouncing-b", "Verify single letter mixed data-* key" ); assert.equal( div.data().foo, "a", "Verify single word data-* key" ); assert.equal( div.data().fooBar, "b", "Verify multiple word data-* key" ); assert.equal( div.data().fooBarBaz, "c", "Verify multiple word data-* key" ); assert.equal( div.data( "foo" ), "a", "Verify single word data-* key" ); assert.equal( div.data( "fooBar" ), "b", "Verify multiple word data-* key" ); assert.equal( div.data( "fooBarBaz" ), "c", "Verify multiple word data-* key" ); div.data( "foo-bar", "d" ); assert.equal( div.data( "fooBar" ), "d", "Verify updated data-* key" ); assert.equal( div.data( "foo-bar" ), "d", "Verify updated data-* key" ); assert.equal( div.data( "fooBar" ), "d", "Verify updated data-* key (fooBar)" ); assert.equal( div.data( "foo-bar" ), "d", "Verify updated data-* key (foo-bar)" ); div.remove(); } ); QUnit.test( ".data should not miss preset data-* w/ hyphenated property names", function( assert ) { assert.expect( 2 ); var div = jQuery( "<div></div>", { id: "hyphened" } ).appendTo( "#qunit-fixture" ), test = { "camelBar": "camelBar", "hyphen-foo": "hyphen-foo" }; div.data( test ); jQuery.each( test, function( i, k ) { assert.equal( div.data( k ), k, "data with property '" + k + "' was correctly found" ); } ); } ); QUnit.test( "jQuery.data should not miss data-* w/ hyphenated property names trac-14047", function( assert ) { assert.expect( 1 ); var div = jQuery( "<div></div>" ); div.data( "foo-bar", "baz" ); assert.equal( jQuery.data( div[ 0 ], "foo-bar" ), "baz", "data with property 'foo-bar' was correctly found" ); } ); QUnit.test( ".data should not miss attr() set data-* with hyphenated property names", function( assert ) { assert.expect( 2 ); var a, b; a = jQuery( "<div></div>" ).appendTo( "#qunit-fixture" ); a.attr( "data-long-param", "test" ); a.data( "long-param", { a: 2 } ); assert.deepEqual( a.data( "long-param" ), { a: 2 }, "data with property long-param was found, 1" ); b = jQuery( "<div></div>" ).appendTo( "#qunit-fixture" ); b.attr( "data-long-param", "test" ); b.data( "long-param" ); b.data( "long-param", { a: 2 } ); assert.deepEqual( b.data( "long-param" ), { a: 2 }, "data with property long-param was found, 2" ); } ); QUnit.test( ".data always sets data with the camelCased key (gh-2257)", function( assert ) { assert.expect( 18 ); var div = jQuery( "<div>" ).appendTo( "#qunit-fixture" ), datas = { "non-empty": { key: "nonEmpty", value: "a string" }, "empty-string": { key: "emptyString", value: "" }, "one-value": { key: "oneValue", value: 1 }, "zero-value": { key: "zeroValue", value: 0 }, "an-array": { key: "anArray", value: [] }, "an-object": { key: "anObject", value: {} }, "bool-true": { key: "boolTrue", value: true }, "bool-false": { key: "boolFalse", value: false }, "some-json": { key: "someJson", value: "{ \"foo\": \"bar\" }" } }; jQuery.each( datas, function( key, val ) { div.data( key, val.value ); var allData = div.data(); assert.equal( allData[ key ], undefined, ".data does not store with hyphenated keys" ); assert.equal( allData[ val.key ], val.value, ".data stores the camelCased key" ); } ); } ); QUnit.test( ".data should not strip more than one hyphen when camelCasing (gh-2070)", function( assert ) { assert.expect( 3 ); var div = jQuery( "<div data-nested-single='single' data-nested--double='double' data-nested---triple='triple'></div>" ).appendTo( "#qunit-fixture" ), allData = div.data(); assert.equal( allData.nestedSingle, "single", "Key is correctly camelCased" ); assert.equal( allData[ "nested-Double" ], "double", "Key with double hyphens is correctly camelCased" ); assert.equal( allData[ "nested--Triple" ], "triple", "Key with triple hyphens is correctly camelCased" ); } ); QUnit.test( ".data supports interoperable hyphenated/camelCase get/set of properties with arbitrary non-null|NaN|undefined values", function( assert ) { var div = jQuery( "<div></div>", { id: "hyphened" } ).appendTo( "#qunit-fixture" ), datas = { "non-empty": { key: "nonEmpty", value: "a string" }, "empty-string": { key: "emptyString", value: "" }, "one-value": { key: "oneValue", value: 1 }, "zero-value": { key: "zeroValue", value: 0 }, "an-array": { key: "anArray", value: [] }, "an-object": { key: "anObject", value: {} }, "bool-true": { key: "boolTrue", value: true }, "bool-false": { key: "boolFalse", value: false }, "some-json": { key: "someJson", value: "{ \"foo\": \"bar\" }" }, "num-1-middle": { key: "num-1Middle", value: true }, "num-end-2": { key: "numEnd-2", value: true }, "2-num-start": { key: "2NumStart", value: true }, // Vendor prefixes are not treated in a special way. "-ms-foo": { key: "MsFoo", value: true }, "-moz-foo": { key: "MozFoo", value: true }, "-webkit-foo": { key: "WebkitFoo", value: true }, "-fake-foo": { key: "FakeFoo", value: true } }; assert.expect( 32 ); jQuery.each( datas, function( key, val ) { div.data( key, val.value ); assert.deepEqual( div.data( key ), val.value, "get: " + key ); assert.deepEqual( div.data( val.key ), val.value, "get: " + val.key ); } ); } ); QUnit.test( ".data supports interoperable removal of hyphenated/camelCase properties", function( assert ) { var div = jQuery( "<div></div>", { id: "hyphened" } ).appendTo( "#qunit-fixture" ), rdashAlpha = /-([a-z])/g, datas = { "non-empty": "a string", "empty-string": "", "one-value": 1, "zero-value": 0, "an-array": [], "an-object": {}, "bool-true": true, "bool-false": false, "some-json": "{ \"foo\": \"bar\" }" }; assert.expect( 27 ); function fcamelCase( all, letter ) { return letter.toUpperCase(); } jQuery.each( datas, function( key, val ) { div.data( key, val ); assert.deepEqual( div.data( key ), val, "get: " + key ); assert.deepEqual( div.data( key.replace( rdashAlpha, fcamelCase ) ), val, "get: " + key.replace( rdashAlpha, fcamelCase ) ); div.removeData( key ); assert.equal( div.data( key ), undefined, "get: " + key ); } ); } ); QUnit.test( ".data supports interoperable removal of properties SET TWICE trac-13850", function( assert ) { var div = jQuery( "<div>" ).appendTo( "#qunit-fixture" ), datas = { "non-empty": "a string", "empty-string": "", "one-value": 1, "zero-value": 0, "an-array": [], "an-object": {}, "bool-true": true, "bool-false": false, "some-json": "{ \"foo\": \"bar\" }" }; assert.expect( 9 ); jQuery.each( datas, function( key, val ) { div.data( key, val ); div.data( key, val ); div.removeData( key ); assert.equal( div.data( key ), undefined, "removal: " + key ); } ); } ); QUnit.test( ".removeData supports removal of hyphenated properties via array (trac-12786, gh-2257)", function( assert ) { assert.expect( 4 ); var div, plain, compare; div = jQuery( "<div>" ).appendTo( "#qunit-fixture" ); plain = jQuery( {} ); // Properties should always be camelCased compare = { // From batch assignment .data({ "a-a": 1 }) "aA": 1, // From property, value assignment .data( "b-b", 1 ) "bB": 1 }; // Mixed assignment div.data( { "a-a": 1 } ).data( "b-b", 1 ); plain.data( { "a-a": 1 } ).data( "b-b", 1 ); assert.deepEqual( div.data(), compare, "Data appears as expected. (div)" ); assert.deepEqual( plain.data(), compare, "Data appears as expected. (plain)" ); div.removeData( [ "a-a", "b-b" ] ); plain.removeData( [ "a-a", "b-b" ] ); assert.deepEqual( div.data(), {}, "Data is empty. (div)" ); assert.deepEqual( plain.data(), {}, "Data is empty. (plain)" ); } ); // Test originally by Moschel QUnit.test( ".removeData should not throw exceptions. (trac-10080)", function( assert ) { var done = assert.async(); assert.expect( 1 ); var frame = jQuery( "#loadediframe" ); jQuery( frame[ 0 ].contentWindow ).on( "unload", function() { assert.ok( true, "called unload" ); done(); } ); // change the url to trigger unload frame.attr( "src", baseURL + "iframe.html?param=true" ); } ); QUnit.test( ".data only checks element attributes once. trac-8909", function( assert ) { assert.expect( 2 ); var testing = { "test": "testing", "test2": "testing" }, element = jQuery( "<div data-test='testing'>" ), node = element[ 0 ]; // set an attribute using attr to ensure it node.setAttribute( "data-test2", "testing" ); assert.deepEqual( element.data(), testing, "Sanity Check" ); node.setAttribute( "data-test3", "testing" ); assert.deepEqual( element.data(), testing, "The data didn't change even though the data-* attrs did" ); // clean up data cache element.remove(); } ); QUnit.test( "data-* with JSON value can have newlines", function( assert ) { assert.expect( 1 ); var x = jQuery( "<div data-some='{\n\"foo\":\n\t\"bar\"\n}'></div>" ); assert.equal( x.data( "some" ).foo, "bar", "got a JSON data- attribute with spaces" ); x.remove(); } ); QUnit.test( ".data doesn't throw when calling selection is empty. trac-13551", function( assert ) { assert.expect( 1 ); try { jQuery( null ).data( "prop" ); assert.ok( true, "jQuery(null).data('prop') does not throw" ); } catch ( e ) { assert.ok( false, e.message ); } } ); QUnit.test( "acceptData", function( assert ) { assert.expect( 10 ); var flash, pdf, form; assert.equal( jQuery( document ).data( "test", 42 ).data( "test" ), 42, "document" ); assert.equal( jQuery( document.documentElement ).data( "test", 42 ).data( "test" ), 42, "documentElement" ); assert.equal( jQuery( {} ).data( "test", 42 ).data( "test" ), 42, "object" ); assert.equal( jQuery( document.createElement( "embed" ) ).data( "test", 42 ).data( "test" ), 42, "embed" ); flash = document.createElement( "object" ); flash.setAttribute( "classid", "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" ); assert.equal( jQuery( flash ).data( "test", 42 ).data( "test" ), 42, "flash" ); pdf = document.createElement( "object" ); pdf.setAttribute( "classid", "clsid:CA8A9780-280D-11CF-A24D-444553540000" ); assert.equal( jQuery( pdf ).data( "test", 42 ).data( "test" ), 42, "pdf" ); assert.strictEqual( jQuery( document.createComment( "" ) ).data( "test", 42 ).data( "test" ), undefined, "comment" ); assert.strictEqual( jQuery( document.createTextNode( "" ) ).data( "test", 42 ).data( "test" ), undefined, "text" ); assert.strictEqual( jQuery( document.createDocumentFragment() ).data( "test", 42 ).data( "test" ), undefined, "documentFragment" ); form = jQuery( "#form" ).append( "<input id='nodeType'/><input id='nodeName'/>" )[ 0 ]; assert.equal( jQuery( form ) .data( "test", 42 ).data( "test" ), 42, "form with aliased DOM properties" ); } ); QUnit.test( "Check proper data removal of non-element descendants nodes (trac-8335)", function( assert ) { assert.expect( 1 ); var div = jQuery( "<div>text</div>" ), text = div.contents(); text.data( "test", "test" ); // This should be a noop. div.remove(); assert.ok( !text.data( "test" ), "Be sure data is not stored in non-element" ); } ); testIframe( "enumerate data attrs on body (trac-14894)", "data/dataAttrs.html", function( assert, jQuery, window, document, result ) { assert.expect( 1 ); assert.equal( result, "ok", "enumeration of data- attrs on body" ); } ); QUnit.test( "Check that the expando is removed when there's no more data", function( assert ) { assert.expect( 2 ); var key, div = jQuery( "<div></div>" ); div.data( "some", "data" ); assert.equal( div.data( "some" ), "data", "Data is added" ); div.removeData( "some" ); // Make sure the expando is gone for ( key in div[ 0 ] ) { if ( /^jQuery/.test( key ) ) { assert.strictEqual( div[ 0 ][ key ], undefined, "Expando was not removed when there was no more data" ); } } } ); QUnit.test( "Check that the expando is removed when there's no more data on non-nodes", function( assert ) { assert.expect( 1 ); var key, obj = jQuery( { key: 42 } ); obj.data( "some", "data" ); assert.equal( obj.data( "some" ), "data", "Data is added" ); obj.removeData( "some" ); // Make sure the expando is gone for ( key in obj[ 0 ] ) { if ( /^jQuery/.test( key ) ) { assert.ok( false, "Expando was not removed when there was no more data" ); } } } ); QUnit.test( ".data(prop) does not create expando", function( assert ) { assert.expect( 1 ); var key, div = jQuery( "<div></div>" ); div.data( "foo" ); assert.equal( jQuery.hasData( div[ 0 ] ), false, "No data exists after access" ); // Make sure no expando has been added
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
true
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/test/unit/attributes.js
test/unit/attributes.js
QUnit.module( "attributes", { afterEach: moduleTeardown } ); function bareObj( value ) { return value; } function functionReturningObj( value ) { return function() { return value; }; } function arrayFromString( value ) { return value ? value.split( " " ) : []; } /* ======== local reference ======= bareObj and functionReturningObj can be used to test passing functions to setters See testVal below for an example bareObj( value ); This function returns whatever value is passed in functionReturningObj( value ); Returns a function that returns the value */ QUnit.test( "jQuery.propFix integrity test", function( assert ) { assert.expect( 1 ); // This must be maintained and equal jQuery.attrFix when appropriate // Ensure that accidental or erroneous property // overwrites don't occur // This is simply for better code coverage and future proofing. var props = { "tabindex": "tabIndex", "readonly": "readOnly", "for": "htmlFor", "class": "className", "maxlength": "maxLength", "cellspacing": "cellSpacing", "cellpadding": "cellPadding", "rowspan": "rowSpan", "colspan": "colSpan", "usemap": "useMap", "frameborder": "frameBorder", "contenteditable": "contentEditable" }; assert.deepEqual( props, jQuery.propFix, "jQuery.propFix passes integrity check" ); } ); QUnit.test( "attr(String)", function( assert ) { assert.expect( 50 ); var extras, body, $body, select, optgroup, option, $img, styleElem, $button, $form, $a; assert.equal( jQuery( "#text1" ).attr( "type" ), "text", "Check for type attribute" ); assert.equal( jQuery( "#radio1" ).attr( "type" ), "radio", "Check for type attribute" ); assert.equal( jQuery( "#check1" ).attr( "type" ), "checkbox", "Check for type attribute" ); assert.equal( jQuery( "#john1" ).attr( "rel" ), "bookmark", "Check for rel attribute" ); assert.equal( jQuery( "#google" ).attr( "title" ), "Google!", "Check for title attribute" ); assert.equal( jQuery( "#mozilla" ).attr( "hreflang" ), "en", "Check for hreflang attribute" ); assert.equal( jQuery( "#en" ).attr( "lang" ), "en", "Check for lang attribute" ); assert.equal( jQuery( "#timmy" ).attr( "class" ), "blog link", "Check for class attribute" ); assert.equal( jQuery( "#name" ).attr( "name" ), "name", "Check for name attribute" ); assert.equal( jQuery( "#text1" ).attr( "name" ), "action", "Check for name attribute" ); assert.ok( jQuery( "#form" ).attr( "action" ).indexOf( "formaction" ) >= 0, "Check for action attribute" ); assert.equal( jQuery( "#text1" ).attr( "value", "t" ).attr( "value" ), "t", "Check setting the value attribute" ); assert.equal( jQuery( "#text1" ).attr( "value", "" ).attr( "value" ), "", "Check setting the value attribute to empty string" ); assert.equal( jQuery( "<div value='t'></div>" ).attr( "value" ), "t", "Check setting custom attr named 'value' on a div" ); assert.equal( jQuery( "#form" ).attr( "blah", "blah" ).attr( "blah" ), "blah", "Set non-existent attribute on a form" ); assert.equal( jQuery( "#foo" ).attr( "height" ), undefined, "Non existent height attribute should return undefined" ); // [7472] & [3113] (form contains an input with name="action" or name="id") extras = jQuery( "<input id='id' name='id' /><input id='name' name='name' /><input id='target' name='target' />" ).appendTo( "#testForm" ); assert.equal( jQuery( "#form" ).attr( "action", "newformaction" ).attr( "action" ), "newformaction", "Check that action attribute was changed" ); assert.equal( jQuery( "#testForm" ).attr( "target" ), undefined, "Retrieving target does not equal the input with name=target" ); assert.equal( jQuery( "#testForm" ).attr( "target", "newTarget" ).attr( "target" ), "newTarget", "Set target successfully on a form" ); assert.equal( jQuery( "#testForm" ).removeAttr( "id" ).attr( "id" ), undefined, "Retrieving id does not equal the input with name=id after id is removed [trac-7472]" ); // Bug trac-3685 (form contains input with name="name") assert.equal( jQuery( "#testForm" ).attr( "name" ), undefined, "Retrieving name does not retrieve input with name=name" ); extras.remove(); assert.equal( jQuery( "#text1" ).attr( "maxlength" ), "30", "Check for maxlength attribute" ); assert.equal( jQuery( "#text1" ).attr( "maxLength" ), "30", "Check for maxLength attribute" ); assert.equal( jQuery( "#area1" ).attr( "maxLength" ), "30", "Check for maxLength attribute" ); // using innerHTML in IE causes href attribute to be serialized to the full path jQuery( "<a></a>" ).attr( { "id": "tAnchor5", "href": "#5" } ).appendTo( "#qunit-fixture" ); assert.equal( jQuery( "#tAnchor5" ).attr( "href" ), "#5", "Check for non-absolute href (an anchor)" ); jQuery( "<a id='tAnchor6' href='#5'></a>" ).appendTo( "#qunit-fixture" ); assert.equal( jQuery( "#tAnchor5" ).prop( "href" ), jQuery( "#tAnchor6" ).prop( "href" ), "Check for absolute href prop on an anchor" ); jQuery( "<script type='jquery/test' src='#5' id='scriptSrc'></script>" ).appendTo( "#qunit-fixture" ); assert.equal( jQuery( "#tAnchor5" ).prop( "href" ), jQuery( "#scriptSrc" ).prop( "src" ), "Check for absolute src prop on a script" ); // list attribute is readonly by default in browsers that support it jQuery( "#list-test" ).attr( "list", "datalist" ); assert.equal( jQuery( "#list-test" ).attr( "list" ), "datalist", "Check setting list attribute" ); // Related to [5574] and [5683] body = document.body; $body = jQuery( body ); assert.strictEqual( $body.attr( "foo" ), undefined, "Make sure that a non existent attribute returns undefined" ); body.setAttribute( "foo", "baz" ); assert.equal( $body.attr( "foo" ), "baz", "Make sure the dom attribute is retrieved when no expando is found" ); $body.attr( "foo", "cool" ); assert.equal( $body.attr( "foo" ), "cool", "Make sure that setting works well when both expando and dom attribute are available" ); body.removeAttribute( "foo" ); // Cleanup select = document.createElement( "select" ); optgroup = document.createElement( "optgroup" ); option = document.createElement( "option" ); optgroup.appendChild( option ); select.appendChild( optgroup ); assert.equal( jQuery( option ).prop( "selected" ), true, "Make sure that a single option is selected, even when in an optgroup." ); $img = jQuery( "<img style='display:none' width='215' height='53' src='" + baseURL + "1x1.jpg'/>" ).appendTo( "body" ); assert.equal( $img.attr( "width" ), "215", "Retrieve width attribute on an element with display:none." ); assert.equal( $img.attr( "height" ), "53", "Retrieve height attribute on an element with display:none." ); // Check for style support styleElem = jQuery( "<div></div>" ).appendTo( "#qunit-fixture" ).css( { background: "url(UPPERlower.gif)" } ); assert.ok( !!~styleElem.attr( "style" ).indexOf( "UPPERlower.gif" ), "Check style attribute getter" ); assert.ok( !!~styleElem.attr( "style", "position:absolute;" ).attr( "style" ).indexOf( "absolute" ), "Check style setter" ); // Check value on button element (trac-1954) $button = jQuery( "<button>text</button>" ).insertAfter( "#button" ); assert.strictEqual( $button.attr( "value" ), undefined, "Absence of value attribute on a button" ); assert.equal( $button.attr( "value", "foobar" ).attr( "value" ), "foobar", "Value attribute on a button does not return innerHTML" ); assert.equal( $button.attr( "value", "baz" ).html(), "text", "Setting the value attribute does not change innerHTML" ); // Attributes with a colon on a table element (trac-1591) assert.equal( jQuery( "#table" ).attr( "test:attrib" ), undefined, "Retrieving a non-existent attribute on a table with a colon does not throw an error." ); assert.equal( jQuery( "#table" ).attr( "test:attrib", "foobar" ).attr( "test:attrib" ), "foobar", "Setting an attribute on a table with a colon does not throw an error." ); $form = jQuery( "<form class='something'></form>" ).appendTo( "#qunit-fixture" ); assert.equal( $form.attr( "class" ), "something", "Retrieve the class attribute on a form." ); $a = jQuery( "<a href='#' onclick='something()'>Click</a>" ).appendTo( "#qunit-fixture" ); assert.equal( $a.attr( "onclick" ), "something()", "Retrieve ^on attribute without anonymous function wrapper." ); assert.ok( jQuery( "<div></div>" ).attr( "doesntexist" ) === undefined, "Make sure undefined is returned when no attribute is found." ); assert.ok( jQuery( "<div></div>" ).attr( "title" ) === undefined, "Make sure undefined is returned when no attribute is found." ); assert.equal( jQuery( "<div></div>" ).attr( "title", "something" ).attr( "title" ), "something", "Set the title attribute." ); assert.ok( jQuery().attr( "doesntexist" ) === undefined, "Make sure undefined is returned when no element is there." ); assert.equal( jQuery( "<div></div>" ).attr( "value" ), undefined, "An unset value on a div returns undefined." ); assert.strictEqual( jQuery( "<select><option value='property'></option></select>" ).attr( "value" ), undefined, "An unset value on a select returns undefined." ); $form = jQuery( "#form" ).attr( "enctype", "multipart/form-data" ); assert.equal( $form.prop( "enctype" ), "multipart/form-data", "Set the enctype of a form (encoding in IE6/7 trac-6743)" ); } ); QUnit.test( "attr(String) on cloned elements, trac-9646", function( assert ) { assert.expect( 4 ); var div, input = jQuery( "<input name='tester' />" ); input.attr( "name" ); assert.strictEqual( input.clone( true ).attr( "name", "test" )[ 0 ].name, "test", "Name attribute should be changed on cloned element" ); div = jQuery( "<div id='tester'></div>" ); div.attr( "id" ); assert.strictEqual( div.clone( true ).attr( "id", "test" )[ 0 ].id, "test", "Id attribute should be changed on cloned element" ); input = jQuery( "<input value='tester' />" ); input.attr( "value" ); assert.strictEqual( input.clone( true ).attr( "value", "test" )[ 0 ].value, "test", "Value attribute should be changed on cloned element" ); assert.strictEqual( input.clone( true ).attr( "value", 42 )[ 0 ].value, "42", "Value attribute should be changed on cloned element" ); } ); QUnit.test( "attr(String) in XML Files", function( assert ) { assert.expect( 3 ); var xml = createDashboardXML(); assert.equal( jQuery( "locations", xml ).attr( "class" ), "foo", "Check class attribute in XML document" ); assert.equal( jQuery( "location", xml ).attr( "for" ), "bar", "Check for attribute in XML document" ); assert.equal( jQuery( "location", xml ).attr( "checked" ), "different", "Check that hooks are not attached in XML document" ); } ); QUnit.test( "attr(String, Function)", function( assert ) { assert.expect( 2 ); assert.equal( jQuery( "#text1" ).attr( "value", function() { return this.id; } ).attr( "value" ), "text1", "Set value from id" ); assert.equal( jQuery( "#text1" ).attr( "title", function( i ) { return i; } ).attr( "title" ), "0", "Set value with an index" ); } ); QUnit.test( "attr(Hash)", function( assert ) { assert.expect( 3 ); var pass = true; jQuery( "#qunit-fixture div" ).attr( { "foo": "baz", "zoo": "ping" } ).each( function() { if ( this.getAttribute( "foo" ) !== "baz" && this.getAttribute( "zoo" ) !== "ping" ) { pass = false; } } ); assert.ok( pass, "Set Multiple Attributes" ); assert.equal( jQuery( "#text1" ).attr( { "value": function() { return this.id; } } ).attr( "value" ), "text1", "Set attribute to computed value #1" ); assert.equal( jQuery( "#text1" ).attr( { "title": function( i ) { return i; } } ).attr( "title" ), "0", "Set attribute to computed value #2" ); } ); QUnit.test( "attr(String, Object)", function( assert ) { assert.expect( 71 ); var $input, $text, $details, attributeNode, commentNode, textNode, obj, table, td, j, check, thrown, button, $radio, $radios, $svg, div = jQuery( "#qunit-fixture div" ).attr( "foo", "bar" ), i = 0, fail = false; for ( ; i < div.length; i++ ) { if ( div[ i ].getAttribute( "foo" ) !== "bar" ) { fail = i; break; } } assert.equal( fail, false, "Set Attribute, the #" + fail + " element didn't get the attribute 'foo'" ); assert.ok( jQuery( "#foo" ).attr( { "width": null } ), "Try to set an attribute to nothing" ); jQuery( "#name" ).attr( "name", "something" ); assert.equal( jQuery( "#name" ).attr( "name" ), "something", "Set name attribute" ); jQuery( "#name" ).attr( "name", null ); assert.equal( jQuery( "#name" ).attr( "name" ), undefined, "Remove name attribute" ); $input = jQuery( "<input>", { name: "something", id: "specified" } ); assert.equal( $input.attr( "name" ), "something", "Check element creation gets/sets the name attribute." ); assert.equal( $input.attr( "id" ), "specified", "Check element creation gets/sets the id attribute." ); // As of fixing trac-11115, we only guarantee boolean property update for checked and selected $input = jQuery( "<input type='checkbox'/>" ).attr( "checked", true ); assert.equal( $input.prop( "checked" ), true, "Setting checked updates property (verified by .prop)" ); assert.equal( $input[ 0 ].checked, true, "Setting checked updates property (verified by native property)" ); $input = jQuery( "<option></option>" ).attr( "selected", true ); assert.equal( $input.prop( "selected" ), true, "Setting selected updates property (verified by .prop)" ); assert.equal( $input[ 0 ].selected, true, "Setting selected updates property (verified by native property)" ); $input = jQuery( "#check2" ); $input.prop( "checked", true ).prop( "checked", false ).attr( "checked", "checked" ); assert.equal( $input.attr( "checked" ), "checked", "Set checked (verified by .attr)" ); $input.prop( "checked", false ).prop( "checked", true ).attr( "checked", false ); assert.equal( $input.attr( "checked" ), undefined, "Remove checked (verified by .attr)" ); $input = jQuery( "#text1" ).prop( "readOnly", true ).prop( "readOnly", false ).attr( "readonly", "readonly" ); assert.equal( $input.attr( "readonly" ), "readonly", "Set readonly (verified by .attr)" ); $input.prop( "readOnly", false ).prop( "readOnly", true ).attr( "readonly", false ); assert.equal( $input.attr( "readonly" ), undefined, "Remove readonly (verified by .attr)" ); $input = jQuery( "#check2" ).attr( "checked", true ).attr( "checked", false ).prop( "checked", true ); assert.equal( $input[ 0 ].checked, true, "Set checked property (verified by native property)" ); assert.equal( $input.prop( "checked" ), true, "Set checked property (verified by .prop)" ); assert.equal( $input.attr( "checked" ), undefined, "Setting checked property doesn't affect checked attribute" ); $input.attr( "checked", false ).attr( "checked", "checked" ).prop( "checked", false ); assert.equal( $input[ 0 ].checked, false, "Clear checked property (verified by native property)" ); assert.equal( $input.prop( "checked" ), false, "Clear checked property (verified by .prop)" ); assert.equal( $input.attr( "checked" ), "checked", "Clearing checked property doesn't affect checked attribute" ); $input = jQuery( "#check2" ).attr( "checked", false ).attr( "checked", "checked" ); assert.equal( $input.attr( "checked" ), "checked", "Set checked to 'checked' (verified by .attr)" ); $radios = jQuery( "#checkedtest" ).find( "input[type='radio']" ); $radios.eq( 1 ).trigger( "click" ); assert.equal( $radios.eq( 1 ).prop( "checked" ), true, "Second radio was checked when clicked" ); assert.equal( $radios.eq( 0 ).attr( "checked" ), "checked", "First radio is still [checked]" ); $input = jQuery( "#text1" ).attr( "readonly", false ).prop( "readOnly", true ); assert.equal( $input[ 0 ].readOnly, true, "Set readonly property (verified by native property)" ); assert.equal( $input.prop( "readOnly" ), true, "Set readonly property (verified by .prop)" ); $input.attr( "readonly", true ).prop( "readOnly", false ); assert.equal( $input[ 0 ].readOnly, false, "Clear readonly property (verified by native property)" ); assert.equal( $input.prop( "readOnly" ), false, "Clear readonly property (verified by .prop)" ); $input = jQuery( "#name" ).attr( "maxlength", "5" ); assert.equal( $input[ 0 ].maxLength, 5, "Set maxlength (verified by native property)" ); $input.attr( "maxLength", "10" ); assert.equal( $input[ 0 ].maxLength, 10, "Set maxlength (verified by native property)" ); // HTML5 boolean attributes $text = jQuery( "#text1" ).attr( { "autofocus": "autofocus", "required": "required" } ); assert.equal( $text.attr( "autofocus" ), "autofocus", "Reading autofocus attribute yields 'autofocus'" ); assert.equal( $text.attr( "autofocus", false ).attr( "autofocus" ), undefined, "Setting autofocus to false removes it" ); assert.equal( $text.attr( "required" ), "required", "Reading required attribute yields 'required'" ); assert.equal( $text.attr( "required", false ).attr( "required" ), undefined, "Setting required attribute to false removes it" ); $details = jQuery( "<details open></details>" ).appendTo( "#qunit-fixture" ); assert.equal( $details.attr( "open" ), "", "open attribute presence indicates true" ); assert.equal( $details.attr( "open", false ).attr( "open" ), undefined, "Setting open attribute to false removes it" ); $text.attr( "data-something", true ); assert.equal( $text.attr( "data-something" ), "true", "Set data attributes" ); assert.equal( $text.data( "something" ), true, "Setting data attributes are not affected by boolean settings" ); $text.attr( "data-another", "false" ); assert.equal( $text.attr( "data-another" ), "false", "Set data attributes" ); assert.equal( $text.data( "another" ), false, "Setting data attributes are not affected by boolean settings" ); assert.equal( $text.attr( "aria-disabled", false ).attr( "aria-disabled" ), "false", "Setting aria attributes are not affected by boolean settings" ); $text.removeData( "something" ).removeData( "another" ).removeAttr( "aria-disabled" ); jQuery( "#foo" ).attr( "contenteditable", true ); assert.equal( jQuery( "#foo" ).attr( "contenteditable" ), "true", "Enumerated attributes are set properly" ); attributeNode = document.createAttribute( "irrelevant" ); commentNode = document.createComment( "some comment" ); textNode = document.createTextNode( "some text" ); obj = {}; jQuery.each( [ commentNode, textNode, attributeNode ], function( i, elem ) { var $elem = jQuery( elem ); $elem.attr( "nonexisting", "foo" ); assert.strictEqual( $elem.attr( "nonexisting" ), undefined, "attr(name, value) works correctly on comment and text nodes (bug trac-7500)." ); } ); jQuery.each( [ window, document, obj, "#firstp" ], function( i, elem ) { var oldVal = elem.nonexisting, $elem = jQuery( elem ); assert.strictEqual( $elem.attr( "nonexisting" ), undefined, "attr works correctly for non existing attributes (bug trac-7500)." ); assert.equal( $elem.attr( "nonexisting", "foo" ).attr( "nonexisting" ), "foo", "attr falls back to prop on unsupported arguments" ); elem.nonexisting = oldVal; } ); // Register the property on the window for the previous assertion so it will be clean up Globals.register( "nonexisting" ); table = jQuery( "#table" ).append( "<tr><td>cell</td></tr><tr><td>cell</td><td>cell</td></tr><tr><td>cell</td><td>cell</td></tr>" ); td = table.find( "td" ).eq( 0 ); td.attr( "rowspan", "2" ); assert.equal( td[ 0 ].rowSpan, 2, "Check rowspan is correctly set" ); td.attr( "colspan", "2" ); assert.equal( td[ 0 ].colSpan, 2, "Check colspan is correctly set" ); table.attr( "cellspacing", "2" ); assert.equal( table[ 0 ].cellSpacing, "2", "Check cellspacing is correctly set" ); assert.equal( jQuery( "#area1" ).attr( "value" ), undefined, "Value attribute is distinct from value property." ); // for trac-1070 jQuery( "#name" ).attr( "someAttr", "0" ); assert.equal( jQuery( "#name" ).attr( "someAttr" ), "0", "Set attribute to a string of '0'" ); jQuery( "#name" ).attr( "someAttr", 0 ); assert.equal( jQuery( "#name" ).attr( "someAttr" ), "0", "Set attribute to the number 0" ); jQuery( "#name" ).attr( "someAttr", 1 ); assert.equal( jQuery( "#name" ).attr( "someAttr" ), "1", "Set attribute to the number 1" ); // using contents will get comments regular, text, and comment nodes j = jQuery( "#nonnodes" ).contents(); j.attr( "name", "attrvalue" ); assert.equal( j.attr( "name" ), "attrvalue", "Check node,textnode,comment for attr" ); j.removeAttr( "name" ); // Type try { jQuery( "#check2" ).attr( "type", "hidden" ); assert.ok( true, "No exception thrown on input type change" ); } catch ( e ) { assert.ok( true, "Exception thrown on input type change: " + e ); } check = document.createElement( "input" ); thrown = true; try { jQuery( check ).attr( "type", "checkbox" ); } catch ( e ) { thrown = false; } assert.ok( thrown, "Exception thrown when trying to change type property" ); assert.equal( "checkbox", jQuery( check ).attr( "type" ), "Verify that you can change the type of an input element that isn't in the DOM" ); check = jQuery( "<input />" ); thrown = true; try { check.attr( "type", "checkbox" ); } catch ( e ) { thrown = false; } assert.ok( thrown, "Exception thrown when trying to change type property" ); assert.equal( "checkbox", check.attr( "type" ), "Verify that you can change the type of an input element that isn't in the DOM" ); button = jQuery( "#button" ); try { button.attr( "type", "submit" ); assert.ok( true, "No exception thrown on button type change" ); } catch ( e ) { assert.ok( true, "Exception thrown on button type change: " + e ); } $radio = jQuery( "<input>", { "value": "sup", // Use uppercase here to ensure the type // attrHook is still used "TYPE": "radio" } ).appendTo( "#testForm" ); assert.equal( $radio.val(), "sup", "Value is not reset when type is set after value on a radio" ); // Setting attributes on svg elements (bug trac-3116) $svg = jQuery( "<svg xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' version='1.1' baseProfile='full' width='200' height='200'>" + "<circle cx='200' cy='200' r='150' />" + "</svg>" ).appendTo( "body" ); assert.equal( $svg.attr( "cx", 100 ).attr( "cx" ), "100", "Set attribute on svg element" ); $svg.remove(); // undefined values are chainable jQuery( "#name" ).attr( "maxlength", "5" ).removeAttr( "nonexisting" ); assert.equal( typeof jQuery( "#name" ).attr( "maxlength", undefined ), "object", ".attr('attribute', undefined) is chainable (trac-5571)" ); assert.equal( jQuery( "#name" ).attr( "maxlength", undefined ).attr( "maxlength" ), "5", ".attr('attribute', undefined) does not change value (trac-5571)" ); assert.equal( jQuery( "#name" ).attr( "nonexisting", undefined ).attr( "nonexisting" ), undefined, ".attr('attribute', undefined) does not create attribute (trac-5571)" ); } ); QUnit.test( "attr( previously-boolean-attr, non-boolean-value)", function( assert ) { assert.expect( 3 ); var div = jQuery( "<div></div>" ).appendTo( "#qunit-fixture" ); div.attr( "hidden", "foo" ); assert.strictEqual( div.attr( "hidden" ), "foo", "Values not normalized for previously-boolean hidden attribute" ); div.attr( "hidden", "until-found" ); assert.strictEqual( div.attr( "hidden" ), "until-found", "`until-found` value preserved for hidden attribute" ); div.attr( "hiDdeN", "uNtil-fOund" ); assert.strictEqual( div.attr( "hidden" ), "uNtil-fOund", "`uNtil-fOund` different casing preserved" ); } ); QUnit.test( "attr(non-ASCII)", function( assert ) { assert.expect( 2 ); var $div = jQuery( "<div Ω='omega' aØc='alpha'></div>" ).appendTo( "#qunit-fixture" ); assert.equal( $div.attr( "Ω" ), "omega", ".attr() exclusively lowercases characters in the range A-Z (gh-2730)" ); assert.equal( $div.attr( "AØC" ), "alpha", ".attr() exclusively lowercases characters in the range A-Z (gh-2730)" ); } ); QUnit.test( "attr(String, Object) - Loaded via XML document", function( assert ) { assert.expect( 2 ); var xml = createDashboardXML(), titles = []; jQuery( "tab", xml ).each( function() { titles.push( jQuery( this ).attr( "title" ) ); } ); assert.equal( titles[ 0 ], "Location", "attr() in XML context: Check first title" ); assert.equal( titles[ 1 ], "Users", "attr() in XML context: Check second title" ); } ); QUnit.test( "attr(String, Object) - Loaded via XML fragment", function( assert ) { assert.expect( 2 ); var frag = createXMLFragment(), $frag = jQuery( frag ); $frag.attr( "test", "some value" ); assert.equal( $frag.attr( "test" ), "some value", "set attribute" ); $frag.attr( "test", null ); assert.equal( $frag.attr( "test" ), undefined, "remove attribute" ); } ); QUnit.test( "attr('tabindex')", function( assert ) { assert.expect( 8 ); // elements not natively tabbable assert.equal( jQuery( "#listWithTabIndex" ).attr( "tabindex" ), "5", "not natively tabbable, with tabindex set to 0" ); assert.equal( jQuery( "#divWithNoTabIndex" ).attr( "tabindex" ), undefined, "not natively tabbable, no tabindex set" ); // anchor with href assert.equal( jQuery( "#linkWithNoTabIndex" ).attr( "tabindex" ), undefined, "anchor with href, no tabindex set" ); assert.equal( jQuery( "#linkWithTabIndex" ).attr( "tabindex" ), "2", "anchor with href, tabindex set to 2" ); assert.equal( jQuery( "#linkWithNegativeTabIndex" ).attr( "tabindex" ), "-1", "anchor with href, tabindex set to -1" ); // anchor without href assert.equal( jQuery( "#linkWithNoHrefWithNoTabIndex" ).attr( "tabindex" ), undefined, "anchor without href, no tabindex set" ); assert.equal( jQuery( "#linkWithNoHrefWithTabIndex" ).attr( "tabindex" ), "1", "anchor without href, tabindex set to 2" ); assert.equal( jQuery( "#linkWithNoHrefWithNegativeTabIndex" ).attr( "tabindex" ), "-1", "anchor without href, no tabindex set" ); } ); QUnit.test( "attr('tabindex', value)", function( assert ) { assert.expect( 9 ); var element = jQuery( "#divWithNoTabIndex" ); assert.equal( element.attr( "tabindex" ), undefined, "start with no tabindex" ); // set a positive string element.attr( "tabindex", "1" ); assert.equal( element.attr( "tabindex" ), "1", "set tabindex to 1 (string)" ); // set a zero string element.attr( "tabindex", "0" ); assert.equal( element.attr( "tabindex" ), "0", "set tabindex to 0 (string)" ); // set a negative string element.attr( "tabindex", "-1" ); assert.equal( element.attr( "tabindex" ), "-1", "set tabindex to -1 (string)" ); // set a positive number element.attr( "tabindex", 1 ); assert.equal( element.attr( "tabindex" ), "1", "set tabindex to 1 (number)" ); // set a zero number element.attr( "tabindex", 0 ); assert.equal( element.attr( "tabindex" ), "0", "set tabindex to 0 (number)" ); // set a negative number element.attr( "tabindex", -1 ); assert.equal( element.attr( "tabindex" ), "-1", "set tabindex to -1 (number)" ); element = jQuery( "#linkWithTabIndex" ); assert.equal( element.attr( "tabindex" ), "2", "start with tabindex 2" ); element.attr( "tabindex", -1 ); assert.equal( element.attr( "tabindex" ), "-1", "set negative tabindex" ); } ); QUnit.test( "removeAttr(String)", function( assert ) { assert.expect( 12 ); var $first; assert.equal( jQuery( "<div class='hello'></div>" ).removeAttr( "class" ).attr( "class" ), undefined, "remove class" ); assert.equal( jQuery( "#form" ).removeAttr( "id" ).attr( "id" ), undefined, "Remove id" ); assert.equal( jQuery( "#foo" ).attr( "style", "position:absolute;" ).removeAttr( "style" ).attr( "style" ), undefined, "Check removing style attribute" ); assert.equal( jQuery( "#form" ).attr( "style", "position:absolute;" ).removeAttr( "style" ).attr( "style" ), undefined, "Check removing style attribute on a form" ); assert.equal( jQuery( "<div style='position: absolute'></div>" ).appendTo( "#foo" ).removeAttr( "style" ).prop( "style" ).cssText, "", "Check removing style attribute (trac-9699 Webkit)" ); assert.equal( jQuery( "#fx-test-group" ).attr( "height", "3px" ).removeAttr( "height" ).get( 0 ).style.height, "1px", "Removing height attribute has no effect on height set with style attribute" ); jQuery( "#check1" ).removeAttr( "checked" ).prop( "checked", true ).removeAttr( "checked" ); assert.equal( document.getElementById( "check1" ).checked, true, "removeAttr should not set checked to false, since the checked attribute does NOT mirror the checked property" ); jQuery( "#text1" ).prop( "readOnly", true ).removeAttr( "readonly" ); assert.equal( document.getElementById( "text1" ).readOnly, false, "removeAttr sets boolean properties to false" ); jQuery( "#option2c" ).removeAttr( "selected" ); assert.equal( jQuery( "#option2d" ).attr( "selected" ), "selected", "Removing `selected` from an option that is not selected does not remove selected from the currently selected option (trac-10870)" ); try { $first = jQuery( "#first" ).attr( "contenteditable", "true" ).removeAttr( "contenteditable" ); assert.equal( $first.attr( "contenteditable" ), undefined, "Remove the contenteditable attribute" ); } catch ( e ) { assert.ok( false, "Removing contenteditable threw an error (trac-10429)" ); } $first = jQuery( "<div Case='mixed'></div>" ); assert.equal( $first.attr( "Case" ), "mixed", "case of attribute doesn't matter" ); $first.removeAttr( "Case" ); assert.equal( $first.attr( "Case" ), undefined, "mixed-case attribute was removed" ); } ); QUnit.test( "removeAttr(String) in XML", function( assert ) { assert.expect( 7 ); var xml = createDashboardXML(), iwt = jQuery( "infowindowtab", xml ); assert.equal( iwt.attr( "normal" ), "ab", "Check initial value" ); iwt.removeAttr( "Normal" ); assert.equal( iwt.attr( "normal" ), "ab", "Should still be there" ); iwt.removeAttr( "normal" ); assert.equal( iwt.attr( "normal" ), undefined, "Removed" ); assert.equal( iwt.attr( "mixedCase" ), "yes", "Check initial value" ); assert.equal( iwt.attr( "mixedcase" ), undefined, "toLowerCase not work good" ); iwt.removeAttr( "mixedcase" ); assert.equal( iwt.attr( "mixedCase" ), "yes", "Should still be there" ); iwt.removeAttr( "mixedCase" ); assert.equal( iwt.attr( "mixedCase" ), undefined, "Removed" ); } ); QUnit.test( "removeAttr(Multi String, variable space width)", function( assert ) { assert.expect( 8 ); var div = jQuery( "<div id='a' alt='b' title='c' rel='d'></div>" ), tests = { id: "a", alt: "b", title: "c", rel: "d" }; jQuery.each( tests, function( key, val ) { assert.equal( div.attr( key ), val, "Attribute `" + key + "` exists, and has a value of `" + val + "`" ); } ); div.removeAttr( "id alt title rel " ); jQuery.each( tests, function( key ) { assert.equal( div.attr( key ), undefined, "Attribute `" + key + "` was removed" ); } ); } ); QUnit.test( "removeAttr(Multi String, non-HTML whitespace is valid in attribute names (gh-3003)", function( assert ) { assert.expect( 8 ); var div = jQuery( "<div id='a' data-\xA0='b' title='c' rel='d'></div>" ); var tests = { id: "a", "data-\xA0": "b", title: "c", rel: "d" }; jQuery.each( tests, function( key, val ) { assert.equal( div.attr( key ), val, "Attribute \"" + key + "\" exists, and has a value of \"" + val + "\"" ); } ); div.removeAttr( "id data-\xA0 title rel " ); jQuery.each( tests, function( key ) { assert.equal( div.attr( key ), undefined, "Attribute \"" + key + "\" was removed" ); } ); } ); QUnit.test( "prop(String, Object)", function( assert ) { assert.expect( 17 ); assert.equal( jQuery( "#text1" ).prop( "value" ), "Test", "Check for value attribute" ); assert.equal( jQuery( "#text1" ).prop( "value", "Test2" ).prop( "defaultValue" ), "Test", "Check for defaultValue attribute" ); assert.equal( jQuery( "#select2" ).prop( "selectedIndex" ), 3, "Check for selectedIndex attribute" ); assert.equal( jQuery( "#foo" ).prop( "nodeName" ).toUpperCase(), "DIV", "Check for nodeName attribute" ); assert.equal( jQuery( "#foo" ).prop( "tagName" ).toUpperCase(), "DIV", "Check for tagName attribute" ); assert.equal( jQuery( "<option></option>" ).prop( "selected" ), false, "Check selected attribute on disconnected element." ); assert.equal( jQuery( "#listWithTabIndex" ).prop( "tabindex" ), 5, "Check retrieving tabindex" ); jQuery( "#text1" ).prop( "readonly", true ); assert.equal( document.getElementById( "text1" ).readOnly, true, "Check setting readOnly property with 'readonly'" ); assert.equal( jQuery( "#label-for" ).prop( "for" ), "action", "Check retrieving htmlFor" ); jQuery( "#text1" ).prop( "class", "test" ); assert.equal( document.getElementById( "text1" ).className, "test", "Check setting className with 'class'" );
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
true
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/test/unit/offset.js
test/unit/offset.js
( function() { if ( !includesModule( "offset" ) ) { return; } var alwaysScrollable, forceScroll = supportjQuery( "<div></div>" ).css( { width: 2000, height: 2000 } ), checkSupport = function( assert ) { // Only run once checkSupport = false; // Append forceScroll to the body instead of #qunit-fixture because the latter is hidden forceScroll.appendTo( "body" ); window.scrollTo( 200, 200 ); forceScroll.detach(); // Support: iOS <=7 - 12+ // Hijack the iframe test infrastructure to detect viewport scrollability // for pages with position:fixed document element var done = assert.async(); testIframe( null, "offset/boxes.html", function( assert, $, win, doc ) { var scrollTop = win.pageYOffset, scrollLeft = win.pageXOffset; doc.documentElement.style.position = "fixed"; win.scrollTo( scrollLeft, scrollTop ); alwaysScrollable = win.pageXOffset !== 0; done(); }, function mockQUnit_test( _, testCallback ) { setTimeout( function() { testCallback( assert ); } ); } ); }; QUnit.module( "offset", { beforeEach: function( assert ) { if ( typeof checkSupport === "function" ) { checkSupport( assert ); } // Force a scroll value on the main window to ensure incorrect results // if offset is using the scroll offset of the parent window forceScroll.appendTo( "body" ); window.scrollTo( 1, 1 ); forceScroll.detach(); }, afterEach: moduleTeardown } ); QUnit.test( "empty set", function( assert ) { assert.expect( 2 ); assert.strictEqual( jQuery().offset(), undefined, "offset() returns undefined for empty set (trac-11962)" ); assert.strictEqual( jQuery().position(), undefined, "position() returns undefined for empty set (trac-11962)" ); } ); QUnit.test( "disconnected element", function( assert ) { assert.expect( 4 ); var result = jQuery( document.createElement( "div" ) ).offset(); // These tests are solely for main/compat consistency // Retrieving offset on disconnected/hidden elements is not officially // valid input, but will return zeros for back-compat assert.equal( result.top, 0, "Retrieving offset on disconnected elements returns zeros (gh-2310)" ); assert.equal( result.left, 0, "Retrieving offset on disconnected elements returns zeros (gh-2310)" ); assert.equal( Object.keys( result ).length, 2, "Retrieving offset on disconnected elements returns offset object (gh-3167)" ); assert.equal( jQuery.isPlainObject( result ), true, "Retrieving offset on disconnected elements returns plain object (gh-3612)" ); } ); QUnit.test( "hidden (display: none) element", function( assert ) { assert.expect( 4 ); var node = jQuery( "<div style='display: none'></div>" ).appendTo( "#qunit-fixture" ), result = node.offset(); node.remove(); // These tests are solely for main/compat consistency // Retrieving offset on disconnected/hidden elements is not officially // valid input, but will return zeros for back-compat assert.equal( result.top, 0, "Retrieving offset on hidden elements returns zeros (gh-2310)" ); assert.equal( result.left, 0, "Retrieving offset on hidden elements returns zeros (gh-2310)" ); assert.equal( Object.keys( result ).length, 2, "Retrieving offset on hidden elements returns offset object (gh-3167)" ); assert.equal( jQuery.isPlainObject( result ), true, "Retrieving offset on hidden elements returns plain object (gh-3612)" ); } ); QUnit.test( "0 sized element", function( assert ) { assert.expect( 4 ); var node = jQuery( "<div style='margin: 5px; width: 0; height: 0'></div>" ).appendTo( "#qunit-fixture" ), result = node.offset(); node.remove(); assert.notEqual( result.top, 0, "Retrieving offset on 0 sized elements (gh-3167)" ); assert.notEqual( result.left, 0, "Retrieving offset on 0 sized elements (gh-3167)" ); assert.equal( Object.keys( result ).length, 2, "Retrieving offset on 0 sized elements returns offset object (gh-3167)" ); assert.equal( jQuery.isPlainObject( result ), true, "Retrieving offset on 0 sized elements returns plain object (gh-3612)" ); } ); QUnit.test( "hidden (visibility: hidden) element", function( assert ) { assert.expect( 4 ); var node = jQuery( "<div style='margin: 5px; visibility: hidden'></div>" ).appendTo( "#qunit-fixture" ), result = node.offset(); node.remove(); assert.notEqual( result.top, 0, "Retrieving offset on visibility:hidden elements (gh-3167)" ); assert.notEqual( result.left, 0, "Retrieving offset on visibility:hidden elements (gh-3167)" ); assert.equal( Object.keys( result ).length, 2, "Retrieving offset on visibility:hidden elements returns offset object (gh-3167)" ); assert.equal( jQuery.isPlainObject( result ), true, "Retrieving offset on visibility:hidden elements returns plain object (gh-3612)" ); } ); QUnit.test( "normal element", function( assert ) { assert.expect( 4 ); var node = jQuery( "<div>" ).appendTo( "#qunit-fixture" ), offset = node.offset(), position = node.position(); node.remove(); assert.equal( Object.keys( offset ).length, 2, "Retrieving offset on normal elements returns offset object (gh-3612)" ); assert.equal( jQuery.isPlainObject( offset ), true, "Retrieving offset on normal elements returns plain object (gh-3612)" ); assert.equal( Object.keys( position ).length, 2, "Retrieving position on normal elements returns offset object (gh-3612)" ); assert.equal( jQuery.isPlainObject( position ), true, "Retrieving position on normal elements returns plain object (gh-3612)" ); } ); testIframe( "absolute", "offset/absolute.html", function( assert, $, iframe ) { assert.expect( 4 ); var doc = iframe.document, tests; // get offset tests = [ { "id": "#absolute-1", "top": 1, "left": 1 } ]; jQuery.each( tests, function() { assert.equal( jQuery( this.id, doc ).offset().top, this.top, "jQuery('" + this.id + "').offset().top" ); assert.equal( jQuery( this.id, doc ).offset().left, this.left, "jQuery('" + this.id + "').offset().left" ); } ); // get position tests = [ { "id": "#absolute-1", "top": 0, "left": 0 } ]; jQuery.each( tests, function() { assert.equal( jQuery( this.id, doc ).position().top, this.top, "jQuery('" + this.id + "').position().top" ); assert.equal( jQuery( this.id, doc ).position().left, this.left, "jQuery('" + this.id + "').position().left" ); } ); } ); testIframe( "absolute", "offset/absolute.html", function( assert, $ ) { assert.expect( 178 ); var tests, offset; // get offset tests tests = [ { "id": "#absolute-1", "top": 1, "left": 1 }, { "id": "#absolute-1-1", "top": 5, "left": 5 }, { "id": "#absolute-1-1-1", "top": 9, "left": 9 }, { "id": "#absolute-2", "top": 20, "left": 20 } ]; jQuery.each( tests, function() { assert.equal( $( this.id ).offset().top, this.top, "jQuery('" + this.id + "').offset().top" ); assert.equal( $( this.id ).offset().left, this.left, "jQuery('" + this.id + "').offset().left" ); } ); // get position tests = [ { "id": "#absolute-1", "top": 0, "left": 0 }, { "id": "#absolute-1-1", "top": 1, "left": 1 }, { "id": "#absolute-1-1-1", "top": 1, "left": 1 }, { "id": "#absolute-2", "top": 19, "left": 19 } ]; jQuery.each( tests, function() { assert.equal( $( this.id ).position().top, this.top, "jQuery('" + this.id + "').position().top" ); assert.equal( $( this.id ).position().left, this.left, "jQuery('" + this.id + "').position().left" ); } ); // test trac-5781 offset = $( "#positionTest" ).offset( { "top": 10, "left": 10 } ).offset(); assert.equal( offset.top, 10, "Setting offset on element with position absolute but 'auto' values." ); assert.equal( offset.left, 10, "Setting offset on element with position absolute but 'auto' values." ); // set offset tests = [ { "id": "#absolute-2", "top": 30, "left": 30 }, { "id": "#absolute-2", "top": 10, "left": 10 }, { "id": "#absolute-2", "top": -1, "left": -1 }, { "id": "#absolute-2", "top": 19, "left": 19 }, { "id": "#absolute-1-1-1", "top": 15, "left": 15 }, { "id": "#absolute-1-1-1", "top": 5, "left": 5 }, { "id": "#absolute-1-1-1", "top": -1, "left": -1 }, { "id": "#absolute-1-1-1", "top": 9, "left": 9 }, { "id": "#absolute-1-1", "top": 10, "left": 10 }, { "id": "#absolute-1-1", "top": 0, "left": 0 }, { "id": "#absolute-1-1", "top": -1, "left": -1 }, { "id": "#absolute-1-1", "top": 5, "left": 5 }, { "id": "#absolute-1", "top": 2, "left": 2 }, { "id": "#absolute-1", "top": 0, "left": 0 }, { "id": "#absolute-1", "top": -1, "left": -1 }, { "id": "#absolute-1", "top": 1, "left": 1 } ]; jQuery.each( tests, function() { $( this.id ).offset( { "top": this.top, "left": this.left } ); assert.equal( $( this.id ).offset().top, this.top, "jQuery('" + this.id + "').offset({ top: " + this.top + " })" ); assert.equal( $( this.id ).offset().left, this.left, "jQuery('" + this.id + "').offset({ left: " + this.left + " })" ); var top = this.top, left = this.left; $( this.id ).offset( function( i, val ) { assert.equal( val.top, top, "Verify incoming top position." ); assert.equal( val.left, left, "Verify incoming top position." ); return { "top": top + 1, "left": left + 1 }; } ); assert.equal( $( this.id ).offset().top, this.top + 1, "jQuery('" + this.id + "').offset({ top: " + ( this.top + 1 ) + " })" ); assert.equal( $( this.id ).offset().left, this.left + 1, "jQuery('" + this.id + "').offset({ left: " + ( this.left + 1 ) + " })" ); $( this.id ) .offset( { "left": this.left + 2 } ) .offset( { "top": this.top + 2 } ); assert.equal( $( this.id ).offset().top, this.top + 2, "Setting one property at a time." ); assert.equal( $( this.id ).offset().left, this.left + 2, "Setting one property at a time." ); $( this.id ).offset( { "top": this.top, "left": this.left, "using": function( props ) { $( this ).css( { "top": props.top + 1, "left": props.left + 1 } ); } } ); assert.equal( $( this.id ).offset().top, this.top + 1, "jQuery('" + this.id + "').offset({ top: " + ( this.top + 1 ) + ", using: fn })" ); assert.equal( $( this.id ).offset().left, this.left + 1, "jQuery('" + this.id + "').offset({ left: " + ( this.left + 1 ) + ", using: fn })" ); } ); } ); testIframe( "relative", "offset/relative.html", function( assert, $ ) { assert.expect( 64 ); // get offset var tests = [ { "id": "#relative-1", "top": 7, "left": 7 }, { "id": "#relative-1-1", "top": 15, "left": 15 }, { "id": "#relative-2", "top": 142, "left": 27 }, { "id": "#relative-2-1", "top": 149, "left": 52 } ]; jQuery.each( tests, function() { assert.equal( $( this.id ).offset().top, this.top, "jQuery('" + this.id + "').offset().top" ); assert.equal( $( this.id ).offset().left, this.left, "jQuery('" + this.id + "').offset().left" ); } ); // get position tests = [ { "id": "#relative-1", "top": 6, "left": 6 }, { "id": "#relative-1-1", "top": 5, "left": 5 }, { "id": "#relative-2", "top": 141, "left": 26 }, { "id": "#relative-2-1", "top": 5, "left": 5 } ]; jQuery.each( tests, function() { assert.equal( $( this.id ).position().top, this.top, "jQuery('" + this.id + "').position().top" ); assert.equal( $( this.id ).position().left, this.left, "jQuery('" + this.id + "').position().left" ); } ); // set offset tests = [ { "id": "#relative-2", "top": 200, "left": 50 }, { "id": "#relative-2", "top": 100, "left": 10 }, { "id": "#relative-2", "top": -5, "left": -5 }, { "id": "#relative-2", "top": 142, "left": 27 }, { "id": "#relative-1-1", "top": 100, "left": 100 }, { "id": "#relative-1-1", "top": 5, "left": 5 }, { "id": "#relative-1-1", "top": -1, "left": -1 }, { "id": "#relative-1-1", "top": 15, "left": 15 }, { "id": "#relative-1", "top": 100, "left": 100 }, { "id": "#relative-1", "top": 0, "left": 0 }, { "id": "#relative-1", "top": -1, "left": -1 }, { "id": "#relative-1", "top": 7, "left": 7 } ]; jQuery.each( tests, function() { $( this.id ).offset( { "top": this.top, "left": this.left } ); assert.equal( $( this.id ).offset().top, this.top, "jQuery('" + this.id + "').offset({ top: " + this.top + " })" ); assert.equal( $( this.id ).offset().left, this.left, "jQuery('" + this.id + "').offset({ left: " + this.left + " })" ); $( this.id ).offset( { "top": this.top, "left": this.left, "using": function( props ) { $( this ).css( { "top": props.top + 1, "left": props.left + 1 } ); } } ); assert.equal( $( this.id ).offset().top, this.top + 1, "jQuery('" + this.id + "').offset({ top: " + ( this.top + 1 ) + ", using: fn })" ); assert.equal( $( this.id ).offset().left, this.left + 1, "jQuery('" + this.id + "').offset({ left: " + ( this.left + 1 ) + ", using: fn })" ); } ); } ); testIframe( "static", "offset/static.html", function( assert, $ ) { assert.expect( 80 ); // get offset var tests = [ { "id": "#static-1", "top": 7, "left": 7 }, { "id": "#static-1-1", "top": 15, "left": 15 }, { "id": "#static-1-1-1", "top": 23, "left": 23 }, { "id": "#static-2", "top": 122, left: 7 } ]; jQuery.each( tests, function() { assert.equal( $( this.id ).offset().top, this.top, "jQuery('" + this.id + "').offset().top" ); assert.equal( $( this.id ).offset().left, this.left, "jQuery('" + this.id + "').offset().left" ); } ); // get position tests = [ { "id": "#static-1", "top": 6, "left": 6 }, { "id": "#static-1-1", "top": 14, "left": 14 }, { "id": "#static-1-1-1", "top": 22, "left": 22 }, { "id": "#static-2", "top": 121, "left": 6 } ]; jQuery.each( tests, function() { assert.equal( $( this.id ).position().top, this.top, "jQuery('" + this.top + "').position().top" ); assert.equal( $( this.id ).position().left, this.left, "jQuery('" + this.left + "').position().left" ); } ); // set offset tests = [ { "id": "#static-2", "top": 200, "left": 200 }, { "id": "#static-2", "top": 100, "left": 100 }, { "id": "#static-2", "top": -2, "left": -2 }, { "id": "#static-2", "top": 121, "left": 6 }, { "id": "#static-1-1-1", "top": 50, "left": 50 }, { "id": "#static-1-1-1", "top": 10, "left": 10 }, { "id": "#static-1-1-1", "top": -1, "left": -1 }, { "id": "#static-1-1-1", "top": 22, "left": 22 }, { "id": "#static-1-1", "top": 25, "left": 25 }, { "id": "#static-1-1", "top": 10, "left": 10 }, { "id": "#static-1-1", "top": -3, "left": -3 }, { "id": "#static-1-1", "top": 14, "left": 14 }, { "id": "#static-1", "top": 30, "left": 30 }, { "id": "#static-1", "top": 2, "left": 2 }, { "id": "#static-1", "top": -2, "left": -2 }, { "id": "#static-1", "top": 7, "left": 7 } ]; jQuery.each( tests, function() { $( this.id ).offset( { "top": this.top, "left": this.left } ); assert.equal( $( this.id ).offset().top, this.top, "jQuery('" + this.id + "').offset({ top: " + this.top + " })" ); assert.equal( $( this.id ).offset().left, this.left, "jQuery('" + this.id + "').offset({ left: " + this.left + " })" ); $( this.id ).offset( { "top": this.top, "left": this.left, "using": function( props ) { $( this ).css( { "top": props.top + 1, "left": props.left + 1 } ); } } ); assert.equal( $( this.id ).offset().top, this.top + 1, "jQuery('" + this.id + "').offset({ top: " + ( this.top + 1 ) + ", using: fn })" ); assert.equal( $( this.id ).offset().left, this.left + 1, "jQuery('" + this.id + "').offset({ left: " + ( this.left + 1 ) + ", using: fn })" ); } ); } ); testIframe( "fixed", "offset/fixed.html", function( assert, $ ) { assert.expect( 38 ); var tests, $noTopLeft; tests = [ { "id": "#fixed-1", "offsetTop": 1001, "offsetLeft": 1001, "positionTop": 0, "positionLeft": 0 }, { "id": "#fixed-2", "offsetTop": 1021, "offsetLeft": 1021, "positionTop": 20, "positionLeft": 20 } ]; jQuery.each( tests, function() { assert.equal( jQuery.isPlainObject( $( this.id ).offset() ), true, "jQuery('" + this.id + "').offset() is plain object" ); assert.equal( jQuery.isPlainObject( $( this.id ).position() ), true, "jQuery('" + this.id + "').position() is plain object" ); assert.equal( $( this.id ).offset().top, this.offsetTop, "jQuery('" + this.id + "').offset().top" ); assert.equal( $( this.id ).position().top, this.positionTop, "jQuery('" + this.id + "').position().top" ); assert.equal( $( this.id ).offset().left, this.offsetLeft, "jQuery('" + this.id + "').offset().left" ); assert.equal( $( this.id ).position().left, this.positionLeft, "jQuery('" + this.id + "').position().left" ); } ); tests = [ { "id": "#fixed-1", "top": 100, "left": 100 }, { "id": "#fixed-1", "top": 0, "left": 0 }, { "id": "#fixed-1", "top": -4, "left": -4 }, { "id": "#fixed-2", "top": 200, "left": 200 }, { "id": "#fixed-2", "top": 0, "left": 0 }, { "id": "#fixed-2", "top": -5, "left": -5 } ]; jQuery.each( tests, function() { $( this.id ).offset( { "top": this.top, "left": this.left } ); assert.equal( $( this.id ).offset().top, this.top, "jQuery('" + this.id + "').offset({ top: " + this.top + " })" ); assert.equal( $( this.id ).offset().left, this.left, "jQuery('" + this.id + "').offset({ left: " + this.left + " })" ); $( this.id ).offset( { "top": this.top, "left": this.left, "using": function( props ) { $( this ).css( { "top": props.top + 1, "left": props.left + 1 } ); } } ); assert.equal( $( this.id ).offset().top, this.top + 1, "jQuery('" + this.id + "').offset({ top: " + ( this.top + 1 ) + ", using: fn })" ); assert.equal( $( this.id ).offset().left, this.left + 1, "jQuery('" + this.id + "').offset({ left: " + ( this.left + 1 ) + ", using: fn })" ); } ); // Bug 8316 $noTopLeft = $( "#fixed-no-top-left" ); assert.equal( $noTopLeft.offset().top, 1007, "Check offset top for fixed element with no top set" ); assert.equal( $noTopLeft.offset().left, 1007, "Check offset left for fixed element with no left set" ); } ); testIframe( "table", "offset/table.html", function( assert, $ ) { assert.expect( 6 ); assert.equal( $( "#table-1" ).offset().top, 6, "jQuery('#table-1').offset().top" ); assert.equal( $( "#table-1" ).offset().left, 6, "jQuery('#table-1').offset().left" ); assert.equal( $( "#th-1" ).offset().top, 10, "jQuery('#th-1').offset().top" ); assert.equal( $( "#th-1" ).offset().left, 10, "jQuery('#th-1').offset().left" ); assert.equal( $( "#th-1" ).position().top, 10, "jQuery('#th-1').position().top" ); assert.equal( $( "#th-1" ).position().left, 10, "jQuery('#th-1').position().left" ); } ); testIframe( "scroll", "offset/scroll.html", function( assert, $, win ) { assert.expect( 26 ); assert.equal( $( "#scroll-1" ).offset().top, 7, "jQuery('#scroll-1').offset().top" ); assert.equal( $( "#scroll-1" ).offset().left, 7, "jQuery('#scroll-1').offset().left" ); assert.equal( $( "#scroll-1-1" ).offset().top, 11, "jQuery('#scroll-1-1').offset().top" ); assert.equal( $( "#scroll-1-1" ).offset().left, 11, "jQuery('#scroll-1-1').offset().left" ); // These tests are solely for main/compat consistency // Retrieving offset on disconnected/hidden elements is not officially // valid input, but will return zeros for back-compat assert.equal( $( "#hidden" ).offset().top, 0, "Hidden elements do not subtract scroll" ); assert.equal( $( "#hidden" ).offset().left, 0, "Hidden elements do not subtract scroll" ); // scroll offset tests .scrollTop/Left assert.equal( $( "#scroll-1" ).scrollTop(), 5, "jQuery('#scroll-1').scrollTop()" ); assert.equal( $( "#scroll-1" ).scrollLeft(), 5, "jQuery('#scroll-1').scrollLeft()" ); assert.equal( $( "#scroll-1-1" ).scrollTop(), 0, "jQuery('#scroll-1-1').scrollTop()" ); assert.equal( $( "#scroll-1-1" ).scrollLeft(), 0, "jQuery('#scroll-1-1').scrollLeft()" ); // scroll method chaining assert.equal( $( "#scroll-1" ).scrollTop( undefined ).scrollTop(), 5, ".scrollTop(undefined) is chainable (trac-5571)" ); assert.equal( $( "#scroll-1" ).scrollLeft( undefined ).scrollLeft(), 5, ".scrollLeft(undefined) is chainable (trac-5571)" ); win.name = "test"; assert.equal( $( win ).scrollTop(), 1000, "jQuery(window).scrollTop()" ); assert.equal( $( win ).scrollLeft(), 1000, "jQuery(window).scrollLeft()" ); assert.equal( $( win.document ).scrollTop(), 1000, "jQuery(document).scrollTop()" ); assert.equal( $( win.document ).scrollLeft(), 1000, "jQuery(document).scrollLeft()" ); // test jQuery using parent window/document // jQuery reference here is in the iframe window.scrollTo( 0, 0 ); assert.equal( $( window ).scrollTop(), 0, "jQuery(window).scrollTop() other window" ); assert.equal( $( window ).scrollLeft(), 0, "jQuery(window).scrollLeft() other window" ); assert.equal( $( document ).scrollTop(), 0, "jQuery(window).scrollTop() other document" ); assert.equal( $( document ).scrollLeft(), 0, "jQuery(window).scrollLeft() other document" ); // Tests scrollTop/Left with empty jquery objects assert.notEqual( $().scrollTop( 100 ), null, "jQuery().scrollTop(100) testing setter on empty jquery object" ); assert.notEqual( $().scrollLeft( 100 ), null, "jQuery().scrollLeft(100) testing setter on empty jquery object" ); assert.notEqual( $().scrollTop( null ), null, "jQuery().scrollTop(null) testing setter on empty jquery object" ); assert.notEqual( $().scrollLeft( null ), null, "jQuery().scrollLeft(null) testing setter on empty jquery object" ); assert.strictEqual( $().scrollTop(), undefined, "jQuery().scrollTop() testing getter on empty jquery object" ); assert.strictEqual( $().scrollLeft(), undefined, "jQuery().scrollLeft() testing getter on empty jquery object" ); } ); testIframe( "body", "offset/body.html", function( assert, $ ) { assert.expect( 4 ); assert.equal( $( "body" ).offset().top, 1, "jQuery('#body').offset().top" ); assert.equal( $( "body" ).offset().left, 1, "jQuery('#body').offset().left" ); assert.equal( $( "#firstElement" ).position().left, 5, "$('#firstElement').position().left" ); assert.equal( $( "#firstElement" ).position().top, 5, "$('#firstElement').position().top" ); } ); QUnit.test( "chaining", function( assert ) { assert.expect( 3 ); var coords = { "top": 1, "left": 1 }; assert.equal( jQuery( "#absolute-1" ).offset( coords ).jquery, jQuery.fn.jquery, "offset(coords) returns jQuery object" ); assert.equal( jQuery( "#non-existent" ).offset( coords ).jquery, jQuery.fn.jquery, "offset(coords) with empty jQuery set returns jQuery object" ); assert.equal( jQuery( "#absolute-1" ).offset( undefined ).jquery, jQuery.fn.jquery, "offset(undefined) returns jQuery object (trac-5571)" ); } ); // Test complex content under a variety of <html>/<body> positioning styles ( function() { var POSITION_VALUES = [ "static", "relative", "absolute", "fixed" ], // Use shorthands for describing an element's relevant properties BOX_PROPS = ( "top left marginTop marginLeft borderTop borderLeft paddingTop paddingLeft" + " style parent" ).split( /\s+/g ), props = function() { var propObj = {}; supportjQuery.each( arguments, function( i, value ) { propObj[ BOX_PROPS[ i ] ] = value; } ); return propObj; }, // Values must stay synchronized with test/data/offset/boxes.html divProps = function( position, parentId ) { return props( 8, 4, 16, 8, 4, 2, 32, 16, position, parentId ); }, htmlProps = function( position ) { return props( position === "static" ? 0 : 4096, position === "static" ? 0 : 2048, 64, 32, 128, 64, 256, 128, position ); }, bodyProps = function( position ) { return props( position === "static" ? 0 : 8192, position === "static" ? 0 : 4096, 512, 256, 1024, 512, 2048, 1024, position, position !== "fixed" && "documentElement" ); }; function getExpectations( htmlPos, bodyPos, scrollTop, scrollLeft ) { // Initialize data about page elements var expectations = { "documentElement": htmlProps( htmlPos ), "body": bodyProps( bodyPos ), "relative": divProps( "relative", "body" ), "relative-relative": divProps( "relative", "relative" ), "relative-absolute": divProps( "absolute", "relative" ), "absolute": divProps( "absolute", "body" ), "absolute-relative": divProps( "relative", "absolute" ), "absolute-absolute": divProps( "absolute", "absolute" ), "fixed": divProps( "fixed" ), "fixed-relative": divProps( "relative", "fixed" ), "fixed-absolute": divProps( "absolute", "fixed" ) }; // Define position and offset expectations for page elements supportjQuery.each( expectations, function( id, props ) { var parent = expectations[ props.parent ], // position() relates an element's margin box to its offset parent's padding box pos = props.pos = { top: props.top, left: props.left }, // offset() relates an element's border box to the document origin offset = props.offset = { top: pos.top + props.marginTop, left: pos.left + props.marginLeft }; // Account for ancestors differently by element position // fixed: ignore them // absolute: offset includes offsetParent offset+border // relative: position includes parent padding (and also position+margin+border when // parent is not offsetParent); offset includes parent offset+border+padding // static: same as relative for ( ; parent; parent = expectations[ parent.parent ] ) { // position:fixed if ( props.style === "fixed" ) { break; } // position:absolute bypass if ( props.style === "absolute" && parent.style === "static" ) { continue; } // Offset update offset.top += parent.offset.top + parent.borderTop; offset.left += parent.offset.left + parent.borderLeft; if ( props.style !== "absolute" ) { offset.top += parent.paddingTop; offset.left += parent.paddingLeft; // position:relative or position:static position update pos.top += parent.paddingTop; pos.left += parent.paddingLeft; if ( parent.style === "static" ) { pos.top += parent.pos.top + parent.marginTop + parent.borderTop; pos.left += parent.pos.left + parent.marginLeft + parent.borderLeft; } } break; } // Viewport scroll affects position:fixed elements, except when the page is // unscrollable. if ( props.style === "fixed" && ( alwaysScrollable || expectations.documentElement.style !== "fixed" ) ) { offset.top += scrollTop; offset.left += scrollLeft; } } ); return expectations; } // Cover each combination of <html> position and <body> position supportjQuery.each( POSITION_VALUES, function( _, htmlPos ) { supportjQuery.each( POSITION_VALUES, function( _, bodyPos ) { var label = "nonzero box properties - html." + htmlPos + " body." + bodyPos; testIframe( label, "offset/boxes.html", function( assert, $, win, doc ) { // Define expectations at runtime to properly account for scrolling var scrollTop = win.pageYOffset, scrollLeft = win.pageXOffset, expectations = getExpectations( htmlPos, bodyPos, scrollTop, scrollLeft ); assert.expect( 3 * Object.keys( expectations ).length ); // Setup documentElement and body styles, preserving scroll position doc.documentElement.style.position = htmlPos; doc.body.style.position = bodyPos; win.scrollTo( scrollLeft, scrollTop ); // Verify expected document offset supportjQuery.each( expectations, function( id, descriptor ) { assert.deepEqual( supportjQuery.extend( {}, $( "#" + id ).offset() ), descriptor.offset, "jQuery('#" + id + "').offset(): top " + descriptor.offset.top + ", left " + descriptor.offset.left ); } ); // Verify expected relative position supportjQuery.each( expectations, function( id, descriptor ) { assert.deepEqual( supportjQuery.extend( {}, $( "#" + id ).position() ), descriptor.pos, "jQuery('#" + id + "').position(): top " + descriptor.pos.top + ", left " + descriptor.pos.left ); } ); // Verify that values round-trip supportjQuery.each( Object.keys( expectations ).reverse(), function( _, id ) { var $el = $( "#" + id ), pos = supportjQuery.extend( {}, $el.position() ); $el.css( { top: pos.top, left: pos.left } ); if ( $el.css( "position" ) === "relative" ) { // $relative.position() includes parent padding; switch to absolute // positioning so we don't double its effects. $el.css( { position: "absolute" } ); } assert.deepEqual( supportjQuery.extend( {}, $el.position() ), pos, "jQuery('#" + id + "').position() round-trips" ); // TODO Verify .offset(...) // assert.deepEqual( $el.offset( offset ).offset(), offset ) // assert.deepEqual( $el.offset( adjustedOffset ).offset(), adjustedOffset ) // assert.deepEqual( $new.offset( offset ).offset(), offset ) } ); } ); } ); } ); } )(); QUnit.test( "offsetParent", function( assert ) { assert.expect( 13 ); var body, header, div, area; body = jQuery( "body" ).offsetParent(); assert.equal( body.length, 1, "Only one offsetParent found." ); assert.equal( body[ 0 ], document.documentElement, "The html element is the offsetParent of the body." ); header = jQuery( "#qunit" ).offsetParent(); assert.equal( header.length, 1, "Only one offsetParent found." ); assert.equal( header[ 0 ], document.documentElement, "The html element is the offsetParent of #qunit." ); jQuery( "#qunit-fixture" ).css( "position", "absolute" ); div = jQuery( "#nothiddendivchild" ).offsetParent(); assert.equal( div.length, 1, "Only one offsetParent found." ); assert.equal( div[ 0 ], document.getElementById( "qunit-fixture" ), "The #qunit-fixture is the offsetParent of #nothiddendivchild." ); jQuery( "#qunit-fixture" ).css( "position", "" ); jQuery( "#nothiddendiv" ).css( "position", "relative" ); div = jQuery( "#nothiddendivchild" ).offsetParent(); assert.equal( div.length, 1, "Only one offsetParent found." ); assert.equal( div[ 0 ], jQuery( "#nothiddendiv" )[ 0 ], "The div is the offsetParent." ); div = jQuery( "body, #nothiddendivchild" ).offsetParent(); assert.equal( div.length, 2, "Two offsetParent found." ); assert.equal( div[ 0 ], document.documentElement, "The html element is the offsetParent of the body." ); assert.equal( div[ 1 ], jQuery( "#nothiddendiv" )[ 0 ], "The div is the offsetParent." ); area = jQuery( "<map name=\"imgmap\"><area shape=\"rect\" coords=\"0,0,200,50\"></map>" ).appendTo( "body" ).find( "area" ); assert.equal( area.offsetParent()[ 0 ], document.documentElement, "The html element is the offsetParent of a map area." ); area.remove(); div = jQuery( "<div>" ).css( { "position": "absolute" } ).appendTo( "body" ); assert.equal( div.offsetParent()[ 0 ], document.documentElement, "Absolutely positioned div returns html as offset parent, see trac-12139" ); div.remove(); } ); QUnit.test( "fractions (see trac-7730 and trac-7885)", function( assert ) { assert.expect( 2 ); jQuery( "body" ).append( "<div id='fractions'></div>" ); var result, expected = { "top": 1000, "left": 1000 }, div = jQuery( "#fractions" ); div.css( { "position": "absolute", "left": "1000.7432222px", "top": "1000.532325px", "width": 100, "height": 100 } ); div.offset( expected ); result = div.offset(); // Support: Chrome <=45 - 73+ // In recent Chrome these values differ a little. assert.ok( Math.abs( result.top - expected.top ) < 0.25, "Check top within 0.25 of expected" ); assert.ok( Math.abs( result.left - expected.left ) < 0.25, "Check left within 0.25 of expected" ); div.remove(); } ); QUnit.test( "iframe scrollTop/Left (see gh-1945)", function( assert ) { assert.expect( 2 ); var ifDoc = jQuery( "#iframe" )[ 0 ].contentDocument; // Tests scrollTop/Left with iframes jQuery( "#iframe" ).css( "width", "50px" ).css( "height", "50px" ); ifDoc.write( "<div style='width: 1000px; height: 1000px;'></div>" ); jQuery( ifDoc ).scrollTop( 200 ); jQuery( ifDoc ).scrollLeft( 500 ); assert.equal( jQuery( ifDoc ).scrollTop(), 200, "$($('#iframe')[0].contentDocument).scrollTop()" ); assert.equal( jQuery( ifDoc ).scrollLeft(), 500, "$($('#iframe')[0].contentDocument).scrollLeft()" ); } ); } )();
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
false
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/test/unit/manipulation.js
test/unit/manipulation.js
QUnit.module( "manipulation", { afterEach: moduleTeardown } ); // Ensure that an extended Array prototype doesn't break jQuery Array.prototype.arrayProtoFn = function() { }; function manipulationBareObj( value ) { return value; } function manipulationFunctionReturningObj( value ) { return function() { return value; }; } /* ======== local reference ======= manipulationBareObj and manipulationFunctionReturningObj can be used to test passing functions to setters See testVal below for an example bareObj( value ); This function returns whatever value is passed in functionReturningObj( value ); Returns a function that returns the value */ QUnit.test( "text()", function( assert ) { assert.expect( 6 ); var expected, frag, $newLineTest, doc; expected = "This link has class=\"blog\": Timmy Willison's Weblog"; assert.equal( jQuery( "#sap" ).text(), expected, "Check for merged text of more than one element." ); // Check serialization of text values assert.equal( jQuery( document.createTextNode( "foo" ) ).text(), "foo", "Text node was retrieved from .text()." ); assert.notEqual( jQuery( document ).text(), "", "Retrieving text for the document retrieves all text (trac-10724)." ); // Retrieve from document fragments trac-10864 frag = document.createDocumentFragment(); frag.appendChild( document.createTextNode( "foo" ) ); assert.equal( jQuery( frag ).text(), "foo", "Document Fragment Text node was retrieved from .text()." ); $newLineTest = jQuery( "<div>test<br/>testy</div>" ).appendTo( "#moretests" ); $newLineTest.find( "br" ).replaceWith( "\n" ); assert.equal( $newLineTest.text(), "test\ntesty", "text() does not remove new lines (trac-11153)" ); $newLineTest.remove(); doc = new DOMParser().parseFromString( "<span>example</span>", "text/html" ); assert.equal( jQuery( doc ).text(), "example", "text() on HTMLDocument (gh-5264)" ); } ); QUnit.test( "text(undefined)", function( assert ) { assert.expect( 1 ); assert.equal( jQuery( "#foo" ).text( "<div" ).text( undefined )[ 0 ].innerHTML, "&lt;div", ".text(undefined) is chainable (trac-5571)" ); } ); function testText( valueObj, assert ) { assert.expect( 6 ); var val, j, expected, $multipleElements, $parentDiv, $childDiv; val = valueObj( "<div><b>Hello</b> cruel world!</div>" ); assert.equal( jQuery( "#foo" ).text( val )[ 0 ].innerHTML.replace( />/g, "&gt;" ), "&lt;div&gt;&lt;b&gt;Hello&lt;/b&gt; cruel world!&lt;/div&gt;", "Check escaped text" ); // using contents will get comments regular, text, and comment nodes j = jQuery( "#nonnodes" ).contents(); j.text( valueObj( "hi!" ) ); assert.equal( jQuery( j[ 0 ] ).text(), "hi!", "Check node,textnode,comment with text()" ); assert.equal( j[ 1 ].nodeValue, " there ", "Check node,textnode,comment with text()" ); assert.equal( j[ 2 ].nodeType, 8, "Check node,textnode,comment with text()" ); // Update multiple elements trac-11809 expected = "New"; $multipleElements = jQuery( "<div>Hello</div>" ).add( "<div>World</div>" ); $multipleElements.text( expected ); assert.equal( $multipleElements.eq( 0 ).text(), expected, "text() updates multiple elements (trac-11809)" ); assert.equal( $multipleElements.eq( 1 ).text(), expected, "text() updates multiple elements (trac-11809)" ); // Prevent memory leaks trac-11809 $childDiv = jQuery( "<div></div>" ); $childDiv.data( "leak", true ); $parentDiv = jQuery( "<div></div>" ); $parentDiv.append( $childDiv ); $parentDiv.text( "Dry off" ); } QUnit.test( "text(String)", function( assert ) { testText( manipulationBareObj, assert ); } ); QUnit.test( "text(Function)", function( assert ) { testText( manipulationFunctionReturningObj, assert ); } ); QUnit.test( "text(Function) with incoming value", function( assert ) { assert.expect( 2 ); var old = "This link has class=\"blog\": Timmy Willison's Weblog"; jQuery( "#sap" ).text( function( i, val ) { assert.equal( val, old, "Make sure the incoming value is correct." ); return "foobar"; } ); assert.equal( jQuery( "#sap" ).text(), "foobar", "Check for merged text of more then one element." ); } ); function testAppendForObject( valueObj, isFragment, assert ) { var $base, type = isFragment ? " (DocumentFragment)" : " (Element)", text = "This link has class=\"blog\": Timmy Willison's Weblog", el = document.getElementById( "sap" ).cloneNode( true ), first = document.getElementById( "first" ), yahoo = document.getElementById( "yahoo" ); if ( isFragment ) { $base = document.createDocumentFragment(); jQuery( el ).contents().each( function() { $base.appendChild( this ); } ); $base = jQuery( $base ); } else { $base = jQuery( el ); } assert.equal( $base.clone().append( valueObj( first.cloneNode( true ) ) ).text(), text + "Try them out:", "Check for appending of element" + type ); assert.equal( $base.clone().append( valueObj( [ first.cloneNode( true ), yahoo.cloneNode( true ) ] ) ).text(), text + "Try them out:Yahoo", "Check for appending of array of elements" + type ); assert.equal( $base.clone().append( valueObj( jQuery( "#yahoo, #first" ).clone() ) ).text(), text + "YahooTry them out:", "Check for appending of jQuery object" + type ); assert.equal( $base.clone().append( valueObj( 5 ) ).text(), text + "5", "Check for appending a number" + type ); assert.equal( $base.clone().append( valueObj( [ jQuery( "#first" ).clone(), jQuery( "#yahoo, #google" ).clone() ] ) ).text(), text + "Try them out:GoogleYahoo", "Check for appending of array of jQuery objects" ); assert.equal( $base.clone().append( valueObj( " text with spaces " ) ).text(), text + " text with spaces ", "Check for appending text with spaces" + type ); assert.equal( $base.clone().append( valueObj( [] ) ).text(), text, "Check for appending an empty array" + type ); assert.equal( $base.clone().append( valueObj( "" ) ).text(), text, "Check for appending an empty string" + type ); assert.equal( $base.clone().append( valueObj( document.getElementsByTagName( "foo" ) ) ).text(), text, "Check for appending an empty nodelist" + type ); assert.equal( $base.clone().append( "<span></span>", "<span></span>", "<span></span>" ).children().length, $base.children().length + 3, "Make sure that multiple arguments works." + type ); assert.equal( $base.clone().append( valueObj( document.getElementById( "form" ).cloneNode( true ) ) ).children( "form" ).length, 1, "Check for appending a form (trac-910)" + type ); } function testAppend( valueObj, assert ) { assert.expect( 82 ); testAppendForObject( valueObj, false, assert ); testAppendForObject( valueObj, true, assert ); var defaultText, result, message, iframe, iframeDoc, j, d, $input, $radioChecked, $radioUnchecked, $radioParent, $map, $table; defaultText = "Try them out:"; result = jQuery( "#first" ).append( valueObj( "<b>buga</b>" ) ); assert.equal( result.text(), defaultText + "buga", "Check if text appending works" ); assert.equal( jQuery( "#select3" ).append( valueObj( "<option value='appendTest'>Append Test</option>" ) ).find( "option:last-child" ).attr( "value" ), "appendTest", "Appending html options to select element" ); jQuery( "#qunit-fixture form" ).append( valueObj( "<input name='radiotest' type='radio' checked='checked' />" ) ); jQuery( "#qunit-fixture form input[name=radiotest]" ).each( function() { assert.ok( jQuery( this ).is( ":checked" ), "Append checked radio" ); } ).remove(); jQuery( "#qunit-fixture form" ).append( valueObj( "<input name='radiotest2' type='radio' checked = 'checked' />" ) ); jQuery( "#qunit-fixture form input[name=radiotest2]" ).each( function() { assert.ok( jQuery( this ).is( ":checked" ), "Append alternately formatted checked radio" ); } ).remove(); jQuery( "#qunit-fixture form" ).append( valueObj( "<input name='radiotest3' type='radio' checked />" ) ); jQuery( "#qunit-fixture form input[name=radiotest3]" ).each( function() { assert.ok( jQuery( this ).is( ":checked" ), "Append HTML5-formatted checked radio" ); } ).remove(); jQuery( "#qunit-fixture form" ).append( valueObj( "<input type='radio' checked='checked' name='radiotest4' />" ) ); jQuery( "#qunit-fixture form input[name=radiotest4]" ).each( function() { assert.ok( jQuery( this ).is( ":checked" ), "Append with name attribute after checked attribute" ); } ).remove(); message = "Test for appending a DOM node to the contents of an iframe"; iframe = jQuery( "#iframe" )[ 0 ]; iframeDoc = iframe.contentDocument || iframe.contentWindow && iframe.contentWindow.document; try { if ( iframeDoc && iframeDoc.body ) { assert.equal( jQuery( iframeDoc.body ).append( valueObj( "<div id='success'>test</div>" ) )[ 0 ].lastChild.id, "success", message ); } else { assert.ok( true, message + " - can't test" ); } } catch ( e ) { assert.strictEqual( e.message || e, undefined, message ); } jQuery( "<fieldset></fieldset>" ).appendTo( "#form" ).append( valueObj( "<legend id='legend'>test</legend>" ) ); assert.t( "Append legend", "#legend", [ "legend" ] ); $map = jQuery( "<map></map>" ).append( valueObj( "<area id='map01' shape='rect' coords='50,50,150,150' href='https://www.jquery.com/' alt='jQuery'>" ) ); assert.equal( $map[ 0 ].childNodes.length, 1, "The area was inserted." ); assert.equal( $map[ 0 ].firstChild.nodeName.toLowerCase(), "area", "The area was inserted." ); jQuery( "#select1" ).append( valueObj( "<OPTION>Test</OPTION>" ) ); assert.equal( jQuery( "#select1 option:last-child" ).text(), "Test", "Appending OPTION (all caps)" ); jQuery( "#select1" ).append( valueObj( "<optgroup label='optgroup'><option>optgroup</option></optgroup>" ) ); assert.equal( jQuery( "#select1 optgroup" ).attr( "label" ), "optgroup", "Label attribute in newly inserted optgroup is correct" ); assert.equal( jQuery( "#select1 option" ).last().text(), "optgroup", "Appending optgroup" ); $table = jQuery( "#table" ); jQuery.each( "thead tbody tfoot colgroup caption tr th td".split( " " ), function( i, name ) { $table.append( valueObj( "<" + name + "/>" ) ); assert.equal( $table.find( name ).length, 1, "Append " + name ); assert.ok( jQuery.parseHTML( "<" + name + "/>" ).length, name + " wrapped correctly" ); } ); jQuery( "#table colgroup" ).append( valueObj( "<col></col>" ) ); assert.equal( jQuery( "#table colgroup col" ).length, 1, "Append col" ); jQuery( "#form" ) .append( valueObj( "<select id='appendSelect1'></select>" ) ) .append( valueObj( "<select id='appendSelect2'><option>Test</option></select>" ) ); assert.t( "Append Select", "#appendSelect1, #appendSelect2", [ "appendSelect1", "appendSelect2" ] ); assert.equal( "Two nodes", jQuery( "<div></div>" ).append( "Two", " nodes" ).text(), "Appending two text nodes (trac-4011)" ); assert.equal( jQuery( "<div></div>" ).append( "1", "", 3 ).text(), "13", "If median is false-like value, subsequent arguments should not be ignored" ); // using contents will get comments regular, text, and comment nodes j = jQuery( "#nonnodes" ).contents(); d = jQuery( "<div></div>" ).appendTo( "#nonnodes" ).append( j ); assert.equal( jQuery( "#nonnodes" ).length, 1, "Check node,textnode,comment append moved leaving just the div" ); assert.equal( d.contents().length, 3, "Check node,textnode,comment append works" ); d.contents().appendTo( "#nonnodes" ); d.remove(); assert.equal( jQuery( "#nonnodes" ).contents().length, 3, "Check node,textnode,comment append cleanup worked" ); $input = jQuery( "<input type='checkbox'/>" ).prop( "checked", true ).appendTo( "#testForm" ); assert.equal( $input[ 0 ].checked, true, "A checked checkbox that is appended stays checked" ); $radioChecked = jQuery( "input[type='radio'][name='R1']" ).eq( 1 ); $radioParent = $radioChecked.parent(); $radioUnchecked = jQuery( "<input type='radio' name='R1' checked='checked'/>" ).appendTo( $radioParent ); $radioChecked.trigger( "click" ); $radioUnchecked[ 0 ].checked = false; jQuery( "<div></div>" ).insertBefore( $radioParent ).append( $radioParent ); assert.equal( $radioChecked[ 0 ].checked, true, "Reappending radios uphold which radio is checked" ); assert.equal( $radioUnchecked[ 0 ].checked, false, "Reappending radios uphold not being checked" ); assert.equal( jQuery( "<div></div>" ).append( valueObj( "option<area></area>" ) )[ 0 ].childNodes.length, 2, "HTML-string with leading text should be processed correctly" ); } QUnit.test( "append(String|Element|Array<Element>|jQuery)", function( assert ) { testAppend( manipulationBareObj, assert ); } ); QUnit.test( "append(Function)", function( assert ) { testAppend( manipulationFunctionReturningObj, assert ); } ); QUnit.test( "append(param) to object, see trac-11280", function( assert ) { assert.expect( 5 ); var object = jQuery( document.createElement( "object" ) ).appendTo( document.body ); assert.equal( object.children().length, 0, "object does not start with children" ); object.append( jQuery( "<param type='wmode' name='foo'>" ) ); assert.equal( object.children().length, 1, "appended param" ); assert.equal( object.children().eq( 0 ).attr( "name" ), "foo", "param has name=foo" ); object = jQuery( "<object><param type='baz' name='bar'></object>" ); assert.equal( object.children().length, 1, "object created with child param" ); assert.equal( object.children().eq( 0 ).attr( "name" ), "bar", "param has name=bar" ); } ); QUnit.test( "append(Function) returns String", function( assert ) { assert.expect( 4 ); var defaultText, result, select, old; defaultText = "Try them out:"; old = jQuery( "#first" ).html(); result = jQuery( "#first" ).append( function( i, val ) { assert.equal( val, old, "Make sure the incoming value is correct." ); return "<b>buga</b>"; } ); assert.equal( result.text(), defaultText + "buga", "Check if text appending works" ); select = jQuery( "#select3" ); old = select.html(); assert.equal( select.append( function( i, val ) { assert.equal( val, old, "Make sure the incoming value is correct." ); return "<option value='appendTest'>Append Test</option>"; } ).find( "option:last-child" ).attr( "value" ), "appendTest", "Appending html options to select element" ); } ); QUnit.test( "append(Function) returns Element", function( assert ) { assert.expect( 2 ); var expected = "This link has class=\"blog\": Timmy Willison's WeblogTry them out:", old = jQuery( "#sap" ).html(); jQuery( "#sap" ).append( function( i, val ) { assert.equal( val, old, "Make sure the incoming value is correct." ); return document.getElementById( "first" ); } ); assert.equal( jQuery( "#sap" ).text(), expected, "Check for appending of element" ); } ); QUnit.test( "append(Function) returns Array<Element>", function( assert ) { assert.expect( 2 ); var expected = "This link has class=\"blog\": Timmy Willison's WeblogTry them out:Yahoo", old = jQuery( "#sap" ).html(); jQuery( "#sap" ).append( function( i, val ) { assert.equal( val, old, "Make sure the incoming value is correct." ); return [ document.getElementById( "first" ), document.getElementById( "yahoo" ) ]; } ); assert.equal( jQuery( "#sap" ).text(), expected, "Check for appending of array of elements" ); } ); QUnit.test( "append(Function) returns jQuery", function( assert ) { assert.expect( 2 ); var expected = "This link has class=\"blog\": Timmy Willison's WeblogYahooTry them out:", old = jQuery( "#sap" ).html(); jQuery( "#sap" ).append( function( i, val ) { assert.equal( val, old, "Make sure the incoming value is correct." ); return jQuery( "#yahoo, #first" ); } ); assert.equal( jQuery( "#sap" ).text(), expected, "Check for appending of jQuery object" ); } ); QUnit.test( "append(Function) returns Number", function( assert ) { assert.expect( 2 ); var old = jQuery( "#sap" ).html(); jQuery( "#sap" ).append( function( i, val ) { assert.equal( val, old, "Make sure the incoming value is correct." ); return 5; } ); assert.ok( jQuery( "#sap" )[ 0 ].innerHTML.match( /5$/ ), "Check for appending a number" ); } ); QUnit.test( "XML DOM manipulation (trac-9960)", function( assert ) { assert.expect( 5 ); var xmlDoc1 = jQuery.parseXML( "<scxml xmlns='http://www.w3.org/2005/07/scxml' version='1.0'><state x='100' y='100' initial='actions' id='provisioning'></state><state x='100' y='100' id='error'></state><state x='100' y='100' id='finished' final='true'></state></scxml>" ), xmlDoc2 = jQuery.parseXML( "<scxml xmlns='http://www.w3.org/2005/07/scxml' version='1.0'><state id='provisioning3'></state></scxml>" ), xml1 = jQuery( xmlDoc1 ), xml2 = jQuery( xmlDoc2 ), scxml1 = jQuery( "scxml", xml1 ), scxml2 = jQuery( "scxml", xml2 ), state = scxml2.find( "state" ); scxml1.append( state ); assert.strictEqual( scxml1[ 0 ].lastChild, state[ 0 ], "append" ); scxml1.prepend( state ); assert.strictEqual( scxml1[ 0 ].firstChild, state[ 0 ], "prepend" ); scxml1.find( "#finished" ).after( state ); assert.strictEqual( scxml1[ 0 ].lastChild, state[ 0 ], "after" ); scxml1.find( "#provisioning" ).before( state ); assert.strictEqual( scxml1[ 0 ].firstChild, state[ 0 ], "before" ); scxml2.replaceWith( scxml1 ); assert.deepEqual( jQuery( "state", xml2 ).get(), scxml1.find( "state" ).get(), "replaceWith" ); } ); QUnit.test( "append HTML5 sectioning elements (Bug trac-6485)", function( assert ) { assert.expect( 2 ); var article, aside; jQuery( "#qunit-fixture" ).append( "<article style='font-size:10px'><section><aside>HTML5 elements</aside></section></article>" ); article = jQuery( "article" ); aside = jQuery( "aside" ); assert.equal( article.get( 0 ).style.fontSize, "10px", "HTML5 elements are styleable" ); assert.equal( aside.length, 1, "HTML5 elements do not collapse their children" ); } ); QUnit[ includesModule( "css" ) ? "test" : "skip" ]( "HTML5 Elements inherit styles from style rules (Bug trac-10501)", function( assert ) { assert.expect( 1 ); jQuery( "#qunit-fixture" ).append( "<article id='article'></article>" ); jQuery( "#article" ).append( "<section>This section should have a pink background.</section>" ); // In IE, the missing background color will claim its value is "transparent" assert.notEqual( jQuery( "section" ).css( "background-color" ), "transparent", "HTML5 elements inherit styles" ); } ); QUnit.test( "html(String) with HTML5 (Bug trac-6485)", function( assert ) { assert.expect( 2 ); jQuery( "#qunit-fixture" ).html( "<article><section><aside>HTML5 elements</aside></section></article>" ); assert.equal( jQuery( "#qunit-fixture" ).children().children().length, 1, "Make sure HTML5 article elements can hold children. innerHTML shortcut path" ); assert.equal( jQuery( "#qunit-fixture" ).children().children().children().length, 1, "Make sure nested HTML5 elements can hold children." ); } ); QUnit.test( "html(String) tag-hyphenated elements (Bug gh-1987)", function( assert ) { assert.expect( 27 ); jQuery.each( "thead tbody tfoot colgroup caption tr th td".split( " " ), function( i, name ) { var j = jQuery( "<" + name + "-d></" + name + "-d><" + name + "-d></" + name + "-d>" ); assert.ok( j[ 0 ], "Create a tag-hyphenated element" ); assert.ok( j[ 0 ].nodeName === name.toUpperCase() + "-D", "Hyphenated node name" ); assert.ok( j[ 1 ].nodeName === name.toUpperCase() + "-D", "Hyphenated node name" ); } ); var j = jQuery( "<tr-multiple-hyphens><td-with-hyphen>text</td-with-hyphen></tr-multiple-hyphens>" ); assert.ok( j[ 0 ].nodeName === "TR-MULTIPLE-HYPHENS", "Tags with multiple hyphens" ); assert.ok( j.children()[ 0 ].nodeName === "TD-WITH-HYPHEN", "Tags with multiple hyphens" ); assert.equal( j.children().text(), "text", "Tags with multiple hyphens behave normally" ); } ); QUnit.test( "Tag name processing respects the HTML Standard (gh-2005)", function( assert ) { assert.expect( 240 ); var wrapper = jQuery( "<div></div>" ), nameTerminatingChars = "\x20\t\r\n\f".split( "" ), specialChars = "[ ] { } _ - = + \\ ( ) * & ^ % $ # @ ! ~ ` ' ; ? ¥ « µ λ ⊕ ≈ ξ ℜ ♣ €" .split( " " ); specialChars.push( specialChars.join( "" ) ); jQuery.each( specialChars, function( i, characters ) { assertSpecialCharsSupport( "html", characters ); assertSpecialCharsSupport( "append", characters ); } ); jQuery.each( nameTerminatingChars, function( i, character ) { assertNameTerminatingCharsHandling( "html", character ); assertNameTerminatingCharsHandling( "append", character ); } ); function buildChild( method, html ) { wrapper[ method ]( html ); return wrapper.children()[ 0 ]; } function assertSpecialCharsSupport( method, characters ) { var child, codepoint = characters.charCodeAt( 0 ).toString( 16 ).toUpperCase(), description = characters.length === 1 ? "U+" + ( "000" + codepoint ).slice( -4 ) + " " + characters : "all special characters", nodeName = "valid" + characters + "tagname"; child = buildChild( method, "<" + nodeName + "></" + nodeName + ">" ); assert.equal( child.nodeName.toUpperCase(), nodeName.toUpperCase(), method + "(): Paired tag name includes " + description ); child = buildChild( method, "<" + nodeName + ">" ); assert.equal( child.nodeName.toUpperCase(), nodeName.toUpperCase(), method + "(): Unpaired tag name includes " + description ); child = buildChild( method, "<" + nodeName + "/>" ); assert.equal( child.nodeName.toUpperCase(), nodeName.toUpperCase(), method + "(): Self-closing tag name includes " + description ); } function assertNameTerminatingCharsHandling( method, character ) { var child, codepoint = character.charCodeAt( 0 ).toString( 16 ).toUpperCase(), description = "U+" + ( "000" + codepoint ).slice( -4 ) + " " + character, nodeName = "div" + character + "this-will-be-discarded"; child = buildChild( method, "<" + nodeName + "></" + nodeName + ">" ); assert.equal( child.nodeName.toUpperCase(), "DIV", method + "(): Paired tag name terminated by " + description ); child = buildChild( method, "<" + nodeName + ">" ); assert.equal( child.nodeName.toUpperCase(), "DIV", method + "(): Unpaired open tag name terminated by " + description ); child = buildChild( method, "<" + nodeName + "/>" ); assert.equal( child.nodeName.toUpperCase(), "DIV", method + "(): Self-closing tag name terminated by " + description ); } } ); QUnit.test( "IE8 serialization bug", function( assert ) { assert.expect( 2 ); var wrapper = jQuery( "<div></div>" ); wrapper.html( "<div></div><article></article>" ); assert.equal( wrapper.children( "article" ).length, 1, "HTML5 elements are insertable with .html()" ); wrapper.html( "<div></div><link></link>" ); assert.equal( wrapper.children( "link" ).length, 1, "Link elements are insertable with .html()" ); } ); QUnit.test( "html() object element trac-10324", function( assert ) { assert.expect( 1 ); var object = jQuery( "<object id='object2'><param name='object2test' value='test'></param></object>?" ).appendTo( "#qunit-fixture" ), clone = object.clone(); assert.equal( clone.html(), object.html(), "html() returns correct innerhtml of cloned object elements" ); } ); QUnit.test( "append(xml)", function( assert ) { assert.expect( 1 ); var xmlDoc, xml1, xml2; function createXMLDoc() { return document.implementation.createDocument( "", "", null ); } xmlDoc = createXMLDoc(); xml1 = xmlDoc.createElement( "head" ); xml2 = xmlDoc.createElement( "test" ); assert.ok( jQuery( xml1 ).append( xml2 ), "Append an xml element to another without raising an exception." ); } ); QUnit.test( "appendTo(String)", function( assert ) { assert.expect( 4 ); var l, defaultText; defaultText = "Try them out:"; jQuery( "<b>buga</b>" ).appendTo( "#first" ); assert.equal( jQuery( "#first" ).text(), defaultText + "buga", "Check if text appending works" ); assert.equal( jQuery( "<option value='appendTest'>Append Test</option>" ).appendTo( "#select3" ).parent().find( "option:last-child" ).attr( "value" ), "appendTest", "Appending html options to select element" ); l = jQuery( "#first" ).children().length + 2; jQuery( "<strong>test</strong>" ); jQuery( "<strong>test</strong>" ); jQuery( [ jQuery( "<strong>test</strong>" )[ 0 ], jQuery( "<strong>test</strong>" )[ 0 ] ] ) .appendTo( "#first" ); assert.equal( jQuery( "#first" ).children().length, l, "Make sure the elements were inserted." ); assert.equal( jQuery( "#first" ).children().last()[ 0 ].nodeName.toLowerCase(), "strong", "Verify the last element." ); } ); QUnit.test( "appendTo(Element|Array<Element>)", function( assert ) { assert.expect( 2 ); var expected = "This link has class=\"blog\": Timmy Willison's WeblogTry them out:"; jQuery( document.getElementById( "first" ) ).appendTo( "#sap" ); assert.equal( jQuery( "#sap" ).text(), expected, "Check for appending of element" ); expected = "This link has class=\"blog\": Timmy Willison's WeblogTry them out:Yahoo"; jQuery( [ document.getElementById( "first" ), document.getElementById( "yahoo" ) ] ).appendTo( "#sap" ); assert.equal( jQuery( "#sap" ).text(), expected, "Check for appending of array of elements" ); } ); QUnit.test( "appendTo(jQuery)", function( assert ) { assert.expect( 10 ); var expected, num, div; assert.ok( jQuery( document.createElement( "script" ) ).appendTo( "body" ).length, "Make sure a disconnected script can be appended." ); expected = "This link has class=\"blog\": Timmy Willison's WeblogYahooTry them out:"; jQuery( "#yahoo, #first" ).appendTo( "#sap" ); assert.equal( jQuery( "#sap" ).text(), expected, "Check for appending of jQuery object" ); jQuery( "#select1" ).appendTo( "#foo" ); assert.t( "Append select", "#foo select", [ "select1" ] ); div = jQuery( "<div></div>" ).on( "click", function() { assert.ok( true, "Running a cloned click." ); } ); div.appendTo( "#qunit-fixture, #moretests" ); jQuery( "#qunit-fixture div" ).last().trigger( "click" ); jQuery( "#moretests div" ).last().trigger( "click" ); div = jQuery( "<div></div>" ).appendTo( "#qunit-fixture, #moretests" ); assert.equal( div.length, 2, "appendTo returns the inserted elements" ); div.addClass( "test" ); assert.ok( jQuery( "#qunit-fixture div" ).last().hasClass( "test" ), "appendTo element was modified after the insertion" ); assert.ok( jQuery( "#moretests div" ).last().hasClass( "test" ), "appendTo element was modified after the insertion" ); div = jQuery( "<div></div>" ); jQuery( "<span>a</span><b>b</b>" ).filter( "span" ).appendTo( div ); assert.equal( div.children().length, 1, "Make sure the right number of children were inserted." ); div = jQuery( "#moretests div" ); num = jQuery( "#qunit-fixture div" ).length; div.remove().appendTo( "#qunit-fixture" ); assert.equal( jQuery( "#qunit-fixture div" ).length, num, "Make sure all the removed divs were inserted." ); } ); QUnit.test( "prepend(String)", function( assert ) { assert.expect( 2 ); var result, expected; expected = "Try them out:"; result = jQuery( "#first" ).prepend( "<b>buga</b>" ); assert.equal( result.text(), "buga" + expected, "Check if text prepending works" ); assert.equal( jQuery( "#select3" ).prepend( "<option value='prependTest'>Prepend Test</option>" ).find( "option:first-child" ).attr( "value" ), "prependTest", "Prepending html options to select element" ); } ); QUnit.test( "prepend(Element)", function( assert ) { assert.expect( 1 ); var expected; expected = "Try them out:This link has class=\"blog\": Timmy Willison's Weblog"; jQuery( "#sap" ).prepend( document.getElementById( "first" ) ); assert.equal( jQuery( "#sap" ).text(), expected, "Check for prepending of element" ); } ); QUnit.test( "prepend(Array<Element>)", function( assert ) { assert.expect( 1 ); var expected; expected = "Try them out:YahooThis link has class=\"blog\": Timmy Willison's Weblog"; jQuery( "#sap" ).prepend( [ document.getElementById( "first" ), document.getElementById( "yahoo" ) ] ); assert.equal( jQuery( "#sap" ).text(), expected, "Check for prepending of array of elements" ); } ); QUnit.test( "prepend(jQuery)", function( assert ) { assert.expect( 1 ); var expected; expected = "YahooTry them out:This link has class=\"blog\": Timmy Willison's Weblog"; jQuery( "#sap" ).prepend( jQuery( "#yahoo, #first" ) ); assert.equal( jQuery( "#sap" ).text(), expected, "Check for prepending of jQuery object" ); } ); QUnit.test( "prepend(Array<jQuery>)", function( assert ) { assert.expect( 1 ); var expected; expected = "Try them out:GoogleYahooThis link has class=\"blog\": Timmy Willison's Weblog"; jQuery( "#sap" ).prepend( [ jQuery( "#first" ), jQuery( "#yahoo, #google" ) ] ); assert.equal( jQuery( "#sap" ).text(), expected, "Check for prepending of array of jQuery objects" ); } ); QUnit.test( "prepend(Function) with incoming value -- String", function( assert ) { assert.expect( 4 ); var defaultText, old, result; defaultText = "Try them out:"; old = jQuery( "#first" ).html(); result = jQuery( "#first" ).prepend( function( i, val ) { assert.equal( val, old, "Make sure the incoming value is correct." ); return "<b>buga</b>"; } ); assert.equal( result.text(), "buga" + defaultText, "Check if text prepending works" ); old = jQuery( "#select3" ).html(); assert.equal( jQuery( "#select3" ).prepend( function( i, val ) { assert.equal( val, old, "Make sure the incoming value is correct." ); return "<option value='prependTest'>Prepend Test</option>"; } ).find( "option:first-child" ).attr( "value" ), "prependTest", "Prepending html options to select element" ); } ); QUnit.test( "prepend(Function) with incoming value -- Element", function( assert ) { assert.expect( 2 ); var old, expected; expected = "Try them out:This link has class=\"blog\": Timmy Willison's Weblog"; old = jQuery( "#sap" ).html(); jQuery( "#sap" ).prepend( function( i, val ) { assert.equal( val, old, "Make sure the incoming value is correct." ); return document.getElementById( "first" ); } ); assert.equal( jQuery( "#sap" ).text(), expected, "Check for prepending of element" ); } ); QUnit.test( "prepend(Function) with incoming value -- Array<Element>", function( assert ) { assert.expect( 2 ); var old, expected; expected = "Try them out:YahooThis link has class=\"blog\": Timmy Willison's Weblog"; old = jQuery( "#sap" ).html(); jQuery( "#sap" ).prepend( function( i, val ) { assert.equal( val, old, "Make sure the incoming value is correct." ); return [ document.getElementById( "first" ), document.getElementById( "yahoo" ) ]; } ); assert.equal( jQuery( "#sap" ).text(), expected, "Check for prepending of array of elements" ); } ); QUnit.test( "prepend(Function) with incoming value -- jQuery", function( assert ) { assert.expect( 2 ); var old, expected; expected = "YahooTry them out:This link has class=\"blog\": Timmy Willison's Weblog"; old = jQuery( "#sap" ).html(); jQuery( "#sap" ).prepend( function( i, val ) { assert.equal( val, old, "Make sure the incoming value is correct." ); return jQuery( "#yahoo, #first" ); } ); assert.equal( jQuery( "#sap" ).text(), expected, "Check for prepending of jQuery object" ); } ); QUnit.test( "prependTo(String)", function( assert ) { assert.expect( 2 ); var defaultText; defaultText = "Try them out:"; jQuery( "<b>buga</b>" ).prependTo( "#first" ); assert.equal( jQuery( "#first" ).text(), "buga" + defaultText, "Check if text prepending works" ); assert.equal( jQuery( "<option value='prependTest'>Prepend Test</option>" ).prependTo( "#select3" ).parent().find( "option:first-child" ).attr( "value" ), "prependTest", "Prepending html options to select element" ); } ); QUnit.test( "prependTo(Element)", function( assert ) { assert.expect( 1 ); var expected; expected = "Try them out:This link has class=\"blog\": Timmy Willison's Weblog"; jQuery( document.getElementById( "first" ) ).prependTo( "#sap" ); assert.equal( jQuery( "#sap" ).text(), expected, "Check for prepending of element" ); } ); QUnit.test( "prependTo(Array<Element>)", function( assert ) { assert.expect( 1 ); var expected; expected = "Try them out:YahooThis link has class=\"blog\": Timmy Willison's Weblog"; jQuery( [ document.getElementById( "first" ), document.getElementById( "yahoo" ) ] ).prependTo( "#sap" ); assert.equal( jQuery( "#sap" ).text(), expected, "Check for prepending of array of elements" ); } ); QUnit.test( "prependTo(jQuery)", function( assert ) { assert.expect( 1 ); var expected; expected = "YahooTry them out:This link has class=\"blog\": Timmy Willison's Weblog"; jQuery( "#yahoo, #first" ).prependTo( "#sap" );
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
true
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/test/unit/deprecated.js
test/unit/deprecated.js
QUnit.module( "deprecated", { afterEach: moduleTeardown } ); if ( includesModule( "deprecated" ) ) { QUnit.test( "bind/unbind", function( assert ) { assert.expect( 4 ); var markup = jQuery( "<div><p><span><b>b</b></span></p></div>" ); markup .find( "b" ) .bind( "click", { bindData: 19 }, function( e, trig ) { assert.equal( e.type, "click", "correct event type" ); assert.equal( e.data.bindData, 19, "correct trigger data" ); assert.equal( trig, 42, "correct bind data" ); assert.equal( e.target.nodeName.toLowerCase(), "b", "correct element" ); } ) .trigger( "click", [ 42 ] ) .unbind( "click" ) .trigger( "click" ) .remove(); } ); QUnit.test( "delegate/undelegate", function( assert ) { assert.expect( 2 ); var markup = jQuery( "<div><p><span><b>b</b></span></p></div>" ); markup .delegate( "b", "click", function( e ) { assert.equal( e.type, "click", "correct event type" ); assert.equal( e.target.nodeName.toLowerCase(), "b", "correct element" ); } ) .find( "b" ) .trigger( "click" ) .end() .undelegate( "b", "click" ) .remove(); } ); QUnit.test( "hover() mouseenter mouseleave", function( assert ) { assert.expect( 1 ); var times = 0, handler1 = function() { ++times; }, handler2 = function() { ++times; }; jQuery( "#firstp" ) .hover( handler1, handler2 ) .mouseenter().mouseleave() .off( "mouseenter", handler1 ) .off( "mouseleave", handler2 ) .hover( handler1 ) .mouseenter().mouseleave() .off( "mouseenter mouseleave", handler1 ) .mouseenter().mouseleave(); assert.equal( times, 4, "hover handlers fired" ); } ); QUnit.test( "trigger() shortcuts", function( assert ) { assert.expect( 5 ); var counter, clickCounter, elem = jQuery( "<li><a href='#'>Change location</a></li>" ).prependTo( "#firstUL" ); elem.find( "a" ).on( "click", function() { var close = jQuery( "spanx", this ); // same with jQuery(this).find("span"); assert.equal( close.length, 0, "Context element does not exist, length must be zero" ); assert.ok( !close[ 0 ], "Context element does not exist, direct access to element must return undefined" ); return false; } ).click(); // manually clean up detached elements elem.remove(); jQuery( "#check1" ).click( function() { assert.ok( true, "click event handler for checkbox gets fired twice, see trac-815" ); } ).click(); counter = 0; jQuery( "#firstp" )[ 0 ].onclick = function() { counter++; }; jQuery( "#firstp" ).click(); assert.equal( counter, 1, "Check that click, triggers onclick event handler also" ); clickCounter = 0; jQuery( "#john1" )[ 0 ].onclick = function() { clickCounter++; }; jQuery( "#john1" ).click(); assert.equal( clickCounter, 1, "Check that click, triggers onclick event handler on an a tag also" ); } ); if ( includesModule( "ajax" ) ) { ajaxTest( "Ajax events aliases (with context)", 12, function( assert ) { var context = document.createElement( "div" ); function event( e ) { assert.equal( this, context, e.type ); } function callback( msg ) { return function() { assert.equal( this, context, "context is preserved on callback " + msg ); }; } return { setup: function() { jQuery( context ).appendTo( "#foo" ) .ajaxSend( event ) .ajaxComplete( event ) .ajaxError( event ) .ajaxSuccess( event ); }, requests: [ { url: url( "name.html" ), context: context, beforeSend: callback( "beforeSend" ), success: callback( "success" ), complete: callback( "complete" ) }, { url: url( "404.txt" ), context: context, beforeSend: callback( "beforeSend" ), error: callback( "error" ), complete: callback( "complete" ) } ] }; } ); } QUnit.test( "Event aliases", function( assert ) { // Explicitly skipping focus/blur events due to their flakiness var $elem = jQuery( "<div></div>" ).appendTo( "#qunit-fixture" ), aliases = ( "resize scroll click dblclick mousedown mouseup " + "mousemove mouseover mouseout mouseenter mouseleave change " + "select submit keydown keypress keyup contextmenu" ).split( " " ); assert.expect( aliases.length ); jQuery.each( aliases, function( i, name ) { // e.g. $(elem).click(...).click(); $elem[ name ]( function( event ) { assert.equal( event.type, name, "triggered " + name ); } )[ name ]().off( name ); } ); } ); QUnit.test( "jQuery.proxy", function( assert ) { assert.expect( 9 ); var test2, test3, test4, fn, cb, test = function() { assert.equal( this, thisObject, "Make sure that scope is set properly." ); }, thisObject = { foo: "bar", method: test }; // Make sure normal works test.call( thisObject ); // Basic scoping jQuery.proxy( test, thisObject )(); // Another take on it jQuery.proxy( thisObject, "method" )(); // Make sure it doesn't freak out assert.equal( jQuery.proxy( null, thisObject ), undefined, "Make sure no function was returned." ); // Partial application test2 = function( a ) { assert.equal( a, "pre-applied", "Ensure arguments can be pre-applied." ); }; jQuery.proxy( test2, null, "pre-applied" )(); // Partial application w/ normal arguments test3 = function( a, b ) { assert.equal( b, "normal", "Ensure arguments can be pre-applied and passed as usual." ); }; jQuery.proxy( test3, null, "pre-applied" )( "normal" ); // Test old syntax test4 = { "meth": function( a ) { assert.equal( a, "boom", "Ensure old syntax works." ); } }; jQuery.proxy( test4, "meth" )( "boom" ); // jQuery 1.9 improved currying with `this` object fn = function() { assert.equal( Array.prototype.join.call( arguments, "," ), "arg1,arg2,arg3", "args passed" ); assert.equal( this.foo, "bar", "this-object passed" ); }; cb = jQuery.proxy( fn, null, "arg1", "arg2" ); cb.call( thisObject, "arg3" ); } ); if ( includesModule( "selector" ) ) { QUnit[ QUnit.jQuerySelectors ? "test" : "skip" ]( "jQuery.expr[ \":\" ], jQuery.expr.filters", function( assert ) { assert.expect( 2 ); assert.strictEqual( jQuery.expr[ ":" ], jQuery.expr.pseudos, "jQuery.expr[ \":\" ] is an alias of jQuery.expr.pseudos" ); assert.strictEqual( jQuery.expr.filters, jQuery.expr.pseudos, "jQuery.expr.filters is an alias of jQuery.expr.pseudos" ); } ); } }
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
false
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/test/unit/dimensions.js
test/unit/dimensions.js
( function() { if ( !includesModule( "dimensions" ) ) { return; } QUnit.module( "dimensions", { afterEach: moduleTeardown } ); function pass( val ) { return val; } function fn( val ) { return function() { return val; }; } /* ======== local reference ======= pass and fn can be used to test passing functions to setters See testWidth below for an example pass( value, assert ); This function returns whatever value is passed in fn( value, assert ); Returns a function that returns the value */ function testWidth( val, assert ) { assert.expect( 9 ); var $div, $empty; $div = jQuery( "#nothiddendiv" ); $div.width( val( 30 ) ); assert.equal( $div.width(), 30, "Test set to 30 correctly" ); $div.css( "display", "none" ); assert.equal( $div.width(), 30, "Test hidden div" ); $div.css( "display", "" ); $div.width( val( -1 ) ); // handle negative numbers by setting to 0 trac-11604 assert.equal( $div.width(), 0, "Test negative width normalized to 0" ); $div.css( "padding", "20px" ); assert.equal( $div.width(), 0, "Test padding specified with pixels" ); $div.css( "border", "2px solid #fff" ); assert.equal( $div.width(), 0, "Test border specified with pixels" ); $div.css( { "display": "", "border": "", "padding": "" } ); jQuery( "#nothiddendivchild" ).css( { "width": 20, "padding": "3px", "border": "2px solid #fff" } ); assert.equal( jQuery( "#nothiddendivchild" ).width(), 20, "Test child width with border and padding" ); jQuery( "#nothiddendiv, #nothiddendivchild" ).css( { "border": "", "padding": "", "width": "" } ); $empty = jQuery(); assert.equal( $empty.width( val( 10 ) ), $empty, "Make sure that setting a width on an empty set returns the set." ); assert.strictEqual( $empty.width(), undefined, "Make sure 'undefined' is returned on an empty set" ); assert.equal( jQuery( window ).width(), document.documentElement.clientWidth, "Window width is equal to width reported by window/document." ); } QUnit.test( "width()", function( assert ) { testWidth( pass, assert ); } ); QUnit.test( "width(Function)", function( assert ) { testWidth( fn, assert ); } ); QUnit.test( "width(Function(args))", function( assert ) { assert.expect( 2 ); var $div = jQuery( "#nothiddendiv" ); $div.width( 30 ).width( function( i, width ) { assert.equal( width, 30, "Make sure previous value is correct." ); return width + 1; } ); assert.equal( $div.width(), 31, "Make sure value was modified correctly." ); } ); function testHeight( val, assert ) { assert.expect( 9 ); var $div, blah; $div = jQuery( "#nothiddendiv" ); $div.height( val( 30 ) ); assert.equal( $div.height(), 30, "Test set to 30 correctly" ); $div.css( "display", "none" ); assert.equal( $div.height(), 30, "Test hidden div" ); $div.css( "display", "" ); $div.height( val( -1 ) ); // handle negative numbers by setting to 0 trac-11604 assert.equal( $div.height(), 0, "Test negative height normalized to 0" ); $div.css( "padding", "20px" ); assert.equal( $div.height(), 0, "Test padding specified with pixels" ); $div.css( "border", "2px solid #fff" ); assert.equal( $div.height(), 0, "Test border specified with pixels" ); $div.css( { "display": "", "border": "", "padding": "", "height": "1px" } ); jQuery( "#nothiddendivchild" ).css( { "height": 20, "padding": "3px", "border": "2px solid #fff" } ); assert.equal( jQuery( "#nothiddendivchild" ).height(), 20, "Test child height with border and padding" ); jQuery( "#nothiddendiv, #nothiddendivchild" ).css( { "border": "", "padding": "", "height": "" } ); blah = jQuery( "blah" ); assert.equal( blah.height( val( 10 ) ), blah, "Make sure that setting a height on an empty set returns the set." ); assert.strictEqual( blah.height(), undefined, "Make sure 'undefined' is returned on an empty set" ); assert.equal( jQuery( window ).height(), document.documentElement.clientHeight, "Window width is equal to width reported by window/document." ); } QUnit.test( "height()", function( assert ) { testHeight( pass, assert ); } ); QUnit.test( "height(Function)", function( assert ) { testHeight( fn, assert ); } ); QUnit.test( "height(Function(args))", function( assert ) { assert.expect( 2 ); var $div = jQuery( "#nothiddendiv" ); $div.height( 30 ).height( function( i, height ) { assert.equal( height, 30, "Make sure previous value is correct." ); return height + 1; } ); assert.equal( $div.height(), 31, "Make sure value was modified correctly." ); } ); QUnit.test( "innerWidth()", function( assert ) { assert.expect( 7 ); var $div, div, $win = jQuery( window ), $doc = jQuery( document ); assert.equal( jQuery( window ).innerWidth(), $win.width(), "Test on window" ); assert.equal( jQuery( document ).innerWidth(), $doc.width(), "Test on document" ); assert.strictEqual( jQuery().innerWidth(), undefined, "Test on empty set" ); $div = jQuery( "#nothiddendiv" ); $div.css( { "margin": 10, "border": "2px solid #fff", "width": 30 } ); assert.equal( $div.innerWidth(), 30, "Test with margin and border" ); $div.css( "padding", "20px" ); assert.equal( $div.innerWidth(), 70, "Test with margin, border and padding" ); $div.css( "display", "none" ); assert.equal( $div.innerWidth(), 70, "Test hidden div" ); // reset styles $div.css( { "display": "", "border": "", "padding": "", "width": "", "height": "" } ); div = jQuery( "<div>" ); // Temporarily require 0 for backwards compat - should be auto assert.equal( div.innerWidth(), 0, "Make sure that disconnected nodes are handled." ); div.remove(); } ); QUnit.test( "innerHeight()", function( assert ) { assert.expect( 7 ); var $div, div, $win = jQuery( window ), $doc = jQuery( document ); assert.equal( jQuery( window ).innerHeight(), $win.height(), "Test on window" ); assert.equal( jQuery( document ).innerHeight(), $doc.height(), "Test on document" ); assert.strictEqual( jQuery().innerHeight(), undefined, "Test on empty set" ); $div = jQuery( "#nothiddendiv" ); $div.css( { "margin": 10, "border": "2px solid #fff", "height": 30 } ); assert.equal( $div.innerHeight(), 30, "Test with margin and border" ); $div.css( "padding", "20px" ); assert.equal( $div.innerHeight(), 70, "Test with margin, border and padding" ); $div.css( "display", "none" ); assert.equal( $div.innerHeight(), 70, "Test hidden div" ); // reset styles $div.css( { "display": "", "border": "", "padding": "", "width": "", "height": "" } ); div = jQuery( "<div>" ); // Temporarily require 0 for backwards compat - should be auto assert.equal( div.innerHeight(), 0, "Make sure that disconnected nodes are handled." ); div.remove(); } ); QUnit.test( "outerWidth()", function( assert ) { assert.expect( 12 ); var $div, div, $win = jQuery( window ), $doc = jQuery( document ), winwidth = $win.prop( "innerWidth" ); assert.equal( jQuery( window ).outerWidth(), winwidth, "Test on window without margin option" ); assert.equal( jQuery( window ).outerWidth( true ), winwidth, "Test on window with margin option" ); assert.equal( jQuery( document ).outerWidth(), $doc.width(), "Test on document without margin option" ); assert.equal( jQuery( document ).outerWidth( true ), $doc.width(), "Test on document with margin option" ); assert.strictEqual( jQuery().outerWidth(), undefined, "Test on empty set" ); $div = jQuery( "#nothiddendiv" ); $div.css( "width", 30 ); assert.equal( $div.outerWidth(), 30, "Test with only width set" ); $div.css( "padding", "20px" ); assert.equal( $div.outerWidth(), 70, "Test with padding" ); $div.css( "border", "2px solid #fff" ); assert.equal( $div.outerWidth(), 74, "Test with padding and border" ); $div.css( "margin", "10px" ); assert.equal( $div.outerWidth(), 74, "Test with padding, border and margin without margin option" ); $div.css( "position", "absolute" ); assert.equal( $div.outerWidth( true ), 94, "Test with padding, border and margin with margin option" ); $div.css( "display", "none" ); assert.equal( $div.outerWidth( true ), 94, "Test hidden div with padding, border and margin with margin option" ); // reset styles $div.css( { "position": "", "display": "", "border": "", "padding": "", "width": "", "height": "" } ); div = jQuery( "<div>" ); // Temporarily require 0 for backwards compat - should be auto assert.equal( div.outerWidth(), 0, "Make sure that disconnected nodes are handled." ); div.remove(); } ); QUnit.test( "outerHeight()", function( assert ) { assert.expect( 14 ); var $div, div, $win = jQuery( window ), $doc = jQuery( document ), winheight = $win.prop( "innerHeight" ); assert.equal( jQuery( window ).outerHeight(), winheight, "Test on window without margin option" ); assert.equal( jQuery( window ).outerHeight( true ), winheight, "Test on window with margin option" ); assert.equal( jQuery( document ).outerHeight(), $doc.height(), "Test on document without margin option" ); assert.equal( jQuery( document ).outerHeight( true ), $doc.height(), "Test on document with margin option" ); assert.strictEqual( jQuery().outerHeight(), undefined, "Test on empty set" ); $div = jQuery( "#nothiddendiv" ); $div.css( "height", 30 ); assert.equal( $div.outerHeight(), 30, "Test with only height set" ); $div.css( "padding", "20px" ); assert.equal( $div.outerHeight(), 70, "Test with padding" ); $div.css( "border", "2px solid #fff" ); assert.equal( $div.outerHeight(), 74, "Test with padding and border" ); $div.css( "margin", "10px" ); assert.equal( $div.outerHeight(), 74, "Test with padding, border and margin without margin option" ); $div.css( "position", "absolute" ); assert.equal( $div.outerHeight( true ), 94, "Test with padding, border and margin with margin option" ); $div.css( "display", "none" ); assert.equal( $div.outerHeight( true ), 94, "Test hidden div with padding, border and margin with margin option" ); $div.css( "display", "" ); $div.css( "margin", "-10px" ); assert.equal( $div.outerHeight(), 74, "Test with padding, border and negative margin without margin option" ); assert.equal( $div.outerHeight( true ), 54, "Test with padding, border and negative margin with margin option" ); // reset styles $div.css( { "position": "", "display": "", "border": "", "padding": "", "width": "", "height": "" } ); div = jQuery( "<div>" ); // Temporarily require 0 for backwards compat - should be auto assert.equal( div.outerWidth(), 0, "Make sure that disconnected nodes are handled." ); div.remove(); } ); QUnit.test( "fractional getters", function( assert ) { assert.expect( 8 ); var elem = jQuery( "<div>" ).css( { width: "10.5px", height: "20.5px", border: "10px solid white", padding: "2px", margin: "3px" } ); elem.appendTo( "#qunit-fixture" ); assert.strictEqual( elem.width(), 10.5, "width supports fractions" ); assert.strictEqual( elem.innerWidth(), 14.5, "innerWidth supports fractions" ); assert.strictEqual( elem.outerWidth(), 34.5, "outerWidth supports fractions" ); assert.strictEqual( elem.outerWidth( true ), 40.5, "outerWidth( true ) supports fractions" ); assert.strictEqual( elem.height(), 20.5, "height supports fractions" ); assert.strictEqual( elem.innerHeight(), 24.5, "innerHeight supports fractions" ); assert.strictEqual( elem.outerHeight(), 44.5, "outerHeight supports fractions" ); assert.strictEqual( elem.outerHeight( true ), 50.5, "outerHeight( true ) supports fractions" ); } ); QUnit.test( "child of a hidden elem (or unconnected node) has accurate inner/outer/Width()/Height() see trac-9441 trac-9300", function( assert ) { assert.expect( 16 ); // setup html var $divNormal = jQuery( "<div>" ).css( { "width": "100px", "height": "100px", "border": "10px solid white", "padding": "2px", "margin": "3px" } ), $divChild = $divNormal.clone(), $divUnconnected = $divNormal.clone(), $divHiddenParent = jQuery( "<div>" ).css( "display", "none" ).append( $divChild ).appendTo( "body" ); $divNormal.appendTo( "body" ); // tests that child div of a hidden div works the same as a normal div assert.equal( $divChild.width(), $divNormal.width(), "child of a hidden element width() is wrong see trac-9441" ); assert.equal( $divChild.innerWidth(), $divNormal.innerWidth(), "child of a hidden element innerWidth() is wrong see trac-9441" ); assert.equal( $divChild.outerWidth(), $divNormal.outerWidth(), "child of a hidden element outerWidth() is wrong see trac-9441" ); assert.equal( $divChild.outerWidth( true ), $divNormal.outerWidth( true ), "child of a hidden element outerWidth( true ) is wrong see trac-9300" ); assert.equal( $divChild.height(), $divNormal.height(), "child of a hidden element height() is wrong see trac-9441" ); assert.equal( $divChild.innerHeight(), $divNormal.innerHeight(), "child of a hidden element innerHeight() is wrong see trac-9441" ); assert.equal( $divChild.outerHeight(), $divNormal.outerHeight(), "child of a hidden element outerHeight() is wrong see trac-9441" ); assert.equal( $divChild.outerHeight( true ), $divNormal.outerHeight( true ), "child of a hidden element outerHeight( true ) is wrong see trac-9300" ); // tests that child div of an unconnected div works the same as a normal div assert.equal( $divUnconnected.width(), $divNormal.width(), "unconnected element width() is wrong see trac-9441" ); assert.equal( $divUnconnected.innerWidth(), $divNormal.innerWidth(), "unconnected element innerWidth() is wrong see trac-9441" ); assert.equal( $divUnconnected.outerWidth(), $divNormal.outerWidth(), "unconnected element outerWidth() is wrong see trac-9441" ); assert.equal( $divUnconnected.outerWidth( true ), $divNormal.outerWidth( true ), "unconnected element outerWidth( true ) is wrong see trac-9300" ); assert.equal( $divUnconnected.height(), $divNormal.height(), "unconnected element height() is wrong see trac-9441" ); assert.equal( $divUnconnected.innerHeight(), $divNormal.innerHeight(), "unconnected element innerHeight() is wrong see trac-9441" ); assert.equal( $divUnconnected.outerHeight(), $divNormal.outerHeight(), "unconnected element outerHeight() is wrong see trac-9441" ); assert.equal( $divUnconnected.outerHeight( true ), $divNormal.outerHeight( true ), "unconnected element outerHeight( true ) is wrong see trac-9300" ); // teardown html $divHiddenParent.remove(); $divNormal.remove(); } ); QUnit.test( "hidden element with dimensions from a stylesheet", function( assert ) { assert.expect( 2 ); var div = jQuery( "" + "<div class='display-none-style'>" + " <style>" + " .display-none-style {" + " display: none;" + " width: 111px;" + " height: 123px;" + " }" + " </style>" + "</div>" + "" ) .appendTo( "#qunit-fixture" ); assert.strictEqual( div.width(), 111, "width of a hidden element" ); assert.strictEqual( div.height(), 123, "height of a hidden element" ); } ); QUnit.test( "hidden element with implicit content-based dimensions", function( assert ) { assert.expect( 2 ); var container = jQuery( "" + // font-size affects the child dimensions implicitly "<div style='font-size: 20px'>" + " <div style='padding: 10px; display: none'>" + " <div style='width: 3em; height: 2em'></div>" + " </div>" + "</div>" + "" ), div = container.children().first(); container.appendTo( "#qunit-fixture" ); assert.strictEqual( div.width(), 60, "width of a hidden element" ); assert.strictEqual( div.height(), 40, "height of a hidden element" ); } ); QUnit.test( "table dimensions", function( assert ) { assert.expect( 3 ); var table = jQuery( "" + "<table style='border-spacing: 0'>" + " <colgroup>" + " <col />" + " <col span='2' class='col-double' />" + " </colgroup>" + " <tbody>" + " <tr>" + " <td></td>" + " <td class='td-a-1'>a</td>" + " <td class='td-b-1'>b</td>" + " </tr>" + " <tr>" + " <td></td>" + " <td>a</td>" + " <td>b</td>" + " </tr>" + " </tbody>" + "</table>" ).appendTo( "#qunit-fixture" ), tdElem = table.find( "td" ).first(), colElem = table.find( "col" ).first(), doubleColElem = table.find( ".col-double" ); table.find( "td" ).css( { margin: 0, padding: 0, border: 0 } ); colElem.width( 300 ); table.find( ".td-a-1" ).width( 200 ); table.find( ".td-b-1" ).width( 400 ); assert.equal( tdElem.width(), tdElem.width(), "width() doesn't alter dimension values of empty cells, see trac-11293" ); assert.equal( colElem.width(), 300, "col elements have width(), (trac-12243)" ); // Support: IE 11+ // In IE, `<col>` computed width is `"auto"` unless `width` is set // explicitly via CSS so measurements there remain incorrect. Because of // the lack of a proper workaround, we accept this limitation. // To make IE pass the test, set the width explicitly. if ( QUnit.isIE ) { doubleColElem.width( 600 ); } assert.equal( doubleColElem.width(), 600, "col with span measured correctly (gh-5628)" ); } ); QUnit.test( "SVG dimensions (basic content-box)", function( assert ) { assert.expect( 8 ); var svg = jQuery( "<svg style='width: 100px; height: 100px;'></svg>" ).appendTo( "#qunit-fixture" ); assert.equal( svg.width(), 100 ); assert.equal( svg.height(), 100 ); assert.equal( svg.innerWidth(), 100 ); assert.equal( svg.innerHeight(), 100 ); assert.equal( svg.outerWidth(), 100 ); assert.equal( svg.outerHeight(), 100 ); assert.equal( svg.outerWidth( true ), 100 ); assert.equal( svg.outerHeight( true ), 100 ); svg.remove(); } ); QUnit.test( "SVG dimensions (content-box)", function( assert ) { assert.expect( 8 ); var svg = jQuery( "<svg style='width: 100px; height: 100px; box-sizing: content-box; border: 1px solid white; padding: 2px; margin: 3px'></svg>" ).appendTo( "#qunit-fixture" ); assert.equal( svg.width(), 100 ); assert.equal( svg.height(), 100 ); assert.equal( svg.innerWidth(), 104 ); assert.equal( svg.innerHeight(), 104 ); assert.equal( svg.outerWidth(), 106 ); assert.equal( svg.outerHeight(), 106 ); assert.equal( svg.outerWidth( true ), 112 ); assert.equal( svg.outerHeight( true ), 112 ); svg.remove(); } ); QUnit.test( "SVG dimensions (border-box)", function( assert ) { assert.expect( 8 ); var svg = jQuery( "<svg style='width: 100px; height: 100px; box-sizing: border-box; border: 1px solid white; padding: 2px; margin: 3px'></svg>" ).appendTo( "#qunit-fixture" ); assert.equal( svg.width(), 94, "width" ); assert.equal( svg.height(), 94, "height" ); assert.equal( svg.innerWidth(), 98, "innerWidth" ); assert.equal( svg.innerHeight(), 98, "innerHeight" ); assert.equal( svg.outerWidth(), 100, "outerWidth" ); assert.equal( svg.outerHeight(), 100, "outerHeight" ); assert.equal( svg.outerWidth( true ), 106, "outerWidth( true )" ); assert.equal( svg.outerHeight( true ), 106, "outerHeight( true )" ); svg.remove(); } ); QUnit.test( "box-sizing:border-box child of a hidden elem (or unconnected node) has accurate inner/outer/Width()/Height() see trac-10413", function( assert ) { assert.expect( 16 ); // setup html var $divNormal = jQuery( "<div>" ).css( { "boxSizing": "border-box", "width": "100px", "height": "100px", "border": "10px solid white", "padding": "2px", "margin": "3px" } ), $divChild = $divNormal.clone(), $divUnconnected = $divNormal.clone(), $divHiddenParent = jQuery( "<div>" ).css( "display", "none" ).append( $divChild ).appendTo( "body" ); $divNormal.appendTo( "body" ); // tests that child div of a hidden div works the same as a normal div assert.equal( $divChild.width(), $divNormal.width(), "child of a hidden element width() is wrong see trac-10413" ); assert.equal( $divChild.innerWidth(), $divNormal.innerWidth(), "child of a hidden element innerWidth() is wrong see trac-10413" ); assert.equal( $divChild.outerWidth(), $divNormal.outerWidth(), "child of a hidden element outerWidth() is wrong see trac-10413" ); assert.equal( $divChild.outerWidth( true ), $divNormal.outerWidth( true ), "child of a hidden element outerWidth( true ) is wrong see trac-10413" ); assert.equal( $divChild.height(), $divNormal.height(), "child of a hidden element height() is wrong see trac-10413" ); assert.equal( $divChild.innerHeight(), $divNormal.innerHeight(), "child of a hidden element innerHeight() is wrong see trac-10413" ); assert.equal( $divChild.outerHeight(), $divNormal.outerHeight(), "child of a hidden element outerHeight() is wrong see trac-10413" ); assert.equal( $divChild.outerHeight( true ), $divNormal.outerHeight( true ), "child of a hidden element outerHeight( true ) is wrong see trac-10413" ); // tests that child div of an unconnected div works the same as a normal div assert.equal( $divUnconnected.width(), $divNormal.width(), "unconnected element width() is wrong see trac-10413" ); assert.equal( $divUnconnected.innerWidth(), $divNormal.innerWidth(), "unconnected element innerWidth() is wrong see trac-10413" ); assert.equal( $divUnconnected.outerWidth(), $divNormal.outerWidth(), "unconnected element outerWidth() is wrong see trac-10413" ); assert.equal( $divUnconnected.outerWidth( true ), $divNormal.outerWidth( true ), "unconnected element outerWidth( true ) is wrong see trac-10413" ); assert.equal( $divUnconnected.height(), $divNormal.height(), "unconnected element height() is wrong see trac-10413" ); assert.equal( $divUnconnected.innerHeight(), $divNormal.innerHeight(), "unconnected element innerHeight() is wrong see trac-10413" ); assert.equal( $divUnconnected.outerHeight(), $divNormal.outerHeight(), "unconnected element outerHeight() is wrong see trac-10413" ); assert.equal( $divUnconnected.outerHeight( true ), $divNormal.outerHeight( true ), "unconnected element outerHeight( true ) is wrong see trac-10413" ); // teardown html $divHiddenParent.remove(); $divNormal.remove(); } ); QUnit.test( "passing undefined is a setter trac-5571", function( assert ) { assert.expect( 4 ); assert.equal( jQuery( "#nothiddendiv" ).height( 30 ).height( undefined ).height(), 30, ".height(undefined) is chainable (trac-5571)" ); assert.equal( jQuery( "#nothiddendiv" ).height( 30 ).innerHeight( undefined ).height(), 30, ".innerHeight(undefined) is chainable (trac-5571)" ); assert.equal( jQuery( "#nothiddendiv" ).height( 30 ).outerHeight( undefined ).height(), 30, ".outerHeight(undefined) is chainable (trac-5571)" ); assert.equal( jQuery( "#nothiddendiv" ).width( 30 ).width( undefined ).width(), 30, ".width(undefined) is chainable (trac-5571)" ); } ); QUnit.test( "setters with and without box-sizing:border-box", function( assert ) { assert.expect( 120 ); var parent = jQuery( "#foo" ).css( { width: "200px", height: "200px", "font-size": "16px" } ), el_bb = jQuery( "<div style='margin:5px;padding:1px;border:2px solid black;box-sizing:border-box;'></div>" ).appendTo( parent ), el = jQuery( "<div style='margin:5px;padding:1px;border:2px solid black;'></div>" ).appendTo( parent ), el_bb_np = jQuery( "<div style='margin:5px; padding:0px; border:0px solid green;box-sizing:border-box;'></div>" ).appendTo( parent ), el_np = jQuery( "<div style='margin:5px; padding:0px; border:0px solid green;'></div>" ).appendTo( parent ); jQuery.each( { "number": { set: 100, expected: 100 }, "em": { set: "10em", expected: 160 }, "percentage": { set: "50%", expected: 100 } }, function( units, values ) { assert.equal( el_bb.width( values.set ).width(), values.expected, "test border-box width(" + units + ") by roundtripping" ); assert.equal( el_bb.innerWidth( values.set ).width(), values.expected - 2, "test border-box innerWidth(" + units + ") by roundtripping" ); assert.equal( el_bb.outerWidth( values.set ).width(), values.expected - 6, "test border-box outerWidth(" + units + ") by roundtripping" ); assert.equal( el_bb.outerWidth( values.set, false ).width(), values.expected - 6, "test border-box outerWidth(" + units + ", false) by roundtripping" ); assert.equal( el_bb.outerWidth( values.set, true ).width(), values.expected - 16, "test border-box outerWidth(" + units + ", true) by roundtripping" ); assert.equal( el_bb.height( values.set ).height(), values.expected, "test border-box height(" + units + ") by roundtripping" ); assert.equal( el_bb.innerHeight( values.set ).height(), values.expected - 2, "test border-box innerHeight(" + units + ") by roundtripping" ); assert.equal( el_bb.outerHeight( values.set ).height(), values.expected - 6, "test border-box outerHeight(" + units + ") by roundtripping" ); assert.equal( el_bb.outerHeight( values.set, false ).height(), values.expected - 6, "test border-box outerHeight(" + units + ", false) by roundtripping" ); assert.equal( el_bb.outerHeight( values.set, true ).height(), values.expected - 16, "test border-box outerHeight(" + units + ", true) by roundtripping" ); assert.equal( el.width( values.set ).width(), values.expected, "test non-border-box width(" + units + ") by roundtripping" ); assert.equal( el.innerWidth( values.set ).width(), values.expected - 2, "test non-border-box innerWidth(" + units + ") by roundtripping" ); assert.equal( el.outerWidth( values.set ).width(), values.expected - 6, "test non-border-box outerWidth(" + units + ") by roundtripping" ); assert.equal( el.outerWidth( values.set, false ).width(), values.expected - 6, "test non-border-box outerWidth(" + units + ", false) by roundtripping" ); assert.equal( el.outerWidth( values.set, true ).width(), values.expected - 16, "test non-border-box outerWidth(" + units + ", true) by roundtripping" ); assert.equal( el.height( values.set ).height(), values.expected, "test non-border-box height(" + units + ") by roundtripping" ); assert.equal( el.innerHeight( values.set ).height(), values.expected - 2, "test non-border-box innerHeight(" + units + ") by roundtripping" ); assert.equal( el.outerHeight( values.set ).height(), values.expected - 6, "test non-border-box outerHeight(" + units + ") by roundtripping" ); assert.equal( el.outerHeight( values.set, false ).height(), values.expected - 6, "test non-border-box outerHeight(" + units + ", false) by roundtripping" ); assert.equal( el.outerHeight( values.set, true ).height(), values.expected - 16, "test non-border-box outerHeight(" + units + ", true) by roundtripping" ); assert.equal( el_bb_np.width( values.set ).width(), values.expected, "test border-box width and negative padding(" + units + ") by roundtripping" ); assert.equal( el_bb_np.innerWidth( values.set ).width(), values.expected, "test border-box innerWidth and negative padding(" + units + ") by roundtripping" ); assert.equal( el_bb_np.outerWidth( values.set ).width(), values.expected, "test border-box outerWidth and negative padding(" + units + ") by roundtripping" ); assert.equal( el_bb_np.outerWidth( values.set, false ).width(), values.expected, "test border-box outerWidth and negative padding(" + units + ", false) by roundtripping" ); assert.equal( el_bb_np.outerWidth( values.set, true ).width(), values.expected - 10, "test border-box outerWidth and negative padding(" + units + ", true) by roundtripping" ); assert.equal( el_bb_np.height( values.set ).height(), values.expected, "test border-box height and negative padding(" + units + ") by roundtripping" ); assert.equal( el_bb_np.innerHeight( values.set ).height(), values.expected, "test border-box innerHeight and negative padding(" + units + ") by roundtripping" ); assert.equal( el_bb_np.outerHeight( values.set ).height(), values.expected, "test border-box outerHeight and negative padding(" + units + ") by roundtripping" ); assert.equal( el_bb_np.outerHeight( values.set, false ).height(), values.expected, "test border-box outerHeight and negative padding(" + units + ", false) by roundtripping" ); assert.equal( el_bb_np.outerHeight( values.set, true ).height(), values.expected - 10, "test border-box outerHeight and negative padding(" + units + ", true) by roundtripping" ); assert.equal( el_np.width( values.set ).width(), values.expected, "test non-border-box width and negative padding(" + units + ") by roundtripping" ); assert.equal( el_np.innerWidth( values.set ).width(), values.expected, "test non-border-box innerWidth and negative padding(" + units + ") by roundtripping" ); assert.equal( el_np.outerWidth( values.set ).width(), values.expected, "test non-border-box outerWidth and negative padding(" + units + ") by roundtripping" ); assert.equal( el_np.outerWidth( values.set, false ).width(), values.expected, "test non-border-box outerWidth and negative padding(" + units + ", false) by roundtripping" ); assert.equal( el_np.outerWidth( values.set, true ).width(), values.expected - 10, "test non-border-box outerWidth and negative padding(" + units + ", true) by roundtripping" ); assert.equal( el_np.height( values.set ).height(), values.expected, "test non-border-box height and negative padding(" + units + ") by roundtripping" ); assert.equal( el_np.innerHeight( values.set ).height(), values.expected, "test non-border-box innerHeight and negative padding(" + units + ") by roundtripping" ); assert.equal( el_np.outerHeight( values.set ).height(), values.expected, "test non-border-box outerHeight and negative padding(" + units + ") by roundtripping" ); assert.equal( el_np.outerHeight( values.set, false ).height(), values.expected, "test non-border-box outerHeight and negative padding(" + units + ", false) by roundtripping" ); assert.equal( el_np.outerHeight( values.set, true ).height(), values.expected - 10, "test non-border-box outerHeight and negative padding(" + units + ", true) by roundtripping" ); } ); } ); testIframe( "window vs. large document", "dimensions/documentLarge.html", function( assert, jQuery, window, document ) { assert.expect( 2 ); assert.ok( jQuery( document ).height() > jQuery( window ).height(), "document height is larger than window height" ); assert.ok( jQuery( document ).width() > jQuery( window ).width(), "document width is larger than window width" ); } ); QUnit.test( "allow modification of coordinates argument (gh-1848)", function( assert ) { assert.expect( 1 ); var offsetTop, element = jQuery( "<div></div>" ).appendTo( "#qunit-fixture" ); element.offset( function( index, coords ) { coords.top = 100; return coords; } ); offsetTop = element.offset().top; assert.ok( Math.abs( offsetTop - 100 ) < 0.02, "coordinates are modified (got offset.top: " + offsetTop + ")" ); } ); QUnit.test( "outside view position (gh-2836)", function( assert ) { // This test ported from gh-2836 example assert.expect( 1 ); var parent, pos, html = [ "<div id=div-gh-2836>", "<div></div>", "<div></div>", "<div></div>", "<div></div>", "<div></div>", "</div>" ].join( "" ); parent = jQuery( html ); parent.appendTo( "#qunit-fixture" ); parent.scrollTop( 400 ); pos = parent.find( "div" ).eq( 3 ).position(); assert.strictEqual( pos.top, -100 ); } ); QUnit.test( "width/height on element with transform (gh-3193)", function( assert ) { assert.expect( 2 ); var $elem = jQuery( "<div style='width: 200px; height: 200px; transform: scale(2);'></div>" ) .appendTo( "#qunit-fixture" ); assert.equal( $elem.width(), 200, "Width ignores transforms" ); assert.equal( $elem.height(), 200, "Height ignores transforms" ); } ); QUnit.test( "width/height on an inline element with no explicitly-set dimensions (gh-3571)", function( assert ) { assert.expect( 8 ); var $elem = jQuery( "<span style='border: 2px solid black;padding: 1px;margin: 3px;'>Hello, I'm some text.</span>" ).appendTo( "#qunit-fixture" ); jQuery.each( [ "Width", "Height" ], function( i, method ) { var val = $elem[ method.toLowerCase() ](); assert.notEqual( val, 0, method + " should not be zero on inline element." ); assert.equal( $elem[ "inner" + method ](), val + 2, "inner" + method + " should include padding" ); assert.equal( $elem[ "outer" + method ](), val + 6, "outer" + method + " should include padding and border" ); assert.equal( $elem[ "outer" + method ]( true ), val + 12, "outer" + method + "(true) should include padding, border, and margin" ); } ); } ); QUnit.test( "width/height on an inline element with percentage dimensions (gh-3611)", function( assert ) { assert.expect( 4 ); jQuery( "<div id='gh3611' style='width: 100px;'>" + "<span style='width: 100%; padding: 0 5px'>text</span>" + "</div>" ).appendTo( "#qunit-fixture" ); var $elem = jQuery( "#gh3611 span" ), actualWidth = $elem[ 0 ].getBoundingClientRect().width, marginWidth = $elem.outerWidth( true ), borderWidth = $elem.outerWidth(), paddingWidth = $elem.innerWidth(), contentWidth = $elem.width(); assert.equal( Math.round( borderWidth ), Math.round( actualWidth ),
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
true
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/test/unit/exports.js
test/unit/exports.js
QUnit.module( "exports", { afterEach: moduleTeardown } ); QUnit.test( "amdModule", function( assert ) { assert.expect( 1 ); assert.equal( jQuery, amdDefined, "Make sure defined module matches jQuery" ); } );
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
false
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/test/unit/deferred.js
test/unit/deferred.js
QUnit.module( "deferred", { afterEach: moduleTeardown } ); ( function() { if ( !includesModule( "deferred" ) ) { return; } jQuery.each( [ "", " - new operator" ], function( _, withNew ) { function createDeferred( fn ) { return withNew ? new jQuery.Deferred( fn ) : jQuery.Deferred( fn ); } QUnit.test( "jQuery.Deferred" + withNew, function( assert ) { assert.expect( 23 ); var defer = createDeferred(); assert.ok( typeof defer.pipe === "function", "defer.pipe is a function" ); defer.resolve().done( function() { assert.ok( true, "Success on resolve" ); assert.strictEqual( defer.state(), "resolved", "Deferred is resolved (state)" ); } ).fail( function() { assert.ok( false, "Error on resolve" ); } ).always( function() { assert.ok( true, "Always callback on resolve" ); } ); defer = createDeferred(); defer.reject().done( function() { assert.ok( false, "Success on reject" ); } ).fail( function() { assert.ok( true, "Error on reject" ); assert.strictEqual( defer.state(), "rejected", "Deferred is rejected (state)" ); } ).always( function() { assert.ok( true, "Always callback on reject" ); } ); createDeferred( function( defer ) { assert.ok( this === defer, "Defer passed as this & first argument" ); this.resolve( "done" ); } ).done( function( value ) { assert.strictEqual( value, "done", "Passed function executed" ); } ); createDeferred( function( defer ) { var promise = defer.promise(), func = function() {}, funcPromise = defer.promise( func ); assert.strictEqual( defer.promise(), promise, "promise is always the same" ); assert.strictEqual( funcPromise, func, "non objects get extended" ); jQuery.each( promise, function( key ) { if ( typeof promise[ key ] !== "function" ) { assert.ok( false, key + " is a function (" + typeof( promise[ key ] ) + ")" ); } if ( promise[ key ] !== func[ key ] ) { assert.strictEqual( func[ key ], promise[ key ], key + " is the same" ); } } ); } ); jQuery.expandedEach = jQuery.each; jQuery.expandedEach( "resolve reject".split( " " ), function( _, change ) { createDeferred( function( defer ) { assert.strictEqual( defer.state(), "pending", "pending after creation" ); var checked = 0; defer.progress( function( value ) { assert.strictEqual( value, checked, "Progress: right value (" + value + ") received" ); } ); for ( checked = 0; checked < 3; checked++ ) { defer.notify( checked ); } assert.strictEqual( defer.state(), "pending", "pending after notification" ); defer[ change ](); assert.notStrictEqual( defer.state(), "pending", "not pending after " + change ); defer.notify(); } ); } ); } ); } ); QUnit.test( "jQuery.Deferred - chainability", function( assert ) { var defer = jQuery.Deferred(); assert.expect( 10 ); jQuery.expandedEach = jQuery.each; jQuery.expandedEach( "resolve reject notify resolveWith rejectWith notifyWith done fail progress always".split( " " ), function( _, method ) { var object = { m: defer[ method ] }; assert.strictEqual( object.m(), object, method + " is chainable" ); } ); } ); QUnit.test( "jQuery.Deferred.then - filtering (done)", function( assert ) { assert.expect( 4 ); var value1, value2, value3, defer = jQuery.Deferred(), piped = defer.then( function( a, b ) { return a * b; } ), done = jQuery.map( new Array( 3 ), function() { return assert.async(); } ); piped.done( function( result ) { value3 = result; } ); defer.done( function( a, b ) { value1 = a; value2 = b; } ); defer.resolve( 2, 3 ).then( function() { assert.strictEqual( value1, 2, "first resolve value ok" ); assert.strictEqual( value2, 3, "second resolve value ok" ); assert.strictEqual( value3, 6, "result of filter ok" ); done.pop().call(); } ); jQuery.Deferred().reject().then( function() { assert.ok( false, "then should not be called on reject" ); } ).then( null, done.pop() ); jQuery.Deferred().resolve().then( jQuery.noop ).done( function( value ) { assert.strictEqual( value, undefined, "then done callback can return undefined/null" ); done.pop().call(); } ); } ); QUnit.test( "jQuery.Deferred.then - filtering (fail)", function( assert ) { assert.expect( 4 ); var value1, value2, value3, defer = jQuery.Deferred(), piped = defer.then( null, function( a, b ) { return a * b; } ), done = jQuery.map( new Array( 3 ), function() { return assert.async(); } ); piped.done( function( result ) { value3 = result; } ); defer.fail( function( a, b ) { value1 = a; value2 = b; } ); defer.reject( 2, 3 ).then( null, function() { assert.strictEqual( value1, 2, "first reject value ok" ); assert.strictEqual( value2, 3, "second reject value ok" ); assert.strictEqual( value3, 6, "result of filter ok" ); done.pop().call(); } ); jQuery.Deferred().resolve().then( null, function() { assert.ok( false, "then should not be called on resolve" ); } ).then( done.pop() ); jQuery.Deferred().reject().then( null, jQuery.noop ).done( function( value ) { assert.strictEqual( value, undefined, "then fail callback can return undefined/null" ); done.pop().call(); } ); } ); QUnit.test( "jQuery.Deferred.catch", function( assert ) { assert.expect( 4 ); var value1, value2, value3, defer = jQuery.Deferred(), piped = defer.catch( function( a, b ) { return a * b; } ), done = jQuery.map( new Array( 3 ), function() { return assert.async(); } ); piped.done( function( result ) { value3 = result; } ); defer.fail( function( a, b ) { value1 = a; value2 = b; } ); defer.reject( 2, 3 ).catch( function() { assert.strictEqual( value1, 2, "first reject value ok" ); assert.strictEqual( value2, 3, "second reject value ok" ); assert.strictEqual( value3, 6, "result of filter ok" ); done.pop().call(); } ); jQuery.Deferred().resolve().catch( function() { assert.ok( false, "then should not be called on resolve" ); } ).then( done.pop() ); jQuery.Deferred().reject().catch( jQuery.noop ).done( function( value ) { assert.strictEqual( value, undefined, "then fail callback can return undefined/null" ); done.pop().call(); } ); } ); QUnit.test( "[PIPE ONLY] jQuery.Deferred.pipe - filtering (fail)", function( assert ) { assert.expect( 4 ); var value1, value2, value3, defer = jQuery.Deferred(), piped = defer.pipe( null, function( a, b ) { return a * b; } ), done = jQuery.map( new Array( 3 ), function() { return assert.async(); } ); piped.fail( function( result ) { value3 = result; } ); defer.fail( function( a, b ) { value1 = a; value2 = b; } ); defer.reject( 2, 3 ).pipe( null, function() { assert.strictEqual( value1, 2, "first reject value ok" ); assert.strictEqual( value2, 3, "second reject value ok" ); assert.strictEqual( value3, 6, "result of filter ok" ); done.pop().call(); } ); jQuery.Deferred().resolve().pipe( null, function() { assert.ok( false, "then should not be called on resolve" ); } ).then( done.pop() ); jQuery.Deferred().reject().pipe( null, jQuery.noop ).fail( function( value ) { assert.strictEqual( value, undefined, "then fail callback can return undefined/null" ); done.pop().call(); } ); } ); QUnit.test( "jQuery.Deferred.then - filtering (progress)", function( assert ) { assert.expect( 3 ); var value1, value2, value3, defer = jQuery.Deferred(), piped = defer.then( null, null, function( a, b ) { return a * b; } ), done = assert.async(); piped.progress( function( result ) { value3 = result; } ); defer.progress( function( a, b ) { value1 = a; value2 = b; } ); defer.notify( 2, 3 ).then( null, null, function() { assert.strictEqual( value1, 2, "first progress value ok" ); assert.strictEqual( value2, 3, "second progress value ok" ); assert.strictEqual( value3, 6, "result of filter ok" ); done(); } ); } ); QUnit.test( "jQuery.Deferred.then - deferred (done)", function( assert ) { assert.expect( 3 ); var value1, value2, value3, defer = jQuery.Deferred(), piped = defer.then( function( a, b ) { return jQuery.Deferred( function( defer ) { defer.reject( a * b ); } ); } ), done = assert.async(); piped.fail( function( result ) { value3 = result; } ); defer.done( function( a, b ) { value1 = a; value2 = b; } ); defer.resolve( 2, 3 ); piped.fail( function() { assert.strictEqual( value1, 2, "first resolve value ok" ); assert.strictEqual( value2, 3, "second resolve value ok" ); assert.strictEqual( value3, 6, "result of filter ok" ); done(); } ); } ); QUnit.test( "jQuery.Deferred.then - deferred (fail)", function( assert ) { assert.expect( 3 ); var value1, value2, value3, defer = jQuery.Deferred(), piped = defer.then( null, function( a, b ) { return jQuery.Deferred( function( defer ) { defer.resolve( a * b ); } ); } ), done = assert.async(); piped.done( function( result ) { value3 = result; } ); defer.fail( function( a, b ) { value1 = a; value2 = b; } ); defer.reject( 2, 3 ); piped.done( function() { assert.strictEqual( value1, 2, "first reject value ok" ); assert.strictEqual( value2, 3, "second reject value ok" ); assert.strictEqual( value3, 6, "result of filter ok" ); done(); } ); } ); QUnit.test( "jQuery.Deferred.then - deferred (progress)", function( assert ) { assert.expect( 3 ); var value1, value2, value3, defer = jQuery.Deferred(), piped = defer.then( null, null, function( a, b ) { return jQuery.Deferred( function( defer ) { defer.resolve( a * b ); } ); } ), done = assert.async(); piped.progress( function( result ) { return jQuery.Deferred().resolve().then( function() { return result; } ).then( function( result ) { value3 = result; } ); } ); defer.progress( function( a, b ) { value1 = a; value2 = b; } ); defer.notify( 2, 3 ); piped.then( null, null, function( result ) { return jQuery.Deferred().resolve().then( function() { return result; } ).then( function() { assert.strictEqual( value1, 2, "first progress value ok" ); assert.strictEqual( value2, 3, "second progress value ok" ); assert.strictEqual( value3, 6, "result of filter ok" ); done(); } ); } ); } ); QUnit.test( "[PIPE ONLY] jQuery.Deferred.pipe - deferred (progress)", function( assert ) { assert.expect( 3 ); var value1, value2, value3, defer = jQuery.Deferred(), piped = defer.pipe( null, null, function( a, b ) { return jQuery.Deferred( function( defer ) { defer.resolve( a * b ); } ); } ), done = assert.async(); piped.done( function( result ) { value3 = result; } ); defer.progress( function( a, b ) { value1 = a; value2 = b; } ); defer.notify( 2, 3 ); piped.done( function() { assert.strictEqual( value1, 2, "first progress value ok" ); assert.strictEqual( value2, 3, "second progress value ok" ); assert.strictEqual( value3, 6, "result of filter ok" ); done(); } ); } ); QUnit.test( "jQuery.Deferred.then - context", function( assert ) { assert.expect( 11 ); var defer, piped, defer2, piped2, context = { custom: true }, done = jQuery.map( new Array( 5 ), function() { return assert.async(); } ); jQuery.Deferred().resolveWith( context, [ 2 ] ).then( function( value ) { assert.strictEqual( this, context, "custom context received by .then handler" ); return value * 3; } ).done( function( value ) { assert.notStrictEqual( this, context, "custom context not propagated through .then handler" ); assert.strictEqual( value, 6, "proper value received" ); done.pop().call(); } ); jQuery.Deferred().resolveWith( context, [ 2 ] ).then().done( function( value ) { assert.strictEqual( this, context, "custom context propagated through .then without handler" ); assert.strictEqual( value, 2, "proper value received" ); done.pop().call(); } ); jQuery.Deferred().resolve().then( function() { assert.strictEqual( this, window, "default context in .then handler" ); return jQuery.Deferred().resolveWith( context ); } ).done( function() { assert.strictEqual( this, context, "custom context of returned deferred correctly propagated" ); done.pop().call(); } ); defer = jQuery.Deferred(); piped = defer.then( function( value ) { return value * 3; } ); defer.resolve( 2 ); piped.done( function( value ) { assert.strictEqual( this, window, ".then handler does not introduce context" ); assert.strictEqual( value, 6, "proper value received" ); done.pop().call(); } ); defer2 = jQuery.Deferred(); piped2 = defer2.then(); defer2.resolve( 2 ); piped2.done( function( value ) { assert.strictEqual( this, window, ".then without handler does not introduce context" ); assert.strictEqual( value, 2, "proper value received (without passing function)" ); done.pop().call(); } ); } ); QUnit.test( "[PIPE ONLY] jQuery.Deferred.pipe - context", function( assert ) { assert.expect( 11 ); var defer, piped, defer2, piped2, context = { custom: true }, done = jQuery.map( new Array( 5 ), function() { return assert.async(); } ); jQuery.Deferred().resolveWith( context, [ 2 ] ).pipe( function( value ) { assert.strictEqual( this, context, "custom context received by .pipe handler" ); return value * 3; } ).done( function( value ) { assert.strictEqual( this, context, "[PIPE ONLY] custom context propagated through .pipe handler" ); assert.strictEqual( value, 6, "proper value received" ); done.pop().call(); } ); jQuery.Deferred().resolveWith( context, [ 2 ] ).pipe().done( function( value ) { assert.strictEqual( this, context, "[PIPE ONLY] custom context propagated through .pipe without handler" ); assert.strictEqual( value, 2, "proper value received" ); done.pop().call(); } ); jQuery.Deferred().resolve().pipe( function() { assert.strictEqual( this, window, "default context in .pipe handler" ); return jQuery.Deferred().resolveWith( context ); } ).done( function() { assert.strictEqual( this, context, "custom context of returned deferred correctly propagated" ); done.pop().call(); } ); defer = jQuery.Deferred(); piped = defer.pipe( function( value ) { return value * 3; } ); defer.resolve( 2 ); piped.done( function( value ) { assert.strictEqual( this, window, ".pipe handler does not introduce context" ); assert.strictEqual( value, 6, "proper value received" ); done.pop().call(); } ); defer2 = jQuery.Deferred(); piped2 = defer2.pipe(); defer2.resolve( 2 ); piped2.done( function( value ) { assert.strictEqual( this, window, ".pipe without handler does not introduce context" ); assert.strictEqual( value, 2, "proper value received (without passing function)" ); done.pop().call(); } ); } ); QUnit.test( "jQuery.Deferred.then - spec compatibility", function( assert ) { assert.expect( 1 ); var done = assert.async(), defer = jQuery.Deferred(); defer.done( function() { setTimeout( done ); throw new Error(); } ); defer.then( function() { assert.ok( true, "errors in .done callbacks don't stop .then handlers" ); } ); try { defer.resolve(); } catch ( _ ) {} } ); QUnit.testUnlessIE( "jQuery.Deferred.then - IsCallable determination (gh-3596)", function( assert ) { assert.expect( 1 ); var done = assert.async(), defer = jQuery.Deferred(); function faker() { assert.ok( true, "handler with non-'Function' @@toStringTag gets invoked" ); } faker[ Symbol.toStringTag ] = "String"; defer.then( faker ).then( done ); defer.resolve(); } ); QUnit.test( "jQuery.Deferred.exceptionHook", function( assert ) { assert.expect( 2 ); var done = assert.async(), defer = jQuery.Deferred(), oldWarn = window.console.warn; window.console.warn = function( _intro, error ) { assert.ok( /barf/.test( error.message + "\n" + error.stack ), "Error mentions the method: " + error.message + "\n" + error.stack ); }; jQuery.when( defer.then( function() { // Should get an error jQuery.barf(); } ).then( null, jQuery.noop ), defer.then( function() { // Should NOT get an error throw new Error( "Make me a sandwich" ); } ).then( null, jQuery.noop ) ).then( function barf( ) { jQuery.thisDiesToo(); } ).then( null, function( ) { window.console.warn = oldWarn; done(); } ); defer.resolve(); } ); QUnit.test( "jQuery.Deferred.exceptionHook with error hooks", function( assert ) { assert.expect( 2 ); var done = assert.async(), defer = jQuery.Deferred(), oldWarn = window.console.warn; jQuery.Deferred.getErrorHook = function() { // Default exceptionHook assumes the stack is in a form console.warn can log, // but a custom getErrorHook+exceptionHook pair could save a raw form and // format it to a string only when an exception actually occurs. // For the unit test we just ensure the plumbing works. return "NO ERROR FOR YOU"; }; window.console.warn = function() { var msg = Array.prototype.join.call( arguments, " " ); assert.ok( /cough_up_hairball/.test( msg ), "Function mentioned: " + msg ); assert.ok( /NO ERROR FOR YOU/.test( msg ), "Error included: " + msg ); }; defer.then( function() { jQuery.cough_up_hairball(); } ).then( null, function( ) { window.console.warn = oldWarn; delete jQuery.Deferred.getErrorHook; done(); } ); defer.resolve(); } ); QUnit.test( "jQuery.Deferred - 1.x/2.x compatibility", function( assert ) { assert.expect( 8 ); var context = { id: "callback context" }, thenable = jQuery.Deferred().resolve( "thenable fulfillment" ).promise(), done = jQuery.map( new Array( 8 ), function() { return assert.async(); } ); thenable.unwrapped = false; jQuery.Deferred().resolve( 1, 2 ).then( function() { assert.deepEqual( [].slice.call( arguments ), [ 1, 2 ], ".then fulfillment callbacks receive all resolution values" ); done.pop().call(); } ); jQuery.Deferred().reject( 1, 2 ).then( null, function() { assert.deepEqual( [].slice.call( arguments ), [ 1, 2 ], ".then rejection callbacks receive all rejection values" ); done.pop().call(); } ); jQuery.Deferred().notify( 1, 2 ).then( null, null, function() { assert.deepEqual( [].slice.call( arguments ), [ 1, 2 ], ".then progress callbacks receive all progress values" ); done.pop().call(); } ); jQuery.Deferred().resolveWith( context ).then( function() { assert.deepEqual( this, context, ".then fulfillment callbacks receive context" ); done.pop().call(); } ); jQuery.Deferred().rejectWith( context ).then( null, function() { assert.deepEqual( this, context, ".then rejection callbacks receive context" ); done.pop().call(); } ); jQuery.Deferred().notifyWith( context ).then( null, null, function() { assert.deepEqual( this, context, ".then progress callbacks receive context" ); done.pop().call(); } ); jQuery.Deferred().resolve( thenable ).done( function( value ) { assert.strictEqual( value, thenable, ".done doesn't unwrap thenables" ); done.pop().call(); } ); jQuery.Deferred().notify( thenable ).then().then( null, null, function( value ) { assert.strictEqual( value, "thenable fulfillment", ".then implicit progress callbacks unwrap thenables" ); done.pop().call(); } ); } ); QUnit.test( "jQuery.Deferred.then - progress and thenables", function( assert ) { assert.expect( 2 ); var trigger = jQuery.Deferred().notify(), expectedProgress = [ "baz", "baz" ], done = jQuery.map( new Array( 2 ), function() { return assert.async(); } ), failer = function( evt ) { return function() { assert.ok( false, "no unexpected " + evt ); }; }; trigger.then( null, null, function() { var notifier = jQuery.Deferred().notify( "foo" ); setTimeout( function() { notifier.notify( "bar" ).resolve( "baz" ); } ); return notifier; } ).then( failer( "fulfill" ), failer( "reject" ), function( v ) { assert.strictEqual( v, expectedProgress.shift(), "expected progress value" ); done.pop().call(); } ); trigger.notify(); } ); QUnit.test( "jQuery.Deferred - notify and resolve", function( assert ) { assert.expect( 7 ); var notifiedResolved = jQuery.Deferred().notify( "foo" )/*xxx .resolve( "bar" )*/, done = jQuery.map( new Array( 3 ), function() { return assert.async(); } ); notifiedResolved.progress( function( v ) { assert.strictEqual( v, "foo", "progress value" ); } ); notifiedResolved.pipe().progress( function( v ) { assert.strictEqual( v, "foo", "piped progress value" ); } ); notifiedResolved.pipe( null, null, function() { return "baz"; } ).progress( function( v ) { assert.strictEqual( v, "baz", "replaced piped progress value" ); } ); notifiedResolved.pipe( null, null, function() { return jQuery.Deferred().notify( "baz" ).resolve( "quux" ); } ).progress( function( v ) { assert.strictEqual( v, "baz", "deferred replaced piped progress value" ); } ); notifiedResolved.then().progress( function( v ) { assert.strictEqual( v, "foo", "then'd progress value" ); done.pop().call(); } ); notifiedResolved.then( null, null, function() { return "baz"; } ).progress( function( v ) { assert.strictEqual( v, "baz", "replaced then'd progress value" ); done.pop().call(); } ); notifiedResolved.then( null, null, function() { return jQuery.Deferred().notify( "baz" ).resolve( "quux" ); } ).progress( function( v ) { // Progress from the surrogate deferred is ignored assert.strictEqual( v, "quux", "deferred replaced then'd progress value" ); done.pop().call(); } ); } ); QUnit.test( "jQuery.Deferred - resolved to a notifying deferred", function( assert ) { assert.expect( 2 ); var deferred = jQuery.Deferred(), done = assert.async( 2 ); deferred.resolve( jQuery.Deferred( function( notifyingDeferred ) { notifyingDeferred.notify( "foo", "bar" ); notifyingDeferred.resolve( "baz", "quux" ); } ) ); // Apply an empty then to force thenable unwrapping. // See https://github.com/jquery/jquery/issues/3000 for more info. deferred.then().then( function() { assert.deepEqual( [].slice.call( arguments ), [ "baz", "quux" ], "The fulfilled handler receives proper params" ); done(); }, null, function() { assert.deepEqual( [].slice.call( arguments ), [ "foo", "bar" ], "The progress handler receives proper params" ); done(); } ); } ); QUnit.test( "jQuery.when(nonThenable) - like Promise.resolve", function( assert ) { "use strict"; assert.expect( 44 ); var defaultContext = ( function getDefaultContext() { return this; } )(), done = assert.async( 20 ); jQuery.when() .done( function() { assert.strictEqual( arguments.length, 0, "Resolved .done with no arguments" ); assert.strictEqual( this, defaultContext, "Default .done context with no arguments" ); } ) .then( function() { assert.strictEqual( arguments.length, 0, "Resolved .then with no arguments" ); assert.strictEqual( this, defaultContext, "Default .then context with no arguments" ); } ); jQuery.each( { "an empty string": "", "a non-empty string": "some string", "zero": 0, "a number other than zero": 1, "true": true, "false": false, "null": null, "undefined": undefined, "a plain object": {}, "an array": [ 1, 2, 3 ] }, function( message, value ) { var code = "jQuery.when( " + message + " )", onFulfilled = function( method ) { var call = code + "." + method; return function( resolveValue ) { assert.strictEqual( resolveValue, value, call + " resolve" ); assert.strictEqual( this, defaultContext, call + " context" ); done(); }; }, onRejected = function( method ) { var call = code + "." + method; return function() { assert.ok( false, call + " reject" ); done(); }; }; jQuery.when( value ) .done( onFulfilled( "done" ) ) .fail( onRejected( "done" ) ) .then( onFulfilled( "then" ), onRejected( "then" ) ); } ); } ); QUnit.test( "jQuery.when(thenable) - like Promise.resolve", function( assert ) { "use strict"; var customToStringThen = { then: function( onFulfilled ) { onFulfilled(); } }; if ( typeof Symbol === "function" ) { customToStringThen.then[ Symbol.toStringTag ] = "String"; } var slice = [].slice, sentinel = { context: "explicit" }, eventuallyFulfilled = jQuery.Deferred().notify( true ), eventuallyRejected = jQuery.Deferred().notify( true ), secondaryFulfilled = jQuery.Deferred().resolve( eventuallyFulfilled ), secondaryRejected = jQuery.Deferred().resolve( eventuallyRejected ), inputs = { promise: Promise.resolve( true ), customToStringThen: customToStringThen, rejectedPromise: Promise.reject( false ), deferred: jQuery.Deferred().resolve( true ), eventuallyFulfilled: eventuallyFulfilled, secondaryFulfilled: secondaryFulfilled, eventuallySecondaryFulfilled: jQuery.Deferred().notify( true ), multiDeferred: jQuery.Deferred().resolve( "foo", "bar" ), deferredWith: jQuery.Deferred().resolveWith( sentinel, [ true ] ), multiDeferredWith: jQuery.Deferred().resolveWith( sentinel, [ "foo", "bar" ] ), rejectedDeferred: jQuery.Deferred().reject( false ), eventuallyRejected: eventuallyRejected, secondaryRejected: secondaryRejected, eventuallySecondaryRejected: jQuery.Deferred().notify( true ), multiRejectedDeferred: jQuery.Deferred().reject( "baz", "quux" ), rejectedDeferredWith: jQuery.Deferred().rejectWith( sentinel, [ false ] ), multiRejectedDeferredWith: jQuery.Deferred().rejectWith( sentinel, [ "baz", "quux" ] ) }, contexts = { deferredWith: sentinel, multiDeferredWith: sentinel, rejectedDeferredWith: sentinel, multiRejectedDeferredWith: sentinel }, willSucceed = { promise: [ true ], customToStringThen: [], deferred: [ true ], eventuallyFulfilled: [ true ], secondaryFulfilled: [ true ], eventuallySecondaryFulfilled: [ true ], multiDeferred: [ "foo", "bar" ], deferredWith: [ true ], multiDeferredWith: [ "foo", "bar" ] }, willError = { rejectedPromise: [ false ], rejectedDeferred: [ false ], eventuallyRejected: [ false ], secondaryRejected: [ false ], eventuallySecondaryRejected: [ false ], multiRejectedDeferred: [ "baz", "quux" ], rejectedDeferredWith: [ false ], multiRejectedDeferredWith: [ "baz", "quux" ] }, numCases = Object.keys( willSucceed ).length + Object.keys( willError ).length, defaultContext = ( function getDefaultContext() { return this; } )(), done = assert.async( numCases * 2 ); assert.expect( numCases * 4 ); jQuery.each( inputs, function( message, value ) { var code = "jQuery.when( " + message + " )", shouldResolve = willSucceed[ message ], shouldError = willError[ message ], context = contexts[ message ] || defaultContext, onFulfilled = function( method ) { var call = code + "." + method; return function() { if ( shouldResolve ) { assert.deepEqual( slice.call( arguments ), shouldResolve, call + " resolve" ); assert.strictEqual( this, context, call + " context" ); } else { assert.ok( false, call + " resolve" ); } done(); }; }, onRejected = function( method ) { var call = code + "." + method; return function() { if ( shouldError ) { assert.deepEqual( slice.call( arguments ), shouldError, call + " reject" ); assert.strictEqual( this, context, call + " context" ); } else { assert.ok( false, call + " reject" ); } done(); }; }; jQuery.when( value ) .done( onFulfilled( "done" ) ) .fail( onRejected( "done" ) ) .then( onFulfilled( "then" ), onRejected( "then" ) ); } ); setTimeout( function() { eventuallyFulfilled.resolve( true ); eventuallyRejected.reject( false ); inputs.eventuallySecondaryFulfilled.resolve( secondaryFulfilled ); inputs.eventuallySecondaryRejected.resolve( secondaryRejected ); }, 50 ); } ); QUnit.test( "jQuery.when(a, b) - like Promise.all", function( assert ) { "use strict"; assert.expect( 196 ); var slice = [].slice, deferreds = { rawValue: 1, fulfilled: jQuery.Deferred().resolve( 1 ), rejected: jQuery.Deferred().reject( 0 ), eventuallyFulfilled: jQuery.Deferred().notify( true ), eventuallyRejected: jQuery.Deferred().notify( true ), fulfilledStandardPromise: Promise.resolve( 1 ), rejectedStandardPromise: Promise.reject( 0 ) }, willSucceed = { rawValue: true, fulfilled: true, eventuallyFulfilled: true, fulfilledStandardPromise: true }, willError = { rejected: true, eventuallyRejected: true, rejectedStandardPromise: true }, defaultContext = ( function getDefaultContext() { return this; } )(), done = assert.async( 98 ); jQuery.each( deferreds, function( id1, v1 ) { jQuery.each( deferreds, function( id2, v2 ) { var code = "jQuery.when( " + id1 + ", " + id2 + " )", shouldResolve = willSucceed[ id1 ] && willSucceed[ id2 ], shouldError = willError[ id1 ] || willError[ id2 ], expected = shouldResolve ? [ 1, 1 ] : [ 0 ], context = shouldResolve ? [ defaultContext, defaultContext ] : defaultContext, onFulfilled = function( method ) { var call = code + "." + method; return function() { if ( shouldResolve ) { assert.deepEqual( slice.call( arguments ), expected, call + " resolve" ); assert.deepEqual( this, context, code + " context" ); } else { assert.ok( false, call + " resolve" ); } done(); }; }, onRejected = function( method ) { var call = code + "." + method; return function() { if ( shouldError ) { assert.deepEqual( slice.call( arguments ), expected, call + " reject" ); assert.deepEqual( this, context, code + " context" ); } else { assert.ok( false, call + " reject" ); } done(); }; }; jQuery.when( v1, v2 ) .done( onFulfilled( "done" ) ) .fail( onRejected( "done" ) ) .then( onFulfilled( "then" ), onRejected( "then" ) ); } ); } ); setTimeout( function() { deferreds.eventuallyFulfilled.resolve( 1 ); deferreds.eventuallyRejected.reject( 0 ); }, 50 ); } ); QUnit.test( "jQuery.when - always returns a new promise", function( assert ) { assert.expect( 42 ); jQuery.each( { "no arguments": [], "non-thenable": [ "foo" ], "promise": [ Promise.resolve( "bar" ) ], "rejected promise": [ Promise.reject( "bar" ) ], "deferred": [ jQuery.Deferred().resolve( "baz" ) ], "rejected deferred": [ jQuery.Deferred().reject( "baz" ) ], "multi-resolved deferred": [ jQuery.Deferred().resolve( "qux", "quux" ) ], "multiple non-thenables": [ "corge", "grault" ], "multiple deferreds": [ jQuery.Deferred().resolve( "garply" ), jQuery.Deferred().resolve( "waldo" ) ] }, function( label, args ) { var result = jQuery.when.apply( jQuery, args ); assert.ok( typeof result.then === "function", "Thenable returned from " + label ); assert.strictEqual( result.resolve, undefined, "Non-deferred returned from " + label ); assert.strictEqual( result.promise(), result, "Promise returned from " + label ); jQuery.each( args, function( i, arg ) { assert.notStrictEqual( result, arg, "Returns distinct from arg " + i + " of " + label ); if ( arg.promise ) { assert.notStrictEqual( result, arg.promise(), "Returns distinct from promise of arg " + i + " of " + label ); } } ); } ); } ); QUnit.test( "jQuery.when - notify does not affect resolved", function( assert ) { assert.expect( 3 ); var a = jQuery.Deferred().notify( 1 ).resolve( 4 ), b = jQuery.Deferred().notify( 2 ).resolve( 5 ), c = jQuery.Deferred().notify( 3 ).resolve( 6 ); jQuery.when( a, b, c ).done( function( a, b, c ) { assert.strictEqual( a, 4, "first resolve value ok" ); assert.strictEqual( b, 5, "second resolve value ok" ); assert.strictEqual( c, 6, "third resolve value ok" ); } ).fail( function() { assert.ok( false, "Error on resolve" ); } ); } ); QUnit.test( "jQuery.when(...) - opportunistically synchronous", function( assert ) { assert.expect( 5 ); var when = "before", resolved = jQuery.Deferred().resolve( true ), rejected = jQuery.Deferred().reject( false ), validate = function( label ) { return function() { assert.equal( when, "before", label ); }; }, done = assert.async( 5 ); jQuery.when().done( validate( "jQuery.when()" ) ).always( done ); jQuery.when( when ).done( validate( "jQuery.when(nonThenable)" ) ).always( done ); jQuery.when( resolved ).done( validate( "jQuery.when(alreadyFulfilled)" ) ).always( done ); jQuery.when( rejected ).fail( validate( "jQuery.when(alreadyRejected)" ) ).always( done ); jQuery.when( resolved, rejected )
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
true
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/test/unit/selector.js
test/unit/selector.js
QUnit.module( "selector", { beforeEach: function() { // Playwright WebKit on macOS doesn't expose `Safari` in its user agent // string; use the "AppleWebKit" token. This token is also present // in the Chromium UA, but it is locked to an older version there. // Modern WebKit (Safari 13+) locks it to `605.1.15`. this.safari = /\bapplewebkit\/605\.1\.15\b/i.test( navigator.userAgent ); }, afterEach: moduleTeardown } ); QUnit.test( "empty", function( assert ) { assert.expect( 5 ); var form; assert.strictEqual( jQuery( "" ).length, 0, "Empty selector returns an empty array" ); assert.deepEqual( jQuery( "div", document.createTextNode( "" ) ).get(), [], "Text element as context fails silently" ); form = document.getElementById( "form" ); assert.ok( !jQuery( form ).is( "" ), "Empty string passed to .is() does not match" ); if ( QUnit.jQuerySelectors ) { assert.equal( jQuery( " " ).length, 0, "Empty selector returns an empty array" ); assert.equal( jQuery( "\t" ).length, 0, "Empty selector returns an empty array" ); } else { assert.ok( "skip", "whitespace-only selector not supported in selector-native" ); assert.ok( "skip", "whitespace-only selector not supported in selector-native" ); } } ); QUnit.test( "star", function( assert ) { assert.expect( 2 ); var good, i, all = jQuery( "*" ); assert.ok( all.length >= 30, "Select all" ); good = true; for ( i = 0; i < all.length; i++ ) { if ( all[ i ].nodeType === 8 ) { good = false; } } assert.ok( good, "Select all elements, no comment nodes" ); } ); QUnit.test( "element", function( assert ) { assert.expect( 37 ); var i, lengthtest, siblingTest, html, fixture = document.getElementById( "qunit-fixture" ); assert.deepEqual( jQuery( "p", fixture ).get(), q( "firstp", "ap", "sndp", "en", "sap", "first" ), "Finding elements with a Node context." ); assert.deepEqual( jQuery( "p", "#qunit-fixture" ).get(), q( "firstp", "ap", "sndp", "en", "sap", "first" ), "Finding elements with a selector context." ); assert.deepEqual( jQuery( "p", jQuery( "#qunit-fixture" ) ).get(), q( "firstp", "ap", "sndp", "en", "sap", "first" ), "Finding elements with a jQuery object context." ); assert.deepEqual( jQuery( "#qunit-fixture" ).find( "p" ).get(), q( "firstp", "ap", "sndp", "en", "sap", "first" ), "Finding elements with a context via .find()." ); assert.ok( jQuery( "#length" ).length, "<input name=\"length\"> cannot be found under IE, see trac-945" ); assert.ok( jQuery( "#lengthtest input" ).length, "<input name=\"length\"> cannot be found under IE, see trac-945" ); // trac-7533 assert.equal( jQuery( "<div id=\"A'B~C.D[E]\"><p>foo</p></div>" ).find( "p" ).length, 1, "Find where context root is a node and has an ID with CSS3 meta characters" ); assert.equal( jQuery( "" ).length, 0, "Empty selector returns an empty array" ); assert.deepEqual( jQuery( "div", document.createTextNode( "" ) ).get(), [], "Text element as context fails silently" ); assert.t( "Element Selector", "html", [ "html" ] ); assert.t( "Element Selector", "body", [ "body" ] ); assert.t( "Element Selector", "#qunit-fixture p", [ "firstp", "ap", "sndp", "en", "sap", "first" ] ); assert.t( "Leading space", " #qunit-fixture p", [ "firstp", "ap", "sndp", "en", "sap", "first" ] ); assert.t( "Leading tab", "\t#qunit-fixture p", [ "firstp", "ap", "sndp", "en", "sap", "first" ] ); assert.t( "Leading carriage return", "\r#qunit-fixture p", [ "firstp", "ap", "sndp", "en", "sap", "first" ] ); assert.t( "Leading line feed", "\n#qunit-fixture p", [ "firstp", "ap", "sndp", "en", "sap", "first" ] ); assert.t( "Leading form feed", "\f#qunit-fixture p", [ "firstp", "ap", "sndp", "en", "sap", "first" ] ); assert.t( "Trailing space", "#qunit-fixture p ", [ "firstp", "ap", "sndp", "en", "sap", "first" ] ); assert.t( "Trailing tab", "#qunit-fixture p\t", [ "firstp", "ap", "sndp", "en", "sap", "first" ] ); assert.t( "Trailing carriage return", "#qunit-fixture p\r", [ "firstp", "ap", "sndp", "en", "sap", "first" ] ); assert.t( "Trailing line feed", "#qunit-fixture p\n", [ "firstp", "ap", "sndp", "en", "sap", "first" ] ); assert.t( "Trailing form feed", "#qunit-fixture p\f", [ "firstp", "ap", "sndp", "en", "sap", "first" ] ); assert.deepEqual( jQuery( jQuery( "div ol" ) ).filter( "#qunit-fixture *" ).get(), q( "empty", "listWithTabIndex" ), "Parent Element" ); assert.deepEqual( jQuery( jQuery( "div\tol" ) ).filter( "#qunit-fixture *" ).get(), q( "empty", "listWithTabIndex" ), "Parent Element (non-space descendant combinator)" ); // Check for unique-ness and sort order assert.deepEqual( jQuery( "p, div p" ), jQuery( "p" ), "Check for duplicates: p, div p" ); jQuery( "<h1 id='h1'></h1><h2 id='h2'></h2><h2 id='h2-2'></h2>" ).prependTo( "#qunit-fixture" ); assert.t( "Checking sort order", "#qunit-fixture h2, #qunit-fixture h1", [ "h1", "h2", "h2-2" ] ); if ( QUnit.jQuerySelectorsPos ) { assert.t( "Checking sort order", "#qunit-fixture h2:first, #qunit-fixture h1:first", [ "h1", "h2" ] ); } else { assert.ok( "skip", "Positional selectors are not supported" ); } assert.t( "Checking sort order", "#qunit-fixture p, #qunit-fixture p a", [ "firstp", "john1", "ap", "google", "groups", "anchor1", "mozilla", "sndp", "en", "yahoo", "sap", "anchor2", "timmy", "first" ] ); // Test Conflict ID lengthtest = document.getElementById( "lengthtest" ); assert.deepEqual( jQuery( "#idTest", lengthtest ).get(), q( "idTest" ), "Finding element with id of ID." ); assert.deepEqual( jQuery( "[name='id']", lengthtest ).get(), q( "idTest" ), "Finding element with id of ID." ); assert.deepEqual( jQuery( "input[id='idTest']", lengthtest ).get(), q( "idTest" ), "Finding elements with id of ID." ); siblingTest = document.getElementById( "siblingTest" ); assert.deepEqual( jQuery( "div em", siblingTest ).get(), [], "Element-rooted QSA does not select based on document context" ); assert.deepEqual( jQuery( "div em, div em, div em:not(div em)", siblingTest ).get(), [], "Element-rooted QSA does not select based on document context" ); assert.deepEqual( jQuery( "div em, em\\,", siblingTest ).get(), [], "Escaped commas do not get treated with an id in element-rooted QSA" ); html = ""; for ( i = 0; i < 100; i++ ) { html = "<div>" + html + "</div>"; } html = jQuery( html ).appendTo( document.body ); assert.ok( !!jQuery( "body div div div" ).length, "No stack or performance problems with large amounts of descendants" ); assert.ok( !!jQuery( "body>div div div" ).length, "No stack or performance problems with large amounts of descendants" ); html.remove(); // Real use case would be using .watch in browsers with window.watch // (see https://github.com/jquery/sizzle/pull/157) q( "qunit-fixture" )[ 0 ].appendChild( document.createElement( "toString" ) ).id = "toString"; assert.t( "Element name matches Object.prototype property", "toString#toString", [ "toString" ] ); } ); QUnit.test( "XML Document Selectors", function( assert ) { assert.expect( 11 ); var xml = createWithFriesXML(); assert.equal( jQuery( "foo_bar", xml ).length, 1, "Element Selector with underscore" ); assert.equal( jQuery( ".component", xml ).length, 1, "Class selector" ); assert.equal( jQuery( "[class*=component]", xml ).length, 1, "Attribute selector for class" ); assert.equal( jQuery( "property[name=prop2]", xml ).length, 1, "Attribute selector with name" ); assert.equal( jQuery( "[name=prop2]", xml ).length, 1, "Attribute selector with name" ); assert.equal( jQuery( "#seite1", xml ).length, 1, "Attribute selector with ID" ); assert.equal( jQuery( "component#seite1", xml ).length, 1, "Attribute selector with ID" ); assert.equal( jQuery( "component", xml ).filter( "#seite1" ).length, 1, "Attribute selector filter with ID" ); assert.equal( jQuery( "meta property thing", xml ).length, 2, "Descendent selector and dir caching" ); if ( QUnit.jQuerySelectors ) { assert.ok( jQuery( xml.lastChild ).is( "soap\\:Envelope" ), "Check for namespaced element" ); xml = jQuery.parseXML( "<?xml version='1.0' encoding='UTF-8'?><root><elem id='1'/></root>" ); assert.equal( jQuery( "elem:not(:has(*))", xml ).length, 1, "Non-qSA path correctly handles numeric ids (jQuery trac-14142)" ); } else { assert.ok( "skip", "namespaced elements not matching correctly in selector-native" ); assert.ok( "skip", ":not(complex selector) not supported in selector-native" ); } } ); QUnit.test( "broken selectors throw", function( assert ) { assert.expect( 33 ); function broken( name, selector ) { assert.throws( function() { jQuery( selector ); }, name + ": " + selector ); } broken( "Broken Selector", "[" ); broken( "Broken Selector", "(" ); broken( "Broken Selector", "{" ); broken( "Broken Selector", "<" ); broken( "Broken Selector", "()" ); broken( "Broken Selector", "<>" ); broken( "Broken Selector", "{}" ); broken( "Broken Selector", "," ); broken( "Broken Selector", ",a" ); broken( "Broken Selector", "a," ); broken( "Post-comma invalid selector", "*,:x" ); broken( "Identifier with bad escape", "foo\\\fbaz" ); broken( "Broken Selector", "[id=012345678901234567890123456789" ); broken( "Doesn't exist", ":visble" ); broken( "Nth-child", ":nth-child" ); broken( "Nth-child", ":nth-child(-)" ); broken( "Nth-child", ":nth-child(asdf)", [] ); broken( "Nth-child", ":nth-child(2n+-0)" ); broken( "Nth-child", ":nth-child(2+0)" ); broken( "Nth-child", ":nth-child(- 1n)" ); broken( "Nth-child", ":nth-child(-1 n)" ); broken( "First-child", ":first-child(n)" ); broken( "Last-child", ":last-child(n)" ); broken( "Only-child", ":only-child(n)" ); broken( "Nth-last-last-child", ":nth-last-last-child(1)" ); broken( "First-last-child", ":first-last-child" ); broken( "Last-last-child", ":last-last-child" ); broken( "Only-last-child", ":only-last-child" ); // Make sure attribute value quoting works correctly. See: trac-6093 jQuery( "<input type='hidden' value='2' name='foo.baz' id='attrbad1'/>" + "<input type='hidden' value='2' name='foo[baz]' id='attrbad2'/>" ) .appendTo( "#qunit-fixture" ); broken( "Attribute equals non-value", "input[name=]" ); broken( "Attribute equals unquoted non-identifier", "input[name=foo.baz]" ); broken( "Attribute equals unquoted non-identifier", "input[name=foo[baz]]" ); broken( "Attribute equals bad string", "input[name=''double-quoted'']" ); broken( "Attribute equals bad string", "input[name='apostrophe'd']" ); } ); QUnit.test( "id", function( assert ) { assert.expect( 35 ); var fiddle, a, lengthtest; assert.t( "ID Selector", "#body", [ "body" ] ); assert.t( "ID Selector w/ Element", "body#body", [ "body" ] ); assert.t( "ID Selector w/ Element", "ul#first", [] ); assert.t( "ID selector with existing ID descendant", "#firstp #john1", [ "john1" ] ); assert.t( "ID selector with non-existent descendant", "#firstp #foobar", [] ); assert.t( "ID selector using UTF8", "#台北Táiběi", [ "台北Táiběi" ] ); assert.t( "Multiple ID selectors using UTF8", "#台北Táiběi, #台北", [ "台北Táiběi", "台北" ] ); assert.t( "Descendant ID selector using UTF8", "div #台北", [ "台北" ] ); assert.t( "Child ID selector using UTF8", "form > #台北", [ "台北" ] ); assert.t( "Escaped ID", "#foo\\:bar", [ "foo:bar" ] ); if ( QUnit.jQuerySelectors ) { assert.t( "Escaped ID with descendant", "#foo\\:bar span:not(:input)", [ "foo_descendant" ] ); } else { assert.ok( "skip", ":input not supported in selector-native" ); } assert.t( "Escaped ID", "#test\\.foo\\[5\\]bar", [ "test.foo[5]bar" ] ); assert.t( "Descendant escaped ID", "div #foo\\:bar", [ "foo:bar" ] ); assert.t( "Descendant escaped ID", "div #test\\.foo\\[5\\]bar", [ "test.foo[5]bar" ] ); assert.t( "Child escaped ID", "form > #foo\\:bar", [ "foo:bar" ] ); assert.t( "Child escaped ID", "form > #test\\.foo\\[5\\]bar", [ "test.foo[5]bar" ] ); fiddle = jQuery( "<div id='fiddle\\Foo'><span id='fiddleSpan'></span></div>" ) .appendTo( "#qunit-fixture" ); assert.deepEqual( jQuery( "> span", jQuery( "#fiddle\\\\Foo" )[ 0 ] ).get(), q( [ "fiddleSpan" ] ), "Escaped ID as context" ); fiddle.remove(); assert.t( "ID Selector, child ID present", "#form > #radio1", [ "radio1" ] ); // bug trac-267 assert.t( "ID Selector, not an ancestor ID", "#form #first", [] ); assert.t( "ID Selector, not a child ID", "#form > #option1a", [] ); assert.t( "All Children of ID", "#foo > *", [ "sndp", "en", "sap" ] ); assert.t( "All Children of ID with no children", "#firstUL > *", [] ); assert.equal( jQuery( "#tName1" )[ 0 ].id, "tName1", "ID selector with same value for a name attribute" ); assert.t( "ID selector non-existing but name attribute on an A tag", "#tName2", [] ); assert.t( "Leading ID selector non-existing but name attribute on an A tag", "#tName2 span", [] ); assert.t( "Leading ID selector existing, retrieving the child", "#tName1 span", [ "tName1-span" ] ); assert.equal( jQuery( "div > div #tName1" )[ 0 ].id, jQuery( "#tName1-span" )[ 0 ].parentNode.id, "Ending with ID" ); a = jQuery( "<a id='backslash\\foo'></a>" ).appendTo( "#qunit-fixture" ); assert.t( "ID Selector contains backslash", "#backslash\\\\foo", [ "backslash\\foo" ] ); a.remove(); assert.t( "ID Selector on Form with an input that has a name of 'id'", "#lengthtest", [ "lengthtest" ] ); // Run the above test again but with `jQuery.find` directly to avoid the jQuery // quick path that avoids running the selector engine. lengthtest = jQuery.find( "#lengthtest" ); assert.strictEqual( lengthtest && lengthtest[ 0 ], document.getElementById( "lengthtest" ), "ID Selector on Form with an input that has a name of 'id' - no quick path (#lengthtest)" ); assert.t( "ID selector with non-existent ancestor", "#asdfasdf #foobar", [] ); // bug trac-986 assert.deepEqual( jQuery( "div#form", document.body ).get(), [], "ID selector within the context of another element" ); assert.t( "Underscore ID", "#types_all", [ "types_all" ] ); assert.t( "Dash ID", "#qunit-fixture", [ "qunit-fixture" ] ); assert.t( "ID with weird characters in it", "#name\\+value", [ "name+value" ] ); } ); QUnit.test( "class", function( assert ) { assert.expect( 32 ); assert.deepEqual( jQuery( ".blog", document.getElementsByTagName( "p" ) ).get(), q( "mozilla", "timmy" ), "Finding elements with a context." ); assert.deepEqual( jQuery( ".blog", "p" ).get(), q( "mozilla", "timmy" ), "Finding elements with a context." ); assert.deepEqual( jQuery( ".blog", jQuery( "p" ) ).get(), q( "mozilla", "timmy" ), "Finding elements with a context." ); assert.deepEqual( jQuery( "p" ).find( ".blog" ).get(), q( "mozilla", "timmy" ), "Finding elements with a context." ); assert.t( "Class Selector", ".blog", [ "mozilla", "timmy" ] ); assert.t( "Class Selector", ".GROUPS", [ "groups" ] ); assert.t( "Class Selector", ".blog.link", [ "timmy" ] ); assert.t( "Class Selector w/ Element", "a.blog", [ "mozilla", "timmy" ] ); assert.t( "Parent Class Selector", "p .blog", [ "mozilla", "timmy" ] ); assert.t( "Class selector using UTF8", ".台北Táiběi", [ "utf8class1" ] ); assert.t( "Class selector using UTF8", ".台北", [ "utf8class1", "utf8class2" ] ); assert.t( "Class selector using UTF8", ".台北Táiběi.台北", [ "utf8class1" ] ); assert.t( "Class selector using UTF8", ".台北Táiběi, .台北", [ "utf8class1", "utf8class2" ] ); assert.t( "Descendant class selector using UTF8", "div .台北Táiběi", [ "utf8class1" ] ); assert.t( "Child class selector using UTF8", "form > .台北Táiběi", [ "utf8class1" ] ); assert.t( "Escaped Class", ".foo\\:bar", [ "foo:bar" ] ); assert.t( "Escaped Class", ".test\\.foo\\[5\\]bar", [ "test.foo[5]bar" ] ); assert.t( "Descendant escaped Class", "div .foo\\:bar", [ "foo:bar" ] ); assert.t( "Descendant escaped Class", "div .test\\.foo\\[5\\]bar", [ "test.foo[5]bar" ] ); assert.t( "Child escaped Class", "form > .foo\\:bar", [ "foo:bar" ] ); assert.t( "Child escaped Class", "form > .test\\.foo\\[5\\]bar", [ "test.foo[5]bar" ] ); var div = document.createElement( "div" ); div.innerHTML = "<div class='test e'></div><div class='test'></div>"; assert.deepEqual( jQuery( ".e", div ).get(), [ div.firstChild ], "Finding a second class." ); div.lastChild.className = "e"; assert.ok( !jQuery( div ).is( ".null" ), ".null does not match an element with no class" ); assert.ok( !jQuery( div.firstChild ).is( ".null div" ), ".null does not match an element with no class" ); div.className = "null"; assert.ok( jQuery( div ).is( ".null" ), ".null matches element with class 'null'" ); assert.ok( jQuery( div.firstChild ).is( ".null div" ), "caching system respects DOM changes" ); assert.ok( !jQuery( document ).is( ".foo" ), "testing class on document doesn't error" ); assert.ok( !jQuery( window ).is( ".foo" ), "testing class on window doesn't error" ); assert.deepEqual( jQuery( ".e", div ).get(), [ div.firstChild, div.lastChild ], "Finding a modified class." ); div.lastChild.className += " hasOwnProperty toString"; assert.deepEqual( jQuery( ".e.hasOwnProperty.toString", div ).get(), [ div.lastChild ], "Classes match Object.prototype properties" ); div = jQuery( "<div><svg width='200' height='250' version='1.1'" + " xmlns='http://www.w3.org/2000/svg'><rect x='10' y='10' width='30' height='30'" + "class='foo'></rect></svg></div>" )[ 0 ]; assert.equal( jQuery( ".foo", div ).length, 1, "Class selector against SVG container" ); assert.equal( jQuery( ".foo", div.firstChild ).length, 1, "Class selector directly against SVG" ); } ); QUnit.test( "name", function( assert ) { assert.expect( 14 ); var form; assert.t( "Name selector", "input[name=action]", [ "text1" ] ); assert.t( "Name selector with single quotes", "input[name='action']", [ "text1" ] ); assert.t( "Name selector with double quotes", "input[name=\"action\"]", [ "text1" ] ); assert.t( "Name selector non-input", "[name=example]", [ "name-is-example" ] ); assert.t( "Name selector non-input", "[name=div]", [ "name-is-div" ] ); assert.t( "Name selector non-input", "*[name=iframe]", [ "iframe" ] ); assert.t( "Name selector for grouped input", "input[name='types[]']", [ "types_all", "types_anime", "types_movie" ] ); form = document.getElementById( "form" ); assert.deepEqual( jQuery( "input[name=action]", form ).get(), q( "text1" ), "Name selector within the context of another element" ); assert.deepEqual( jQuery( "input[name='foo[bar]']", form ).get(), q( "hidden2" ), "Name selector for grouped form element within the context of another element" ); form = jQuery( "<form><input name='id'/></form>" ).appendTo( "body" ); assert.equal( jQuery( "input", form[ 0 ] ).length, 1, "Make sure that rooted queries on forms (with possible expandos) work." ); form.remove(); assert.t( "Find elements that have similar IDs", "[name=tName1]", [ "tName1ID" ] ); assert.t( "Find elements that have similar IDs", "[name=tName2]", [ "tName2ID" ] ); assert.t( "Find elements that have similar IDs", "#tName2ID", [ "tName2ID" ] ); assert.t( "Case-sensitivity", "[name=tname1]", [] ); } ); QUnit.test( "comma-separated", function( assert ) { assert.expect( 10 ); var fixture = jQuery( "<div><h2><span></span></h2><div><p><span></span></p><p></p></div></div>" ); assert.equal( fixture.find( "h2, div p" ).filter( "p" ).length, 2, "has to find two <p>" ); assert.equal( fixture.find( "h2, div p" ).filter( "h2" ).length, 1, "has to find one <h2>" ); assert.equal( fixture.find( "h2 , div p" ).filter( "p" ).length, 2, "has to find two <p>" ); assert.equal( fixture.find( "h2 , div p" ).filter( "h2" ).length, 1, "has to find one <h2>" ); assert.equal( fixture.find( "h2 ,div p" ).filter( "p" ).length, 2, "has to find two <p>" ); assert.equal( fixture.find( "h2 ,div p" ).filter( "h2" ).length, 1, "has to find one <h2>" ); assert.equal( fixture.find( "h2,div p" ).filter( "p" ).length, 2, "has to find two <p>" ); assert.equal( fixture.find( "h2,div p" ).filter( "h2" ).length, 1, "has to find one <h2>" ); assert.equal( fixture.find( "h2\t,\rdiv p" ).filter( "p" ).length, 2, "has to find two <p>" ); assert.equal( fixture.find( "h2\t,\rdiv p" ).filter( "h2" ).length, 1, "has to find one <h2>" ); } ); QUnit.test( "comma-separated, only supported natively (gh-5177)", function( assert ) { assert.expect( 5 ); var fixture = jQuery( "<div><input/><span></span></div>" ); fixture.appendTo( "#qunit-fixture" ); assert.equal( fixture.find( "input:valid, span" ).length, 2, "has to find two elements" ); assert.equal( fixture.find( "input:valid , span" ).length, 2, "has to find two elements" ); assert.equal( fixture.find( "input:valid ,span" ).length, 2, "has to find two elements" ); assert.equal( fixture.find( "input:valid,span" ).length, 2, "has to find two elements" ); assert.equal( fixture.find( "input:valid\t,\rspan" ).length, 2, "has to find two elements" ); } ); QUnit.test( "child and adjacent", function( assert ) { assert.expect( 43 ); var siblingFirst, en, nothiddendiv; assert.t( "Child", "p > a", [ "john1", "google", "groups", "mozilla", "yahoo", "timmy" ] ); assert.t( "Child minus leading whitespace", "p> a", [ "john1", "google", "groups", "mozilla", "yahoo", "timmy" ] ); assert.t( "Child minus trailing whitespace", "p >a", [ "john1", "google", "groups", "mozilla", "yahoo", "timmy" ] ); assert.t( "Child minus whitespace", "p>a", [ "john1", "google", "groups", "mozilla", "yahoo", "timmy" ] ); assert.t( "Child w/ Class", "p > a.blog", [ "mozilla", "timmy" ] ); assert.t( "All Children", "code > *", [ "anchor1", "anchor2" ] ); assert.selectInFixture( "All Grandchildren", "p > * > *", [ "anchor1", "anchor2" ] ); assert.t( "Rooted tag adjacent", "#qunit-fixture a + a", [ "groups", "tName2ID" ] ); assert.t( "Rooted tag adjacent minus whitespace", "#qunit-fixture a+a", [ "groups", "tName2ID" ] ); assert.t( "Rooted tag adjacent minus leading whitespace", "#qunit-fixture a +a", [ "groups", "tName2ID" ] ); assert.t( "Rooted tag adjacent minus trailing whitespace", "#qunit-fixture a+ a", [ "groups", "tName2ID" ] ); assert.t( "Tag adjacent", "p + p", [ "ap", "en", "sap" ] ); assert.t( "#id adjacent", "#firstp + p", [ "ap" ] ); assert.t( "Tag#id adjacent", "p#firstp + p", [ "ap" ] ); assert.t( "Tag[attr] adjacent", "p[lang=en] + p", [ "sap" ] ); assert.t( "Tag.class adjacent", "a.GROUPS + code + a", [ "mozilla" ] ); assert.t( "Comma, Child, and Adjacent", "#qunit-fixture a + a, code > a", [ "groups", "anchor1", "anchor2", "tName2ID" ] ); assert.t( "Element Preceded By", "#qunit-fixture p ~ div", [ "foo", "nothiddendiv", "moretests", "tabindex-tests", "liveHandlerOrder", "siblingTest", "fx-test-group" ] ); assert.t( "Element Preceded By", "#first ~ div", [ "moretests", "tabindex-tests", "liveHandlerOrder", "siblingTest", "fx-test-group" ] ); assert.t( "Element Preceded By", "#groups ~ a", [ "mozilla" ] ); assert.t( "Element Preceded By", "#length ~ input", [ "idTest" ] ); assert.t( "Element Preceded By", "#siblingfirst ~ em", [ "siblingnext", "siblingthird" ] ); assert.t( "Element Preceded By (multiple)", "#siblingTest em ~ em ~ em ~ span", [ "siblingspan" ] ); siblingFirst = document.getElementById( "siblingfirst" ); assert.deepEqual( jQuery( "+ em", siblingFirst ).get(), q( "siblingnext" ), "Element Directly Preceded By with a context." ); assert.deepEqual( jQuery( "~ em", siblingFirst ).get(), q( "siblingnext", "siblingthird" ), "Element Preceded By with a context." ); if ( QUnit.jQuerySelectorsPos ) { assert.deepEqual( jQuery( "~ em:first", siblingFirst ).get(), q( "siblingnext" ), "Element Preceded By positional with a context." ); } else { assert.ok( "skip", "Positional selectors are not supported" ); } en = document.getElementById( "en" ); assert.deepEqual( jQuery( "+ p, a", en ).get(), q( "yahoo", "sap" ), "Compound selector with context, beginning with sibling test." ); assert.deepEqual( jQuery( "a, + p", en ).get(), q( "yahoo", "sap" ), "Compound selector with context, containing sibling test." ); if ( QUnit.jQuerySelectors ) { assert.t( "Element Preceded By, Containing", "#liveHandlerOrder ~ div em:contains('1')", [ "siblingfirst" ] ); assert.t( "Combinators are not skipped when mixing general and specific", "#siblingTest > em:contains('x') + em ~ span", [] ); } else { assert.ok( "skip", ":contains not supported in selector-native" ); assert.ok( "skip", ":contains not supported in selector-native" ); } if ( QUnit.jQuerySelectorsPos ) { assert.equal( jQuery( "#listWithTabIndex li:eq(2) ~ li" ).length, 1, "Find by general sibling combinator (trac-8310)" ); nothiddendiv = document.getElementById( "nothiddendiv" ); assert.deepEqual( jQuery( "> :first", nothiddendiv ).get(), q( "nothiddendivchild" ), "Verify child context positional selector" ); assert.deepEqual( jQuery( "> :eq(0)", nothiddendiv ).get(), q( "nothiddendivchild" ), "Verify child context positional selector" ); assert.deepEqual( jQuery( "> *:first", nothiddendiv ).get(), q( "nothiddendivchild" ), "Verify child context positional selector" ); } else { assert.ok( "skip", "Positional selectors are not supported" ); assert.ok( "skip", "Positional selectors are not supported" ); assert.ok( "skip", "Positional selectors are not supported" ); assert.ok( "skip", "Positional selectors are not supported" ); } assert.t( "Multiple combinators selects all levels", "#siblingTest em *", [ "siblingchild", "siblinggrandchild", "siblinggreatgrandchild" ] ); assert.t( "Multiple combinators selects all levels", "#siblingTest > em *", [ "siblingchild", "siblinggrandchild", "siblinggreatgrandchild" ] ); assert.t( "Multiple sibling combinators doesn't miss general siblings", "#siblingTest > em:first-child + em ~ span", [ "siblingspan" ] ); assert.equal( jQuery( "#listWithTabIndex" ).length, 1, "Parent div for next test is found via ID (trac-8310)" ); assert.equal( jQuery( "#__sizzle__" ).length, 0, "Make sure the temporary id assigned by sizzle is cleared out (trac-8310)" ); assert.equal( jQuery( "#listWithTabIndex" ).length, 1, "Parent div for previous test is still found via ID (trac-8310)" ); assert.t( "Verify deep class selector", "div.blah > p > a", [] ); assert.t( "No element deep selector", "div.foo > span > a", [] ); assert.t( "Non-existent ancestors", ".fototab > .thumbnails > a", [] ); } ); QUnit.test( "attributes - existence", function( assert ) { assert.expect( 7 ); assert.t( "On element", "#qunit-fixture a[title]", [ "google" ] ); assert.t( "On element (whitespace ignored)", "#qunit-fixture a[ title ]", [ "google" ] ); assert.t( "On element (case-insensitive)", "#qunit-fixture a[TITLE]", [ "google" ] ); assert.t( "On any element", "#qunit-fixture *[title]", [ "google" ] ); assert.t( "On implicit element", "#qunit-fixture [title]", [ "google" ] ); assert.t( "Boolean", "#select2 option[selected]", [ "option2d" ] ); assert.t( "For attribute on label", "#qunit-fixture form label[for]", [ "label-for" ] ); } ); QUnit.test( "attributes - equals", function( assert ) { assert.expect( 20 ); var withScript; assert.t( "Identifier", "#qunit-fixture a[rel=bookmark]", [ "john1" ] ); assert.t( "Identifier with underscore", "input[id=types_all]", [ "types_all" ] ); assert.t( "String", "#qunit-fixture a[rel='bookmark']", [ "john1" ] ); assert.t( "String (whitespace ignored)", "#qunit-fixture a[ rel = 'bookmark' ]", [ "john1" ] ); assert.t( "Non-identifier string", "#qunit-fixture a[href='https://www.google.com/']", [ "google" ] ); assert.t( "Empty string", "#select1 option[value='']", [ "option1a" ] ); if ( QUnit.jQuerySelectors ) { assert.t( "Number", "#qunit-fixture option[value=1]", [ "option1b", "option2b", "option3b", "option4b", "option5c" ] ); assert.t( "negative number", "#qunit-fixture li[tabIndex=-1]", [ "foodWithNegativeTabIndex" ] ); } else { assert.ok( "skip", "Number value not supported in selector-native" ); assert.ok( "skip", "Negative number value not supported in selector-native" ); } assert.t( "Non-ASCII identifier", "span[lang=中文]", [ "台北" ] ); assert.t( "input[type=text]", "#form input[type=text]", [ "text1", "text2", "hidden2", "name" ] ); assert.t( "input[type=search]", "#form input[type=search]", [ "search" ] ); withScript = supportjQuery( "<div><span><script src=''></script></span></div>" ); assert.ok( withScript.find( "#moretests script[src]" ).has( "script" ), "script[src] (jQuery trac-13777)" ); assert.t( "Boolean attribute equals name", "#select2 option[selected='selected']", [ "option2d" ] ); assert.t( "for Attribute in form", "#form [for=action]", [ "label-for" ] ); assert.t( "Grouped Form Elements - name", "input[name='foo[bar]']", [ "hidden2" ] ); assert.t( "Value", "input[value=Test]", [ "text1", "text2" ] ); assert.deepEqual( jQuery( "input[data-comma='0,1']" ).get(), q( "el12087" ), "Without context, single-quoted attribute containing ','" ); assert.deepEqual( jQuery( "input[data-comma=\"0,1\"]" ).get(), q( "el12087" ), "Without context, double-quoted attribute containing ','" ); assert.deepEqual( jQuery( "input[data-comma='0,1']", document.getElementById( "t12087" ) ).get(), q( "el12087" ), "With context, single-quoted attribute containing ','" ); assert.deepEqual( jQuery( "input[data-comma=\"0,1\"]", document.getElementById( "t12087" ) ).get(), q( "el12087" ), "With context, double-quoted attribute containing ','" ); } ); QUnit[ QUnit.jQuerySelectors ? "test" : "skip" ]( "attributes - does not equal", function( assert ) { assert.expect( 2 ); assert.t( "string", "#ap a[hreflang!='en']", [ "google", "groups", "anchor1" ] ); assert.t( "Empty values", "#select1 option[value!='']", [ "option1b", "option1c", "option1d" ] ); } ); QUnit.test( "attributes - starts with", function( assert ) { assert.expect( 4 ); assert.t( "string (whitespace ignored)", "a[href ^= 'https://www']", [ "google", "yahoo" ] ); assert.t( "href starts with hash", "p a[href^='#']", [ "anchor2" ] ); assert.t( "string containing '['", "input[name^='foo[']", [ "hidden2" ] ); assert.t( "string containing '[' ... ']'", "input[name^='foo[bar]']", [ "hidden2" ] ); } ); QUnit.test( "attributes - contains", function( assert ) { assert.expect( 4 ); assert.t( "string (whitespace ignored)", "a[href *= 'google']", [ "google", "groups" ] ); assert.t( "string like '[' ... ']']", "input[name*='[bar]']", [ "hidden2" ] ); assert.t( "string containing '['...']", "input[name*='foo[bar]']", [ "hidden2" ] ); assert.t( "href contains hash", "p a[href*='#']", [ "john1", "anchor2" ] ); } ); QUnit.test( "attributes - ends with", function( assert ) { assert.expect( 4 ); assert.t( "string (whitespace ignored)", "a[href $= 'org/']", [ "mozilla" ] ); assert.t( "string ending with ']'", "input[name$='bar]']", [ "hidden2" ] ); assert.t( "string like '[' ... ']'", "input[name$='[bar]']", [ "hidden2" ] ); assert.t( "Attribute containing []", "input[name$='foo[bar]']", [ "hidden2" ] ); } ); QUnit.test( "attributes - whitespace list includes", function( assert ) { assert.expect( 3 ); assert.t( "string found at the beginning", "input[data-15233~='foo']", [ "t15233-single", "t15233-double", "t15233-double-tab", "t15233-double-nl", "t15233-triple" ] ); assert.t( "string found in the middle", "input[data-15233~='bar']", [ "t15233-double", "t15233-double-tab", "t15233-double-nl", "t15233-triple" ] ); assert.t( "string found at the end", "input[data-15233~='baz']", [ "t15233-triple" ] ); } ); QUnit.test( "attributes - hyphen-prefix matches", function( assert ) { assert.expect( 3 ); assert.t( "string", "#names-group span[id|='name']", [ "name-is-example", "name-is-div" ] ); assert.t( "string containing hyphen", "#names-group span[id|='name-is']", [ "name-is-example", "name-is-div" ] ); assert.t( "string ending with hyphen", "#names-group span[id|='name-is-']", [] ); } ); QUnit.test( "attributes - special characters", function( assert ) { assert.expect( 16 ); var attrbad; var div = document.createElement( "div" ); // trac-3729 div.innerHTML = "<div id='foo' xml:test='something'></div>"; assert.deepEqual( jQuery( "[xml\\:test]", div ).get(), [ div.firstChild ], "attribute name containing colon" ); // Make sure attribute value quoting works correctly. // See jQuery trac-6093; trac-6428; trac-13894. // Use seeded results to bypass querySelectorAll optimizations. attrbad = jQuery( "<input type='hidden' id='attrbad_space' name='foo bar'/>" +
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
true
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/test/unit/animation.js
test/unit/animation.js
( function() { // Can't test what ain't there if ( !includesModule( "effects" ) ) { return; } var fxInterval = 13, oldRaf = window.requestAnimationFrame, defaultPrefilter = jQuery.Animation.prefilters[ 0 ], defaultTweener = jQuery.Animation.tweeners[ "*" ][ 0 ], startTime = 505877050; // This module tests jQuery.Animation and the corresponding 1.8+ effects APIs QUnit.module( "animation", { beforeEach: function() { this.sandbox = sinon.createSandbox(); this.clock = this.sandbox.useFakeTimers( startTime ); window.requestAnimationFrame = null; jQuery.fx.step = {}; jQuery.Animation.prefilters = [ defaultPrefilter ]; jQuery.Animation.tweeners = { "*": [ defaultTweener ] }; }, afterEach: function() { this.sandbox.restore(); jQuery.fx.stop(); window.requestAnimationFrame = oldRaf; return moduleTeardown.apply( this, arguments ); } } ); QUnit.test( "Animation( subject, props, opts ) - shape", function( assert ) { assert.expect( 20 ); var subject = { test: 0 }, props = { test: 1 }, opts = { queue: "fx", duration: fxInterval * 10 }, animation = jQuery.Animation( subject, props, opts ); assert.equal( animation.elem, subject, ".elem is set to the exact object passed" ); assert.equal( animation.originalOptions, opts, ".originalOptions is set to options passed" ); assert.equal( animation.originalProperties, props, ".originalProperties is set to props passed" ); assert.notEqual( animation.props, props, ".props is not the original however" ); assert.deepEqual( animation.props, props, ".props is a copy of the original" ); assert.deepEqual( animation.opts, { duration: fxInterval * 10, queue: "fx", specialEasing: { test: undefined }, easing: jQuery.easing._default }, ".options is filled with default easing and specialEasing" ); assert.equal( animation.startTime, startTime, "startTime was set" ); assert.equal( animation.duration, fxInterval * 10, ".duration is set" ); assert.equal( animation.tweens.length, 1, ".tweens has one Tween" ); assert.equal( typeof animation.tweens[ 0 ].run, "function", "which has a .run function" ); assert.equal( typeof animation.createTween, "function", ".createTween is a function" ); assert.equal( typeof animation.stop, "function", ".stop is a function" ); assert.equal( typeof animation.done, "function", ".done is a function" ); assert.equal( typeof animation.fail, "function", ".fail is a function" ); assert.equal( typeof animation.always, "function", ".always is a function" ); assert.equal( typeof animation.progress, "function", ".progress is a function" ); assert.equal( jQuery.timers.length, 1, "Added a timers function" ); assert.equal( jQuery.timers[ 0 ].elem, subject, "...with .elem as the subject" ); assert.equal( jQuery.timers[ 0 ].anim, animation, "...with .anim as the animation" ); assert.equal( jQuery.timers[ 0 ].queue, opts.queue, "...with .queue" ); // Cleanup after ourselves by ticking to the end this.clock.tick( fxInterval * 10 ); } ); QUnit.test( "Animation.prefilter( fn ) - calls prefilter after defaultPrefilter", function( assert ) { assert.expect( 1 ); var prefilter = this.sandbox.stub(), defaultSpy = this.sandbox.spy( jQuery.Animation.prefilters, "0" ); jQuery.Animation.prefilter( prefilter ); jQuery.Animation( {}, {}, {} ); assert.ok( prefilter.calledAfter( defaultSpy ), "our prefilter called after" ); } ); QUnit.test( "Animation.prefilter( fn, true ) - calls prefilter before defaultPrefilter", function( assert ) { assert.expect( 1 ); var prefilter = this.sandbox.stub(), defaultSpy = this.sandbox.spy( jQuery.Animation.prefilters, "0" ); jQuery.Animation.prefilter( prefilter, true ); jQuery.Animation( {}, {}, {} ); assert.ok( prefilter.calledBefore( defaultSpy ), "our prefilter called before" ); } ); QUnit.test( "Animation.prefilter - prefilter return hooks", function( assert ) { assert.expect( 34 ); var animation, realAnimation, element, sandbox = this.sandbox, ourAnimation = { stop: this.sandbox.spy() }, target = { height: 50 }, props = { height: 100 }, opts = { duration: 100 }, prefilter = this.sandbox.spy( function() { realAnimation = this; sandbox.spy( realAnimation, "createTween" ); assert.deepEqual( realAnimation.originalProperties, props, "originalProperties" ); assert.equal( arguments[ 0 ], this.elem, "first param elem" ); assert.equal( arguments[ 1 ], this.props, "second param props" ); assert.equal( arguments[ 2 ], this.opts, "third param opts" ); return ourAnimation; } ), defaultSpy = sandbox.spy( jQuery.Animation.prefilters, "0" ), queueSpy = sandbox.spy( function( next ) { next(); } ), TweenSpy = sandbox.spy( jQuery, "Tween" ); jQuery.Animation.prefilter( prefilter, true ); sandbox.stub( jQuery.fx, "timer" ); animation = jQuery.Animation( target, props, opts ); assert.equal( prefilter.callCount, 1, "Called prefilter" ); assert.equal( defaultSpy.callCount, 0, "Returning something from a prefilter caused remaining prefilters to not run" ); assert.equal( jQuery.fx.timer.callCount, 0, "Returning something never queues a timer" ); assert.equal( animation, ourAnimation, "Returning something returned it from jQuery.Animation" ); assert.equal( realAnimation.createTween.callCount, 0, "Returning something never creates tweens" ); assert.equal( TweenSpy.callCount, 0, "Returning something never creates tweens" ); // Test overridden usage on queues: prefilter.resetHistory(); element = jQuery( "<div>" ) .css( "height", 50 ) .animate( props, 100 ) .queue( queueSpy ) .animate( props, 100 ) .queue( queueSpy ) .animate( props, 100 ) .queue( queueSpy ); assert.equal( prefilter.callCount, 1, "Called prefilter" ); assert.equal( queueSpy.callCount, 0, "Next function in queue not called" ); realAnimation.opts.complete.call( realAnimation.elem ); assert.equal( queueSpy.callCount, 1, "Next function in queue called after complete" ); assert.equal( prefilter.callCount, 2, "Called prefilter again - animation #2" ); assert.equal( ourAnimation.stop.callCount, 0, ".stop() on our animation hasn't been called" ); element.stop(); assert.equal( ourAnimation.stop.callCount, 1, ".stop() called ourAnimation.stop()" ); assert.ok( !ourAnimation.stop.args[ 0 ][ 0 ], ".stop( falsy ) (undefined or false are both valid)" ); assert.equal( queueSpy.callCount, 2, "Next queue function called" ); assert.ok( queueSpy.calledAfter( ourAnimation.stop ), "After our animation was told to stop" ); // ourAnimation.stop.reset(); assert.equal( prefilter.callCount, 3, "Got the next animation" ); ourAnimation.stop.resetHistory(); // do not clear queue, gotoEnd element.stop( false, true ); assert.ok( ourAnimation.stop.calledWith( true ), ".stop(true) calls .stop(true)" ); assert.ok( queueSpy.calledAfter( ourAnimation.stop ), "and the next queue function ran after we were told" ); } ); QUnit.test( "Animation.tweener( fn ) - unshifts a * tweener", function( assert ) { assert.expect( 2 ); var starTweeners = jQuery.Animation.tweeners[ "*" ]; jQuery.Animation.tweener( jQuery.noop ); assert.equal( starTweeners.length, 2 ); assert.deepEqual( starTweeners, [ jQuery.noop, defaultTweener ] ); } ); QUnit.test( "Animation.tweener( 'prop', fn ) - unshifts a 'prop' tweener", function( assert ) { assert.expect( 4 ); var tweeners = jQuery.Animation.tweeners, fn = function() {}; jQuery.Animation.tweener( "prop", jQuery.noop ); assert.equal( tweeners.prop.length, 1 ); assert.deepEqual( tweeners.prop, [ jQuery.noop ] ); jQuery.Animation.tweener( "prop", fn ); assert.equal( tweeners.prop.length, 2 ); assert.deepEqual( tweeners.prop, [ fn, jQuery.noop ] ); } ); QUnit.test( "Animation.tweener( 'list of props', fn ) - unshifts a tweener to each prop", function( assert ) { assert.expect( 2 ); var tweeners = jQuery.Animation.tweeners, fn = function() {}; jQuery.Animation.tweener( "list of props", jQuery.noop ); assert.deepEqual( tweeners, { list: [ jQuery.noop ], of: [ jQuery.noop ], props: [ jQuery.noop ], "*": [ defaultTweener ] } ); // Test with extra whitespaces jQuery.Animation.tweener( " list\t of \tprops\n*", fn ); assert.deepEqual( tweeners, { list: [ fn, jQuery.noop ], of: [ fn, jQuery.noop ], props: [ fn, jQuery.noop ], "*": [ fn, defaultTweener ] } ); } ); } )();
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
false
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/test/unit/serialize.js
test/unit/serialize.js
QUnit.module( "serialize", { afterEach: moduleTeardown } ); QUnit.test( "jQuery.param()", function( assert ) { assert.expect( 24 ); var params; params = { "foo": "bar", "baz": 42, "quux": "All your base are belong to us" }; assert.equal( jQuery.param( params ), "foo=bar&baz=42&quux=All%20your%20base%20are%20belong%20to%20us", "simple" ); params = { "string": "foo", "null": null, "undefined": undefined }; assert.equal( jQuery.param( params ), "string=foo&null=&undefined=", "handle nulls and undefineds properly" ); params = { "someName": [ 1, 2, 3 ], "regularThing": "blah" }; assert.equal( jQuery.param( params ), "someName%5B%5D=1&someName%5B%5D=2&someName%5B%5D=3&regularThing=blah", "with array" ); params = { "foo": [ "a", "b", "c" ] }; assert.equal( jQuery.param( params ), "foo%5B%5D=a&foo%5B%5D=b&foo%5B%5D=c", "with array of strings" ); params = { "foo": [ "baz", 42, "All your base are belong to us" ] }; assert.equal( jQuery.param( params ), "foo%5B%5D=baz&foo%5B%5D=42&foo%5B%5D=All%20your%20base%20are%20belong%20to%20us", "more array" ); params = { "foo": { "bar": "baz", "beep": 42, "quux": "All your base are belong to us" } }; assert.equal( jQuery.param( params ), "foo%5Bbar%5D=baz&foo%5Bbeep%5D=42&foo%5Bquux%5D=All%20your%20base%20are%20belong%20to%20us", "even more arrays" ); params = { a: [ 1, 2 ], b: { c: 3, d: [ 4, 5 ], e: { x: [ 6 ], y: 7, z: [ 8, 9 ] }, f: true, g: false, h: undefined }, i: [ 10, 11 ], j: true, k: false, l: [ undefined, 0 ], m: "cowboy hat?" }; assert.equal( decodeURIComponent( jQuery.param( params ) ), "a[]=1&a[]=2&b[c]=3&b[d][]=4&b[d][]=5&b[e][x][]=6&b[e][y]=7&b[e][z][]=8&b[e][z][]=9&b[f]=true&b[g]=false&b[h]=&i[]=10&i[]=11&j=true&k=false&l[]=&l[]=0&m=cowboy hat?", "huge structure" ); params = { "a": [ 0, [ 1, 2 ], [ 3, [ 4, 5 ], [ 6 ] ], { "b": [ 7, [ 8, 9 ], [ { "c": 10, "d": 11 } ], [ [ 12 ] ], [ [ [ 13 ] ] ], { "e": { "f": { "g": [ 14, [ 15 ] ] } } }, 16 ] }, 17 ] }; assert.equal( decodeURIComponent( jQuery.param( params ) ), "a[]=0&a[1][]=1&a[1][]=2&a[2][]=3&a[2][1][]=4&a[2][1][]=5&a[2][2][]=6&a[3][b][]=7&a[3][b][1][]=8&a[3][b][1][]=9&a[3][b][2][0][c]=10&a[3][b][2][0][d]=11&a[3][b][3][0][]=12&a[3][b][4][0][0][]=13&a[3][b][5][e][f][g][]=14&a[3][b][5][e][f][g][1][]=15&a[3][b][]=16&a[]=17", "nested arrays" ); params = { "a": [ 1, 2 ], "b": { "c": 3, "d": [ 4, 5 ], "e": { "x": [ 6 ], "y": 7, "z": [ 8, 9 ] }, "f": true, "g": false, "h": undefined }, "i": [ 10, 11 ], "j": true, "k": false, "l": [ undefined, 0 ], "m": "cowboy hat?" }; assert.equal( jQuery.param( params, true ), "a=1&a=2&b=%5Bobject%20Object%5D&i=10&i=11&j=true&k=false&l=&l=0&m=cowboy%20hat%3F", "huge structure, forced traditional" ); assert.equal( decodeURIComponent( jQuery.param( { "a": [ 1, 2, 3 ], "b[]": [ 4, 5, 6 ], "c[d]": [ 7, 8, 9 ], "e": { "f": [ 10 ], "g": [ 11, 12 ], "h": 13 } } ) ), "a[]=1&a[]=2&a[]=3&b[]=4&b[]=5&b[]=6&c[d][]=7&c[d][]=8&c[d][]=9&e[f][]=10&e[g][]=11&e[g][]=12&e[h]=13", "Make sure params are not double-encoded." ); // trac-7945 assert.equal( jQuery.param( { "jquery": "1.4.2" } ), "jquery=1.4.2", "Check that object with a jQuery property get serialized correctly" ); params = { "foo": "bar", "baz": 42, "quux": "All your base are belong to us" }; assert.equal( jQuery.param( params, true ), "foo=bar&baz=42&quux=All%20your%20base%20are%20belong%20to%20us", "simple" ); params = { "someName": [ 1, 2, 3 ], "regularThing": "blah" }; assert.equal( jQuery.param( params, true ), "someName=1&someName=2&someName=3&regularThing=blah", "with array" ); params = { "foo": [ "a", "b", "c" ] }; assert.equal( jQuery.param( params, true ), "foo=a&foo=b&foo=c", "with array of strings" ); params = { "foo[]": [ "baz", 42, "All your base are belong to us" ] }; assert.equal( jQuery.param( params, true ), "foo%5B%5D=baz&foo%5B%5D=42&foo%5B%5D=All%20your%20base%20are%20belong%20to%20us", "more array" ); params = { "foo[bar]": "baz", "foo[beep]": 42, "foo[quux]": "All your base are belong to us" }; assert.equal( jQuery.param( params, true ), "foo%5Bbar%5D=baz&foo%5Bbeep%5D=42&foo%5Bquux%5D=All%20your%20base%20are%20belong%20to%20us", "even more arrays" ); params = { a: [ 1, 2 ], b: { c: 3, d: [ 4, 5 ], e: { x: [ 6 ], y: 7, z: [ 8, 9 ] }, f: true, g: false, h: undefined }, i: [ 10, 11 ], j: true, k: false, l: [ undefined, 0 ], m: "cowboy hat?" }; assert.equal( jQuery.param( params, true ), "a=1&a=2&b=%5Bobject%20Object%5D&i=10&i=11&j=true&k=false&l=&l=0&m=cowboy%20hat%3F", "huge structure" ); params = { "a": [ 0, [ 1, 2 ], [ 3, [ 4, 5 ], [ 6 ] ], { "b": [ 7, [ 8, 9 ], [ { "c": 10, d: 11 } ], [ [ 12 ] ], [ [ [ 13 ] ] ], { "e": { "f": { "g": [ 14, [ 15 ] ] } } }, 16 ] }, 17 ] }; assert.equal( jQuery.param( params, true ), "a=0&a=1%2C2&a=3%2C4%2C5%2C6&a=%5Bobject%20Object%5D&a=17", "nested arrays (not possible when traditional == true)" ); params = { a: [ 1, 2 ], b: { c: 3, d: [ 4, 5 ], e: { x: [ 6 ], y: 7, z: [ 8, 9 ] }, f: true, g: false, h: undefined }, i: [ 10, 11 ], j: true, k: false, l: [ undefined, 0 ], m: "cowboy hat?" }; assert.equal( decodeURIComponent( jQuery.param( params ) ), "a[]=1&a[]=2&b[c]=3&b[d][]=4&b[d][]=5&b[e][x][]=6&b[e][y]=7&b[e][z][]=8&b[e][z][]=9&b[f]=true&b[g]=false&b[h]=&i[]=10&i[]=11&j=true&k=false&l[]=&l[]=0&m=cowboy hat?", "huge structure, forced not traditional" ); params = { "param1": null }; assert.equal( jQuery.param( params ), "param1=", "Make sure that null params aren't traversed." ); params = { "param1": function() {}, "param2": function() { return null; } }; assert.equal( jQuery.param( params, false ), "param1=&param2=", "object with function property that returns null value" ); params = { "test": { "length": 3, "foo": "bar" } }; assert.equal( jQuery.param( params ), "test%5Blength%5D=3&test%5Bfoo%5D=bar", "Sub-object with a length property" ); params = { "test": [ 1, 2, null ] }; assert.equal( jQuery.param( params ), "test%5B%5D=1&test%5B%5D=2&test%5B%5D=", "object with array property with null value" ); params = undefined; assert.equal( jQuery.param( params ), "", "jQuery.param( undefined ) === empty string" ); } ); QUnit[ includesModule( "ajax" ) ? "test" : "skip" ]( "jQuery.param() not affected by ajaxSettings", function( assert ) { assert.expect( 1 ); var oldTraditional = jQuery.ajaxSettings.traditional; jQuery.ajaxSettings.traditional = true; assert.equal( jQuery.param( { "foo": [ "a", "b", "c" ] } ), "foo%5B%5D=a&foo%5B%5D=b&foo%5B%5D=c", "ajaxSettings.traditional is ignored" ); jQuery.ajaxSettings.traditional = oldTraditional; } ); QUnit.test( "jQuery.param() Constructed prop values", function( assert ) { assert.expect( 4 ); /** @constructor */ function Record() { this.prop = "val"; } var MyString = String, MyNumber = Number, params = { "test": new MyString( "foo" ) }; assert.equal( jQuery.param( params, false ), "test=foo", "Do not mistake new String() for a plain object" ); params = { "test": new MyNumber( 5 ) }; assert.equal( jQuery.param( params, false ), "test=5", "Do not mistake new Number() for a plain object" ); params = { "test": new Date() }; assert.ok( jQuery.param( params, false ), "(Non empty string returned) Do not mistake new Date() for a plain object" ); // should allow non-native constructed objects params = { "test": new Record() }; assert.equal( jQuery.param( params, false ), jQuery.param( { "test": { "prop": "val" } } ), "Allow non-native constructed objects" ); } ); QUnit.test( "serialize()", function( assert ) { assert.expect( 6 ); // Add html5 elements only for serialize because selector can't yet find them on non-html5 browsers jQuery( "#search" ).after( "<input type='email' id='html5email' name='email' value='dave@jquery.com' />" + "<input type='number' id='html5number' name='number' value='43' />" + "<input type='file' name='fileupload' />" ); assert.equal( jQuery( "#form" ).serialize(), "action=Test&radio2=on&check=on&hidden=&foo%5Bbar%5D=&name=name&search=search&email=dave%40jquery.com&number=43&select1=&select2=3&select3=1&select3=2&select5=3", "Check form serialization as query string" ); assert.equal( jQuery( "input,select,textarea,button", "#form" ).serialize(), "action=Test&radio2=on&check=on&hidden=&foo%5Bbar%5D=&name=name&search=search&email=dave%40jquery.com&number=43&select1=&select2=3&select3=1&select3=2&select5=3", "Check input serialization as query string" ); assert.equal( jQuery( "#testForm" ).serialize(), "T3=%3F%0D%0AZ&H1=x&H2=&PWD=&T1=&T2=YES&My%20Name=me&S1=abc&S3=YES&S4=", "Check form serialization as query string" ); assert.equal( jQuery( "input,select,textarea,button", "#testForm" ).serialize(), "T3=%3F%0D%0AZ&H1=x&H2=&PWD=&T1=&T2=YES&My%20Name=me&S1=abc&S3=YES&S4=", "Check input serialization as query string" ); assert.equal( jQuery( "#form, #testForm" ).serialize(), "action=Test&radio2=on&check=on&hidden=&foo%5Bbar%5D=&name=name&search=search&email=dave%40jquery.com&number=43&select1=&select2=3&select3=1&select3=2&select5=3&T3=%3F%0D%0AZ&H1=x&H2=&PWD=&T1=&T2=YES&My%20Name=me&S1=abc&S3=YES&S4=", "Multiple form serialization as query string" ); assert.equal( jQuery( "#form, #testForm input, #testForm select, #testForm textarea, #testForm button" ).serialize(), "action=Test&radio2=on&check=on&hidden=&foo%5Bbar%5D=&name=name&search=search&email=dave%40jquery.com&number=43&select1=&select2=3&select3=1&select3=2&select5=3&T3=%3F%0D%0AZ&H1=x&H2=&PWD=&T1=&T2=YES&My%20Name=me&S1=abc&S3=YES&S4=", "Mixed form/input serialization as query string" ); jQuery( "#html5email, #html5number" ).remove(); } );
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
false
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/test/unit/tween.js
test/unit/tween.js
( function() { // Can't test what ain't there if ( !includesModule( "effects" ) ) { return; } var oldRaf = window.requestAnimationFrame; QUnit.module( "tween", { beforeEach: function() { this.sandbox = sinon.createSandbox(); this.clock = this.sandbox.useFakeTimers( 505877050 ); window.requestAnimationFrame = null; jQuery.fx.step = {}; }, afterEach: function() { this.sandbox.restore(); jQuery.fx.stop(); window.requestAnimationFrame = oldRaf; return moduleTeardown.apply( this, arguments ); } } ); QUnit.test( "jQuery.Tween - Default propHooks on plain objects", function( assert ) { assert.expect( 8 ); var propHooks, defaultHook, testObject, fakeTween, stepSpy; propHooks = jQuery.Tween.propHooks; assert.equal( typeof propHooks, "object", "jQuery.Tween.propHooks exists" ); defaultHook = propHooks._default; assert.ok( defaultHook, "_default propHook exists" ); testObject = { test: 0 }; fakeTween = { elem: testObject, prop: "test", now: 10, unit: "px" }; assert.equal( defaultHook.get( fakeTween ), 0, "Can get property of object" ); fakeTween.prop = "testMissing"; assert.equal( defaultHook.get( fakeTween ), undefined, "Can get missing property on object" ); defaultHook.set( fakeTween ); assert.equal( testObject.testMissing, 10, "Sets missing value properly on plain object" ); fakeTween.prop = "opacity"; defaultHook.set( fakeTween ); assert.equal( testObject.opacity, 10, "Correctly set opacity on plain object" ); fakeTween.prop = "test"; stepSpy = jQuery.fx.step.test = this.sandbox.spy(); defaultHook.set( fakeTween ); assert.ok( stepSpy.calledWith( fakeTween ), "Step function called with Tween" ); assert.equal( testObject.test, 0, "Because step didn't set, value is unchanged" ); } ); QUnit.test( "jQuery.Tween - Default propHooks on elements", function( assert ) { assert.expect( 19 ); var propHooks, defaultHook, testElement, fakeTween, cssStub, styleStub, stepSpy; propHooks = jQuery.Tween.propHooks; assert.equal( typeof propHooks, "object", "jQuery.Tween.propHooks exists" ); defaultHook = propHooks._default; assert.ok( defaultHook, "_default propHook exists" ); testElement = jQuery( "<div>" )[ 0 ]; fakeTween = { elem: testElement, prop: "height", now: 10, unit: "px" }; cssStub = this.sandbox.stub( jQuery, "css" ).returns( 10 ); assert.equal( defaultHook.get( fakeTween ), 10, "Gets expected style value" ); assert.ok( cssStub.calledWith( testElement, "height", "" ), "Calls jQuery.css correctly" ); fakeTween.prop = "testOpti"; testElement.testOpti = 15; cssStub.resetHistory(); assert.equal( defaultHook.get( fakeTween ), 15, "Gets expected value not defined on style" ); assert.equal( cssStub.callCount, 0, "Did not call jQuery.css" ); fakeTween.prop = "testMissing"; assert.equal( defaultHook.get( fakeTween ), 10, "Can get missing property on element" ); assert.ok( cssStub.calledWith( testElement, "testMissing", "" ), "...using jQuery.css" ); cssStub.returns( "" ); assert.equal( defaultHook.get( fakeTween ), 0, "Uses 0 for empty string" ); cssStub.returns( "auto" ); assert.equal( defaultHook.get( fakeTween ), 0, "Uses 0 for 'auto'" ); cssStub.returns( null ); assert.equal( defaultHook.get( fakeTween ), 0, "Uses 0 for null" ); cssStub.returns( undefined ); assert.equal( defaultHook.get( fakeTween ), 0, "Uses 0 for undefined" ); cssStub.resetHistory(); // Setters styleStub = this.sandbox.stub( jQuery, "style" ); fakeTween.prop = "height"; defaultHook.set( fakeTween ); assert.ok( styleStub.calledWith( testElement, "height", "10px" ), "Calls jQuery.style with elem, prop, now+unit" ); styleStub.resetHistory(); fakeTween.prop = "testMissing"; defaultHook.set( fakeTween ); assert.equal( styleStub.callCount, 0, "Did not call jQuery.style for non css property" ); assert.equal( testElement.testMissing, 10, "Instead, set value on element directly" ); jQuery.cssHooks.testMissing = jQuery.noop; fakeTween.now = 11; defaultHook.set( fakeTween ); delete jQuery.cssHooks.testMissing; assert.ok( styleStub.calledWith( testElement, "testMissing", "11px" ), "Presence of cssHooks causes jQuery.style with elem, prop, now+unit" ); assert.equal( testElement.testMissing, 10, "And value was unchanged" ); stepSpy = jQuery.fx.step.test = this.sandbox.spy(); styleStub.resetHistory(); fakeTween.prop = "test"; defaultHook.set( fakeTween ); assert.ok( stepSpy.calledWith( fakeTween ), "Step function called with Tween" ); assert.equal( styleStub.callCount, 0, "Did not call jQuery.style" ); } ); QUnit.test( "jQuery.Tween - Plain Object", function( assert ) { assert.expect( 13 ); var testObject = { test: 100 }, testOptions = { duration: 100 }, tween, easingSpy; tween = jQuery.Tween( testObject, testOptions, "test", 0, "linear" ); assert.equal( tween.elem, testObject, "Sets .element" ); assert.equal( tween.options, testOptions, "sets .options" ); assert.equal( tween.prop, "test", "sets .prop" ); assert.equal( tween.end, 0, "sets .end" ); assert.equal( tween.easing, "linear", "sets .easing when provided" ); assert.equal( tween.start, 100, "Reads .start value during construction" ); assert.equal( tween.now, 100, "Reads .now value during construction" ); easingSpy = this.sandbox.spy( jQuery.easing, "linear" ); assert.equal( tween.run( 0.1 ), tween, ".run() returns this" ); assert.equal( tween.now, 90, "Calculated tween" ); assert.ok( easingSpy.calledWith( 0.1, 0.1 * testOptions.duration, 0, 1, testOptions.duration ), "...using jQuery.easing.linear with back-compat arguments" ); assert.equal( testObject.test, 90, "Set value" ); tween.run( 1 ); assert.equal( testObject.test, 0, "Checking another value" ); tween.run( 0 ); assert.equal( testObject.test, 100, "Can even go back in time" ); } ); QUnit.test( "jQuery.Tween - Element", function( assert ) { assert.expect( 15 ); var testElement = jQuery( "<div>" ).css( "height", 100 )[ 0 ], testOptions = { duration: 100 }, tween, easingSpy, eased; tween = jQuery.Tween( testElement, testOptions, "height", 0 ); assert.equal( tween.elem, testElement, "Sets .element" ); assert.equal( tween.options, testOptions, "sets .options" ); assert.equal( tween.prop, "height", "sets .prop" ); assert.equal( tween.end, 0, "sets .end" ); assert.equal( tween.easing, jQuery.easing._default, "sets .easing to default when not provided" ); assert.equal( tween.unit, "px", "sets .unit to px when not provided" ); assert.equal( tween.start, 100, "Reads .start value during construction" ); assert.equal( tween.now, 100, "Reads .now value during construction" ); easingSpy = this.sandbox.spy( jQuery.easing, "swing" ); assert.equal( tween.run( 0.1 ), tween, ".run() returns this" ); assert.equal( tween.pos, jQuery.easing.swing( 0.1 ), "set .pos" ); eased = 100 - ( jQuery.easing.swing( 0.1 ) * 100 ); assert.equal( tween.now, eased, "Calculated tween" ); assert.ok( easingSpy.calledWith( 0.1, 0.1 * testOptions.duration, 0, 1, testOptions.duration ), "...using jQuery.easing.linear with back-compat arguments" ); assert.equal( parseFloat( testElement.style.height ).toFixed( 2 ), eased.toFixed( 2 ), "Set value" ); tween.run( 1 ); assert.equal( testElement.style.height, "0px", "Checking another value" ); tween.run( 0 ); assert.equal( testElement.style.height, "100px", "Can even go back in time" ); } ); QUnit.test( "jQuery.Tween - No duration", function( assert ) { assert.expect( 3 ); var testObject = { test: 100 }, testOptions = { duration: 0 }, tween, easingSpy; tween = jQuery.Tween( testObject, testOptions, "test", 0 ); easingSpy = this.sandbox.spy( jQuery.easing, "swing" ); tween.run( 0.5 ); assert.equal( tween.pos, 0.5, "set .pos correctly" ); assert.equal( testObject.test, 50, "set value on object correctly" ); assert.equal( easingSpy.callCount, 0, "didn't ease the value" ); } ); QUnit.test( "jQuery.Tween - step function option", function( assert ) { assert.expect( 4 ); var testObject = { test: 100 }, testOptions = { duration: 100, step: this.sandbox.spy() }, tween, propHookSpy; propHookSpy = this.sandbox.spy( jQuery.Tween.propHooks._default, "set" ); tween = jQuery.Tween( testObject, testOptions, "test", 0, "linear" ); assert.equal( testOptions.step.callCount, 0, "didn't call step on create" ); tween.run( 0.5 ); assert.ok( testOptions.step.calledOn( testObject ), "Called step function in context of animated object" ); assert.ok( testOptions.step.calledWith( 50, tween ), "Called step function with correct parameters" ); assert.ok( testOptions.step.calledBefore( propHookSpy ), "Called step function before calling propHook.set" ); } ); QUnit.test( "jQuery.Tween - custom propHooks", function( assert ) { assert.expect( 3 ); var testObject = {}, testOptions = { duration: 100, step: this.sandbox.spy() }, propHook = { get: sinon.stub().returns( 100 ), set: sinon.stub() }, tween; jQuery.Tween.propHooks.testHooked = propHook; tween = jQuery.Tween( testObject, testOptions, "testHooked", 0, "linear" ); assert.ok( propHook.get.calledWith( tween ), "called propHook.get on create" ); assert.equal( tween.now, 100, "Used return value from propHook.get" ); tween.run( 0.5 ); assert.ok( propHook.set.calledWith( tween ), "Called propHook.set function with correct parameters" ); delete jQuery.Tween.propHooks.testHooked; } ); QUnit.test( "jQuery.Tween - custom propHooks - advanced values", function( assert ) { assert.expect( 5 ); var testObject = {}, testOptions = { duration: 100, step: this.sandbox.spy() }, propHook = { get: sinon.stub().returns( [ 0, 0 ] ), set: sinon.spy() }, tween; jQuery.Tween.propHooks.testHooked = propHook; tween = jQuery.Tween( testObject, testOptions, "testHooked", [ 1, 1 ], "linear" ); assert.ok( propHook.get.calledWith( tween ), "called propHook.get on create" ); assert.deepEqual( tween.start, [ 0, 0 ], "Used return value from get" ); tween.run( 0.5 ); // Some day this NaN assumption might change - perhaps add a "calc" helper to the hooks? assert.ok( isNaN( tween.now ), "Used return value from propHook.get" ); assert.equal( tween.pos, 0.5, "But the eased percent is still available" ); assert.ok( propHook.set.calledWith( tween ), "Called propHook.set function with correct parameters" ); delete jQuery.Tween.propHooks.testHooked; } ); } )();
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
false
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/test/unit/event.js
test/unit/event.js
QUnit.module( "event", { beforeEach: function() { document.body.focus(); }, afterEach: moduleTeardown } ); QUnit.test( "null or undefined handler", function( assert ) { assert.expect( 4 ); // Supports Fixes bug trac-7229 try { jQuery( "#firstp" ).on( "click", null ); assert.ok( true, "Passing a null handler will not throw an exception" ); } catch ( e ) {} try { jQuery( "#firstp" ).on( "click", undefined ); assert.ok( true, "Passing an undefined handler will not throw an exception" ); } catch ( e ) {} var expectedElem = jQuery( "#firstp" ); var actualElem = expectedElem.on( "click", null ); assert.equal( actualElem, expectedElem, "Passing a null handler should return the original element" ); actualElem = expectedElem.on( "click", undefined ); assert.equal( actualElem, expectedElem, "Passing a null handler should return the original element" ); } ); QUnit.test( "on() with non-null,defined data", function( assert ) { assert.expect( 2 ); var handler = function( event, data ) { assert.equal( data, 0, "non-null, defined data (zero) is correctly passed" ); }; jQuery( "#foo" ).on( "foo.on", handler ); jQuery( "div" ).on( "foo.delegate", "#foo", handler ); jQuery( "#foo" ).trigger( "foo", 0 ); jQuery( "#foo" ).off( "foo.on", handler ); jQuery( "div" ).off( "foo.delegate", "#foo" ); } ); QUnit.test( "Handler changes and .trigger() order", function( assert ) { assert.expect( 1 ); var markup = jQuery( "<div><div><p><span><b class=\"a\">b</b></span></p></div></div>" ), path = ""; markup .find( "*" ).addBack().on( "click", function() { path += this.nodeName.toLowerCase() + " "; } ) .filter( "b" ).on( "click", function( e ) { // Removing span should not stop propagation to original parents if ( e.target === this ) { jQuery( this ).parent().remove(); } } ); markup.find( "b" ).trigger( "click" ); assert.equal( path, "b p div div ", "Delivered all events" ); markup.remove(); } ); QUnit.test( "on(), with data", function( assert ) { assert.expect( 4 ); var test, handler, handler2; handler = function( event ) { assert.ok( event.data, "on() with data, check passed data exists" ); assert.equal( event.data.foo, "bar", "on() with data, Check value of passed data" ); }; jQuery( "#firstp" ).on( "click", { "foo": "bar" }, handler ).trigger( "click" ).off( "click", handler ); assert.ok( !jQuery._data( jQuery( "#firstp" )[ 0 ], "events" ), "Event handler unbound when using data." ); test = function() {}; handler2 = function( event ) { assert.equal( event.data, test, "on() with function data, Check value of passed data" ); }; jQuery( "#firstp" ).on( "click", test, handler2 ).trigger( "click" ).off( "click", handler2 ); } ); QUnit.test( "click(), with data", function( assert ) { assert.expect( 3 ); var handler = function( event ) { assert.ok( event.data, "on() with data, check passed data exists" ); assert.equal( event.data.foo, "bar", "on() with data, Check value of passed data" ); }; jQuery( "#firstp" ).on( "click", { "foo": "bar" }, handler ).trigger( "click" ).off( "click", handler ); assert.ok( !jQuery._data( jQuery( "#firstp" )[ 0 ], "events" ), "Event handler unbound when using data." ); } ); QUnit.test( "on(), with data, trigger with data", function( assert ) { assert.expect( 4 ); var handler = function( event, data ) { assert.ok( event.data, "check passed data exists" ); assert.equal( event.data.foo, "bar", "Check value of passed data" ); assert.ok( data, "Check trigger data" ); assert.equal( data.bar, "foo", "Check value of trigger data" ); }; jQuery( "#firstp" ).on( "click", { foo: "bar" }, handler ).trigger( "click", [ { bar: "foo" } ] ).off( "click", handler ); } ); QUnit.test( "on(), multiple events at once", function( assert ) { assert.expect( 2 ); var handler, clickCounter = 0, mouseoverCounter = 0; handler = function( event ) { if ( event.type === "click" ) { clickCounter += 1; } else if ( event.type === "mouseover" ) { mouseoverCounter += 1; } }; jQuery( "#firstp" ).on( "click mouseover", handler ).trigger( "click" ).trigger( "mouseover" ); assert.equal( clickCounter, 1, "on() with multiple events at once" ); assert.equal( mouseoverCounter, 1, "on() with multiple events at once" ); } ); QUnit.test( "on(), five events at once", function( assert ) { assert.expect( 1 ); var count = 0, handler = function() { count++; }; jQuery( "#firstp" ).on( "click mouseover foo bar baz", handler ) .trigger( "click" ).trigger( "mouseover" ) .trigger( "foo" ).trigger( "bar" ) .trigger( "baz" ); assert.equal( count, 5, "on() five events at once" ); } ); QUnit.test( "on(), multiple events at once and namespaces", function( assert ) { assert.expect( 7 ); var cur, div, obj = {}; div = jQuery( "<div></div>" ).on( "focusin.a", function( e ) { assert.equal( e.type, cur, "Verify right single event was fired." ); } ); cur = "focusin"; div.trigger( "focusin.a" ); // manually clean up detached elements div.remove(); div = jQuery( "<div></div>" ).on( "click mouseover", obj, function( e ) { assert.equal( e.type, cur, "Verify right multi event was fired." ); assert.equal( e.data, obj, "Make sure the data came in correctly." ); } ); cur = "click"; div.trigger( "click" ); cur = "mouseover"; div.trigger( "mouseover" ); // manually clean up detached elements div.remove(); div = jQuery( "<div></div>" ).on( "focusin.a focusout.b", function( e ) { assert.equal( e.type, cur, "Verify right multi event was fired." ); } ); cur = "focusin"; div.trigger( "focusin.a" ); cur = "focusout"; div.trigger( "focusout.b" ); // manually clean up detached elements div.remove(); } ); QUnit.test( "on(), namespace with special add", function( assert ) { assert.expect( 27 ); var i = 0, div = jQuery( "<div></div>" ).appendTo( "#qunit-fixture" ).on( "test", function() { assert.ok( true, "Test event fired." ); } ); jQuery.event.special.test = { _default: function( e, data ) { assert.equal( e.type, "test", "Make sure we're dealing with a test event." ); assert.ok( data, "And that trigger data was passed." ); assert.strictEqual( e.target, div[ 0 ], "And that the target is correct." ); assert.equal( this, window, "And that the context is correct." ); }, setup: function() {}, teardown: function() { assert.ok( true, "Teardown called." ); }, add: function( handleObj ) { var handler = handleObj.handler; handleObj.handler = function( e ) { e.xyz = ++i; handler.apply( this, arguments ); }; }, remove: function() { assert.ok( true, "Remove called." ); } }; div.on( "test.a", { x: 1 }, function( e ) { assert.ok( !!e.xyz, "Make sure that the data is getting passed through." ); assert.equal( e.data.x, 1, "Make sure data is attached properly." ); } ); div.on( "test.b", { x: 2 }, function( e ) { assert.ok( !!e.xyz, "Make sure that the data is getting passed through." ); assert.equal( e.data.x, 2, "Make sure data is attached properly." ); } ); // Should trigger 5 div.trigger( "test", 33.33 ); // Should trigger 2 div.trigger( "test.a", "George Harrison" ); // Should trigger 2 div.trigger( "test.b", { year: 1982 } ); // Should trigger 4 div.off( "test" ); div = jQuery( "<div></div>" ).on( "test", function() { assert.ok( true, "Test event fired." ); } ); // Should trigger 2 div.appendTo( "#qunit-fixture" ).remove(); delete jQuery.event.special.test; } ); QUnit.test( "on(), no data", function( assert ) { assert.expect( 1 ); var handler = function( event ) { assert.ok( !event.data, "Check that no data is added to the event object" ); }; jQuery( "#firstp" ).on( "click", handler ).trigger( "click" ); } ); QUnit.test( "on/one/off(Object)", function( assert ) { assert.expect( 6 ); var $elem, clickCounter = 0, mouseoverCounter = 0; function handler( event ) { if ( event.type === "click" ) { clickCounter++; } else if ( event.type === "mouseover" ) { mouseoverCounter++; } } function handlerWithData( event ) { if ( event.type === "click" ) { clickCounter += event.data; } else if ( event.type === "mouseover" ) { mouseoverCounter += event.data; } } function trigger() { $elem.trigger( "click" ).trigger( "mouseover" ); } $elem = jQuery( "#firstp" ) // Regular bind .on( { "click": handler, "mouseover": handler } ) // Bind with data .one( { "click": handlerWithData, "mouseover": handlerWithData }, 2 ); trigger(); assert.equal( clickCounter, 3, "on(Object)" ); assert.equal( mouseoverCounter, 3, "on(Object)" ); trigger(); assert.equal( clickCounter, 4, "on(Object)" ); assert.equal( mouseoverCounter, 4, "on(Object)" ); jQuery( "#firstp" ).off( { "click": handler, "mouseover": handler } ); trigger(); assert.equal( clickCounter, 4, "on(Object)" ); assert.equal( mouseoverCounter, 4, "on(Object)" ); } ); QUnit.test( "on/off(Object), on/off(Object, String)", function( assert ) { assert.expect( 6 ); var events, clickCounter = 0, mouseoverCounter = 0, $p = jQuery( "#firstp" ), $a = $p.find( "a" ).eq( 0 ); events = { "click": function( event ) { clickCounter += ( event.data || 1 ); }, "mouseover": function( event ) { mouseoverCounter += ( event.data || 1 ); } }; function trigger() { $a.trigger( "click" ).trigger( "mouseover" ); } jQuery( document ).on( events, "#firstp a" ); $p.on( events, "a", 2 ); trigger(); assert.equal( clickCounter, 3, "on" ); assert.equal( mouseoverCounter, 3, "on" ); $p.off( events, "a" ); trigger(); assert.equal( clickCounter, 4, "off" ); assert.equal( mouseoverCounter, 4, "off" ); jQuery( document ).off( events, "#firstp a" ); trigger(); assert.equal( clickCounter, 4, "off" ); assert.equal( mouseoverCounter, 4, "off" ); } ); QUnit.test( "on immediate propagation", function( assert ) { assert.expect( 2 ); var lastClick, $p = jQuery( "#firstp" ), $a = $p.find( "a" ).eq( 0 ); lastClick = ""; jQuery( document ).on( "click", "#firstp a", function( e ) { lastClick = "click1"; e.stopImmediatePropagation(); } ); jQuery( document ).on( "click", "#firstp a", function() { lastClick = "click2"; } ); $a.trigger( "click" ); assert.equal( lastClick, "click1", "on stopImmediatePropagation" ); jQuery( document ).off( "click", "#firstp a" ); lastClick = ""; $p.on( "click", "a", function( e ) { lastClick = "click1"; e.stopImmediatePropagation(); } ); $p.on( "click", "a", function() { lastClick = "click2"; } ); $a.trigger( "click" ); assert.equal( lastClick, "click1", "on stopImmediatePropagation" ); $p.off( "click", "**" ); } ); QUnit.test( "on bubbling, isDefaultPrevented, stopImmediatePropagation", function( assert ) { assert.expect( 3 ); var $anchor2 = jQuery( "#anchor2" ), $main = jQuery( "#qunit-fixture" ), neverCallMe = function() { assert.ok( false, "immediate propagation should have been stopped" ); }, fakeClick = function( $jq ) { // Use a native click so we don't get jQuery simulated bubbling var e = document.createEvent( "MouseEvents" ); e.initEvent( "click", true, true ); $jq[ 0 ].dispatchEvent( e ); }; $anchor2.on( "click", function( e ) { e.preventDefault(); } ); $main.on( "click", "#foo", function( e ) { assert.equal( e.isDefaultPrevented(), true, "isDefaultPrevented true passed to bubbled event" ); } ); fakeClick( $anchor2 ); $anchor2.off( "click" ); $main.off( "click", "**" ); $anchor2.on( "click", function() { // Let the default action occur } ); $main.on( "click", "#foo", function( e ) { assert.equal( e.isDefaultPrevented(), false, "isDefaultPrevented false passed to bubbled event" ); } ); fakeClick( $anchor2 ); $anchor2.off( "click" ); $main.off( "click", "**" ); $anchor2.on( "click", function( e ) { e.stopImmediatePropagation(); assert.ok( true, "anchor was clicked and prop stopped" ); } ); $anchor2[ 0 ].addEventListener( "click", neverCallMe, false ); fakeClick( $anchor2 ); $anchor2[ 0 ].removeEventListener( "click", neverCallMe ); } ); QUnit.test( "triggered events stopPropagation() for natively-bound events", function( assert ) { assert.expect( 1 ); var $button = jQuery( "#button" ), $parent = $button.parent(), neverCallMe = function() { assert.ok( false, "propagation should have been stopped" ); }, stopPropagationCallback = function( e ) { assert.ok( true, "propagation is stopped" ); e.stopPropagation(); }; $parent[ 0 ].addEventListener( "click", neverCallMe ); $button.on( "click", stopPropagationCallback ); $button.trigger( "click" ); $parent[ 0 ].removeEventListener( "click", neverCallMe ); $button.off( "click", stopPropagationCallback ); } ); QUnit.test( "trigger() works with events that were previously stopped", function( assert ) { assert.expect( 0 ); var $button = jQuery( "#button" ), $parent = $button.parent(), neverCallMe = function() { assert.ok( false, "propagation should have been stopped" ); }; $parent[ 0 ].addEventListener( "click", neverCallMe ); $button.on( "click", neverCallMe ); var clickEvent = jQuery.Event( "click" ); clickEvent.stopPropagation(); $button.trigger( clickEvent ); $parent[ 0 ].removeEventListener( "click", neverCallMe ); $button.off( "click", neverCallMe ); } ); QUnit.test( "on(), iframes", function( assert ) { assert.expect( 1 ); // events don't work with iframes, see trac-939 - this test fails in IE because of contentDocument var doc = jQuery( "#loadediframe" ).contents(); jQuery( "div", doc ).on( "click", function() { assert.ok( true, "Binding to element inside iframe" ); } ).trigger( "click" ).off( "click" ); } ); QUnit.test( "on(), trigger change on select", function( assert ) { assert.expect( 5 ); var counter = 0; function selectOnChange( event ) { assert.equal( event.data, counter++, "Event.data is not a global event object" ); } jQuery( "#form select" ).each( function( i ) { jQuery( this ).on( "change", i, selectOnChange ); } ).trigger( "change" ); } ); QUnit.test( "on(), namespaced events, cloned events", function( assert ) { assert.expect( 18 ); var firstp = jQuery( "#firstp" ); firstp.on( "custom.test", function() { assert.ok( false, "Custom event triggered" ); } ); firstp.on( "click", function( e ) { assert.ok( true, "Normal click triggered" ); assert.equal( e.type + e.namespace, "click", "Check that only click events trigger this fn" ); } ); firstp.on( "click.test", function( e ) { var check = "click"; assert.ok( true, "Namespaced click triggered" ); if ( e.namespace ) { check += "test"; } assert.equal( e.type + e.namespace, check, "Check that only click/click.test events trigger this fn" ); } ); //clone(true) element to verify events are cloned correctly firstp = firstp.add( firstp.clone( true ).attr( "id", "firstp2" ).insertBefore( firstp ) ); // Trigger both bound fn (8) firstp.trigger( "click" ); // Trigger one bound fn (4) firstp.trigger( "click.test" ); // Remove only the one fn firstp.off( "click.test" ); // Trigger the remaining fn (4) firstp.trigger( "click" ); // Remove the remaining namespaced fn firstp.off( ".test" ); // Try triggering the custom event (0) firstp.trigger( "custom" ); // using contents will get comments regular, text, and comment nodes jQuery( "#nonnodes" ).contents().on( "tester", function() { assert.equal( this.nodeType, 1, "Check node,textnode,comment on just does real nodes" ); } ).trigger( "tester" ); // Make sure events stick with appendTo'd elements (which are cloned) trac-2027 jQuery( "<a href='#fail' class='test'>test</a>" ).on( "click", function() { return false; } ).appendTo( "#qunit-fixture" ); assert.ok( jQuery( "a.test" ).eq( 0 ).triggerHandler( "click" ) === false, "Handler is bound to appendTo'd elements" ); } ); QUnit.test( "on(), multi-namespaced events", function( assert ) { assert.expect( 6 ); var order = [ "click.test.abc", "click.test.abc", "click.test", "click.test.abc", "click.test", "custom.test2" ]; function check( name, msg ) { assert.deepEqual( name, order.shift(), msg ); } jQuery( "#firstp" ).on( "custom.test", function() { check( "custom.test", "Custom event triggered" ); } ); jQuery( "#firstp" ).on( "custom.test2", function() { check( "custom.test2", "Custom event triggered" ); } ); jQuery( "#firstp" ).on( "click.test", function() { check( "click.test", "Normal click triggered" ); } ); jQuery( "#firstp" ).on( "click.test.abc", function() { check( "click.test.abc", "Namespaced click triggered" ); } ); // Those would not trigger/off (trac-5303) jQuery( "#firstp" ).trigger( "click.a.test" ); jQuery( "#firstp" ).off( "click.a.test" ); // Trigger both bound fn (1) jQuery( "#firstp" ).trigger( "click.test.abc" ); // Trigger one bound fn (1) jQuery( "#firstp" ).trigger( "click.abc" ); // Trigger two bound fn (2) jQuery( "#firstp" ).trigger( "click.test" ); // Remove only the one fn jQuery( "#firstp" ).off( "click.abc" ); // Trigger the remaining fn (1) jQuery( "#firstp" ).trigger( "click" ); // Remove the remaining fn jQuery( "#firstp" ).off( ".test" ); // Trigger the remaining fn (1) jQuery( "#firstp" ).trigger( "custom" ); } ); QUnit.test( "namespace-only event binding is a no-op", function( assert ) { assert.expect( 2 ); jQuery( "#firstp" ) .on( ".whoops", function() { assert.ok( false, "called a namespace-only event" ); } ) .on( "whoops", function() { assert.ok( true, "called whoops" ); } ) .trigger( "whoops" ) // 1 .off( ".whoops" ) .trigger( "whoops" ) // 2 .off( "whoops" ); } ); QUnit.test( "Empty namespace is ignored", function( assert ) { assert.expect( 1 ); jQuery( "#firstp" ) .on( "meow.", function( e ) { assert.equal( e.namespace, "", "triggered a namespace-less meow event" ); } ) .trigger( "meow." ) .off( "meow." ); } ); QUnit.test( "on(), with same function", function( assert ) { assert.expect( 2 ); var count = 0, func = function() { count++; }; jQuery( "#liveHandlerOrder" ).on( "foo.bar", func ).on( "foo.zar", func ); jQuery( "#liveHandlerOrder" ).trigger( "foo.bar" ); assert.equal( count, 1, "Verify binding function with multiple namespaces." ); jQuery( "#liveHandlerOrder" ).off( "foo.bar", func ).off( "foo.zar", func ); jQuery( "#liveHandlerOrder" ).trigger( "foo.bar" ); assert.equal( count, 1, "Verify that removing events still work." ); } ); QUnit.test( "on(), make sure order is maintained", function( assert ) { assert.expect( 1 ); var elem = jQuery( "#firstp" ), log = [], check = []; jQuery.each( new Array( 100 ), function( i ) { elem.on( "click", function() { log.push( i ); } ); check.push( i ); } ); elem.trigger( "click" ); assert.equal( log.join( "," ), check.join( "," ), "Make sure order was maintained." ); elem.off( "click" ); } ); QUnit.test( "on(), with different this object", function( assert ) { assert.expect( 4 ); var thisObject = { myThis: true }, data = { myData: true }, handler1 = function() { assert.equal( this, thisObject, "on() with different this object" ); }.bind( thisObject ), handler2 = function( event ) { assert.equal( this, thisObject, "on() with different this object and data" ); assert.equal( event.data, data, "on() with different this object and data" ); }.bind( thisObject ); jQuery( "#firstp" ) .on( "click", handler1 ).trigger( "click" ).off( "click", handler1 ) .on( "click", data, handler2 ).trigger( "click" ).off( "click", handler2 ); assert.ok( !jQuery._data( jQuery( "#firstp" )[ 0 ], "events" ), "Event handler unbound when using different this object and data." ); } ); QUnit.test( "on(name, false), off(name, false)", function( assert ) { assert.expect( 3 ); var main = 0; jQuery( "#qunit-fixture" ).on( "click", function() { main++; } ); jQuery( "#ap" ).trigger( "click" ); assert.equal( main, 1, "Verify that the trigger happened correctly." ); main = 0; jQuery( "#ap" ).on( "click", false ); jQuery( "#ap" ).trigger( "click" ); assert.equal( main, 0, "Verify that no bubble happened." ); main = 0; jQuery( "#ap" ).off( "click", false ); jQuery( "#ap" ).trigger( "click" ); assert.equal( main, 1, "Verify that the trigger happened correctly." ); // manually clean up events from elements outside the fixture jQuery( "#qunit-fixture" ).off( "click" ); } ); QUnit.test( "on(name, selector, false), off(name, selector, false)", function( assert ) { assert.expect( 3 ); var main = 0; jQuery( "#qunit-fixture" ).on( "click", "#ap", function() { main++; } ); jQuery( "#ap" ).trigger( "click" ); assert.equal( main, 1, "Verify that the trigger happened correctly." ); main = 0; jQuery( "#ap" ).on( "click", "#groups", false ); jQuery( "#groups" ).trigger( "click" ); assert.equal( main, 0, "Verify that no bubble happened." ); main = 0; jQuery( "#ap" ).off( "click", "#groups", false ); jQuery( "#groups" ).trigger( "click" ); assert.equal( main, 1, "Verify that the trigger happened correctly." ); jQuery( "#qunit-fixture" ).off( "click", "#ap" ); } ); QUnit.test( "on()/trigger()/off() on plain object", function( assert ) { assert.expect( 7 ); var events, obj = {}; // Make sure it doesn't complain when no events are found jQuery( obj ).trigger( "test" ); // Make sure it doesn't complain when no events are found jQuery( obj ).off( "test" ); jQuery( obj ).on( { "test": function() { assert.ok( true, "Custom event run." ); }, "submit": function() { assert.ok( true, "Custom submit event run." ); } } ); events = jQuery._data( obj, "events" ); assert.ok( events, "Object has events bound." ); assert.equal( obj.events, undefined, "Events object on plain objects is not events" ); assert.equal( obj.test, undefined, "Make sure that test event is not on the plain object." ); assert.equal( obj.handle, undefined, "Make sure that the event handler is not on the plain object." ); // Should trigger 1 jQuery( obj ).trigger( "test" ); jQuery( obj ).trigger( "submit" ); jQuery( obj ).off( "test" ); jQuery( obj ).off( "submit" ); // Should trigger 0 jQuery( obj ).trigger( "test" ); // Make sure it doesn't complain when no events are found jQuery( obj ).off( "test" ); assert.equal( obj && obj[ jQuery.expando ] && obj[ jQuery.expando ][ jQuery.expando ] && obj[ jQuery.expando ][ jQuery.expando ].events, undefined, "Make sure events object is removed" ); } ); QUnit.test( "off(type)", function( assert ) { assert.expect( 1 ); var message, func, $elem = jQuery( "#firstp" ); function error() { assert.ok( false, message ); } message = "unbind passing function"; $elem.on( "error1", error ).off( "error1", error ).triggerHandler( "error1" ); message = "unbind all from event"; $elem.on( "error1", error ).off( "error1" ).triggerHandler( "error1" ); message = "unbind all"; $elem.on( "error1", error ).off().triggerHandler( "error1" ); message = "unbind many with function"; $elem.on( "error1 error2", error ) .off( "error1 error2", error ) .trigger( "error1" ).triggerHandler( "error2" ); message = "unbind many"; // trac-3538 $elem.on( "error1 error2", error ) .off( "error1 error2" ) .trigger( "error1" ).triggerHandler( "error2" ); message = "unbind without a type or handler"; $elem.on( "error1 error2.test", error ) .off() .trigger( "error1" ).triggerHandler( "error2" ); // Should only unbind the specified function jQuery( document ).on( "click", function() { assert.ok( true, "called handler after selective removal" ); } ); func = function() {}; jQuery( document ) .on( "click", func ) .off( "click", func ) .trigger( "click" ) .off( "click" ); } ); QUnit.test( "off(eventObject)", function( assert ) { assert.expect( 4 ); var $elem = jQuery( "#firstp" ), num; function check( expected ) { num = 0; $elem.trigger( "foo" ).triggerHandler( "bar" ); assert.equal( num, expected, "Check the right handlers are triggered" ); } $elem // This handler shouldn't be unbound .on( "foo", function() { num += 1; } ) .on( "foo", function( e ) { $elem.off( e ); num += 2; } ) // Neither this one .on( "bar", function() { num += 4; } ); check( 7 ); check( 5 ); $elem.off( "bar" ); check( 1 ); $elem.off(); check( 0 ); } ); QUnit.test( "mouseover triggers mouseenter", function( assert ) { assert.expect( 1 ); var count = 0, elem = jQuery( "<a></a>" ); elem.on( "mouseenter", function() { count++; } ); elem.trigger( "mouseover" ); assert.equal( count, 1, "make sure mouseover triggers a mouseenter" ); elem.remove(); } ); QUnit.test( "pointerover triggers pointerenter", function( assert ) { assert.expect( 1 ); var count = 0, elem = jQuery( "<a></a>" ); elem.on( "pointerenter", function() { count++; } ); elem.trigger( "pointerover" ); assert.equal( count, 1, "make sure pointerover triggers a pointerenter" ); elem.remove(); } ); QUnit.test( "withinElement implemented with jQuery.contains()", function( assert ) { assert.expect( 1 ); jQuery( "#qunit-fixture" ).append( "<div id='jc-outer'><div id='jc-inner'></div></div>" ); jQuery( "#jc-outer" ).on( "mouseenter mouseleave", function( event ) { assert.equal( this.id, "jc-outer", this.id + " " + event.type ); } ); jQuery( "#jc-inner" ).trigger( "mouseenter" ); } ); QUnit.test( "mouseenter, mouseleave don't catch exceptions", function( assert ) { assert.expect( 2 ); var elem = jQuery( "#firstp" ).on( "mouseenter mouseleave", function() { throw "an Exception"; } ); try { elem.trigger( "mouseenter" ); } catch ( e ) { assert.equal( e, "an Exception", "mouseenter doesn't catch exceptions" ); } try { elem.trigger( "mouseleave" ); } catch ( e ) { assert.equal( e, "an Exception", "mouseleave doesn't catch exceptions" ); } } ); QUnit.test( "trigger() bubbling", function( assert ) { assert.expect( 18 ); var win = 0, doc = 0, html = 0, body = 0, main = 0, ap = 0; jQuery( window ).on( "click", function() { win++; } ); jQuery( document ).on( "click", function( e ) { if ( e.target !== document ) { doc++; } } ); jQuery( "html" ).on( "click", function() { html++; } ); jQuery( "body" ).on( "click", function() { body++; } ); jQuery( "#qunit-fixture" ).on( "click", function() { main++; } ); jQuery( "#ap" ).on( "click", function() { ap++; return false; } ); jQuery( "html" ).trigger( "click" ); assert.equal( win, 1, "HTML bubble" ); assert.equal( doc, 1, "HTML bubble" ); assert.equal( html, 1, "HTML bubble" ); jQuery( "body" ).trigger( "click" ); assert.equal( win, 2, "Body bubble" ); assert.equal( doc, 2, "Body bubble" ); assert.equal( html, 2, "Body bubble" ); assert.equal( body, 1, "Body bubble" ); jQuery( "#qunit-fixture" ).trigger( "click" ); assert.equal( win, 3, "Main bubble" ); assert.equal( doc, 3, "Main bubble" ); assert.equal( html, 3, "Main bubble" ); assert.equal( body, 2, "Main bubble" ); assert.equal( main, 1, "Main bubble" ); jQuery( "#ap" ).trigger( "click" ); assert.equal( doc, 3, "ap bubble" ); assert.equal( html, 3, "ap bubble" ); assert.equal( body, 2, "ap bubble" ); assert.equal( main, 1, "ap bubble" ); assert.equal( ap, 1, "ap bubble" ); jQuery( document ).trigger( "click" ); assert.equal( win, 4, "doc bubble" ); // manually clean up events from elements outside the fixture jQuery( window ).off( "click" ); jQuery( document ).off( "click" ); jQuery( "html, body, #qunit-fixture" ).off( "click" ); } ); QUnit.test( "trigger(type, [data], [fn])", function( assert ) { assert.expect( 16 ); var $elem, pass, form, elem2, handler = function( event, a, b, c ) { assert.equal( event.type, "click", "check passed data" ); assert.equal( a, 1, "check passed data" ); assert.equal( b, "2", "check passed data" ); assert.equal( c, "abc", "check passed data" ); return "test"; }; $elem = jQuery( "#firstp" ); // Simulate a "native" click $elem[ 0 ].click = function() { assert.ok( true, "Native call was triggered" ); }; jQuery( document ).on( "mouseenter", "#firstp", function() { assert.ok( true, "Trigger mouseenter bound by on" ); } ); jQuery( document ).on( "mouseleave", "#firstp", function() { assert.ok( true, "Trigger mouseleave bound by on" ); } ); $elem.trigger( "mouseenter" ); $elem.trigger( "mouseleave" ); jQuery( document ).off( "mouseenter mouseleave", "#firstp" ); // Triggers handlers and native // Trigger 5 $elem.on( "click", handler ).trigger( "click", [ 1, "2", "abc" ] ); // Simulate a "native" click $elem[ 0 ].click = function() { assert.ok( false, "Native call was triggered" ); }; // Trigger only the handlers (no native) // Triggers 5 assert.equal( $elem.triggerHandler( "click", [ 1, "2", "abc" ] ), "test", "Verify handler response" ); pass = true; try { elem2 = jQuery( "#form input" ).eq( 0 ); elem2.get( 0 ).style.display = "none"; elem2.trigger( "focus" ); } catch ( e ) { pass = false; } assert.ok( pass, "Trigger focus on hidden element" ); pass = true; try { jQuery( "#qunit-fixture table" ).eq( 0 ).on( "test:test", function() {} ).trigger( "test:test" ); } catch ( e ) { pass = false; } assert.ok( pass, "Trigger on a table with a colon in the even type, see trac-3533" ); form = jQuery( "<form action=''></form>" ).appendTo( "body" ); // Make sure it can be prevented locally form.on( "submit", function() { assert.ok( true, "Local `on` still works." ); return false; } ); // Trigger 1 form.trigger( "submit" ); form.off( "submit" ); jQuery( document ).on( "submit", function() { assert.ok( true, "Make sure bubble works up to document." ); return false; } ); // Trigger 1 form.trigger( "submit" ); jQuery( document ).off( "submit" ); form.remove(); } ); QUnit.test( "submit event bubbles on copied forms (trac-11649)", function( assert ) { assert.expect( 3 ); var $formByClone, $formByHTML, $testForm = jQuery( "#testForm" ), $fixture = jQuery( "#qunit-fixture" ), $wrapperDiv = jQuery( "<div></div>" ).appendTo( $fixture ); function noSubmit( e ) { e.preventDefault(); } function delegatedSubmit() { assert.ok( true, "Make sure submit event bubbles up." ); return false; } // Attach a delegated submit handler to the parent element $fixture.on( "submit", "form", delegatedSubmit ); // Trigger form submission to introduce the _submit_attached property $testForm.on( "submit", noSubmit ).find( "input[name=sub1]" ).trigger( "click" ); // Copy the form via .clone() and .html() $formByClone = $testForm.clone( true, true ).removeAttr( "id" ); $formByHTML = jQuery( jQuery.parseHTML( $fixture.html() ) ).filter( "#testForm" ).removeAttr( "id" ); $wrapperDiv.append( $formByClone, $formByHTML ); // Check submit bubbling on the copied forms $wrapperDiv.find( "form" ).on( "submit", noSubmit ).find( "input[name=sub1]" ).trigger( "click" ); // Clean up $wrapperDiv.remove(); $fixture.off( "submit", "form", delegatedSubmit ); $testForm.off( "submit", noSubmit ); } ); QUnit.test( "change event bubbles on copied forms (trac-11796)", function( assert ) { assert.expect( 3 ); var $formByClone, $formByHTML, $form = jQuery( "#form" ), $fixture = jQuery( "#qunit-fixture" ), $wrapperDiv = jQuery( "<div></div>" ).appendTo( $fixture ); function delegatedChange() { assert.ok( true, "Make sure change event bubbles up." ); return false; } // Attach a delegated change handler to the form $fixture.on( "change", "form", delegatedChange ); // Trigger change event to introduce the _change_attached property $form.find( "select[name=select1]" ).val( "1" ).trigger( "change" ); // Copy the form via .clone() and .html() $formByClone = $form.clone( true, true ).removeAttr( "id" ); $formByHTML = jQuery( jQuery.parseHTML( $fixture.html() ) ).filter( "#form" ).removeAttr( "id" ); $wrapperDiv.append( $formByClone, $formByHTML ); // Check change bubbling on the copied forms $wrapperDiv.find( "form select[name=select1]" ).val( "2" ).trigger( "change" ); // Clean up $wrapperDiv.remove(); $fixture.off( "change", "form", delegatedChange ); } ); QUnit.test( "trigger(eventObject, [data], [fn])", function( assert ) { assert.expect( 28 ); var event, $parent = jQuery( "<div id='par'></div>" ).appendTo( "body" ), $child = jQuery( "<p id='child'>foo</p>" ).appendTo( $parent ); $parent.get( 0 ).style.display = "none"; event = jQuery.Event( "noNew" ); assert.ok( event !== window, "Instantiate jQuery.Event without the 'new' keyword" ); assert.equal( event.type, "noNew", "Verify its type" );
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
true
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/test/unit/queue.js
test/unit/queue.js
QUnit.module( "queue", { afterEach: moduleTeardown } ); ( function() { if ( !includesModule( "queue" ) ) { return; } QUnit.test( "queue() with other types", function( assert ) { var done = assert.async( 2 ); assert.expect( 14 ); var $div = jQuery( {} ), counter = 0; $div.promise( "foo" ).done( function() { assert.equal( counter, 0, "Deferred for collection with no queue is automatically resolved" ); } ); $div .queue( "foo", function() { assert.equal( ++counter, 1, "Dequeuing" ); jQuery.dequeue( this, "foo" ); } ) .queue( "foo", function() { assert.equal( ++counter, 2, "Dequeuing" ); jQuery( this ).dequeue( "foo" ); } ) .queue( "foo", function() { assert.equal( ++counter, 3, "Dequeuing" ); } ) .queue( "foo", function() { assert.equal( ++counter, 4, "Dequeuing" ); } ); $div.promise( "foo" ).done( function() { assert.equal( counter, 4, "Testing previous call to dequeue in deferred" ); done(); } ); assert.equal( $div.queue( "foo" ).length, 4, "Testing queue length" ); assert.equal( $div.queue( "foo", undefined ).queue( "foo" ).length, 4, ".queue('name',undefined) does nothing but is chainable (trac-5571)" ); $div.dequeue( "foo" ); assert.equal( counter, 3, "Testing previous call to dequeue" ); assert.equal( $div.queue( "foo" ).length, 1, "Testing queue length" ); $div.dequeue( "foo" ); assert.equal( counter, 4, "Testing previous call to dequeue" ); assert.equal( $div.queue( "foo" ).length, 0, "Testing queue length" ); $div.dequeue( "foo" ); assert.equal( counter, 4, "Testing previous call to dequeue" ); assert.equal( $div.queue( "foo" ).length, 0, "Testing queue length" ); done(); } ); QUnit.test( "queue(name) passes in the next item in the queue as a parameter", function( assert ) { assert.expect( 2 ); var div = jQuery( {} ), counter = 0; div.queue( "foo", function( next ) { assert.equal( ++counter, 1, "Dequeueing" ); next(); } ).queue( "foo", function( next ) { assert.equal( ++counter, 2, "Next was called" ); next(); } ).queue( "bar", function() { assert.equal( ++counter, 3, "Other queues are not triggered by next()" ); } ); div.dequeue( "foo" ); } ); QUnit.test( "queue() passes in the next item in the queue as a parameter to fx queues", function( assert ) { var done = assert.async(); assert.expect( 3 ); var div = jQuery( {} ), counter = 0; div.queue( function( next ) { assert.equal( ++counter, 1, "Dequeueing" ); setTimeout( function() { next(); }, 500 ); } ).queue( function( next ) { assert.equal( ++counter, 2, "Next was called" ); next(); } ).queue( "bar", function() { assert.equal( ++counter, 3, "Other queues are not triggered by next()" ); } ); jQuery.when( div.promise( "fx" ), div ).done( function() { assert.equal( counter, 2, "Deferreds resolved" ); done(); } ); } ); QUnit.test( "callbacks keep their place in the queue", function( assert ) { var done = assert.async(); assert.expect( 5 ); var div = jQuery( "<div>" ), counter = 0; div.queue( function( next ) { assert.equal( ++counter, 1, "Queue/callback order: first called" ); setTimeout( next, 200 ); } ).delay( 100 ).queue( function( next ) { assert.equal( ++counter, 2, "Queue/callback order: second called" ); jQuery( this ).delay( 100 ).queue( function( next ) { assert.equal( ++counter, 4, "Queue/callback order: fourth called" ); next(); } ); next(); } ).queue( function( next ) { assert.equal( ++counter, 3, "Queue/callback order: third called" ); next(); } ); div.promise( "fx" ).done( function() { assert.equal( counter, 4, "Deferreds resolved" ); done(); } ); } ); QUnit.test( "jQuery.queue should return array while manipulating the queue", function( assert ) { assert.expect( 1 ); var div = document.createElement( "div" ); assert.ok( Array.isArray( jQuery.queue( div, "fx", jQuery.noop ) ), "jQuery.queue should return an array while manipulating the queue" ); } ); QUnit.test( "delay()", function( assert ) { var done = assert.async(); assert.expect( 2 ); var foo = jQuery( {} ), run = 0; foo.delay( 100 ).queue( function() { run = 1; assert.ok( true, "The function was dequeued." ); done(); } ); assert.equal( run, 0, "The delay delayed the next function from running." ); } ); QUnit.test( "clearQueue(name) clears the queue", function( assert ) { var done = assert.async( 2 ); assert.expect( 2 ); var div = jQuery( {} ), counter = 0; div.queue( "foo", function( next ) { counter++; jQuery( this ).clearQueue( "foo" ); next(); } ).queue( "foo", function() { counter++; } ); div.promise( "foo" ).done( function() { assert.ok( true, "dequeue resolves the deferred" ); done(); } ); div.dequeue( "foo" ); assert.equal( counter, 1, "the queue was cleared" ); done(); } ); QUnit.test( "clearQueue() clears the fx queue", function( assert ) { assert.expect( 1 ); var div = jQuery( {} ), counter = 0; div.queue( function( next ) { counter++; var self = this; setTimeout( function() { jQuery( self ).clearQueue(); next(); }, 50 ); } ).queue( function() { counter++; } ); assert.equal( counter, 1, "the queue was cleared" ); div.removeData(); } ); QUnit.test( "fn.promise() - called when fx queue is empty", function( assert ) { assert.expect( 3 ); var foo = jQuery( "#foo" ).clone().addBack(), promised = false, done = assert.async(); foo.queue( function( next ) { // called twice! assert.ok( !promised, "Promised hasn't been called" ); setTimeout( next, 10 ); } ); foo.promise().done( function() { assert.ok( promised = true, "Promised" ); done(); } ); } ); QUnit.test( "fn.promise( \"queue\" ) - called whenever last queue function is dequeued", function( assert ) { assert.expect( 5 ); var done = assert.async(); var foo = jQuery( "#foo" ), test; foo.promise( "queue" ).done( function() { assert.strictEqual( test, undefined, "called immediately when queue was already empty" ); } ); test = 1; foo.queue( "queue", function( next ) { assert.strictEqual( test++, 1, "step one" ); setTimeout( next, 0 ); } ).queue( "queue", function( next ) { assert.strictEqual( test++, 2, "step two" ); setTimeout( function() { next(); assert.strictEqual( test++, 4, "step four" ); done(); }, 10 ); } ).promise( "queue" ).done( function() { assert.strictEqual( test++, 3, "step three" ); } ); foo.dequeue( "queue" ); } ); if ( includesModule( "effects" ) ) { QUnit.test( "fn.promise( \"queue\" ) - waits for animation to complete before resolving", function( assert ) { assert.expect( 2 ); var done = assert.async(); var foo = jQuery( "#foo" ), test = 1; foo.animate( { top: 100 }, { duration: 1, queue: "queue", complete: function() { assert.strictEqual( test++, 1, "step one" ); } } ).dequeue( "queue" ); foo.promise( "queue" ).done( function() { assert.strictEqual( test++, 2, "step two" ); done(); } ); } ); } QUnit.test( ".promise(obj)", function( assert ) { assert.expect( 2 ); var obj = {}, promise = jQuery( "#foo" ).promise( "promise", obj ); assert.ok( typeof promise.promise === "function", ".promise(type, obj) returns a promise" ); assert.strictEqual( promise, obj, ".promise(type, obj) returns obj" ); } ); QUnit[ includesModule( "effects" ) ? "test" : "skip" ]( "delay() can be stopped", function( assert ) { var done = assert.async(); assert.expect( 3 ); var storage = {}; jQuery( {} ) .queue( "alternate", function( next ) { storage.alt1 = true; assert.ok( true, "This first function was dequeued" ); next(); } ) .delay( 1000, "alternate" ) .queue( "alternate", function() { storage.alt2 = true; assert.ok( true, "The function was dequeued immediately, the delay was stopped" ); } ) .dequeue( "alternate" ) // stop( "alternate", false ) will NOT clear the queue, so it should automatically dequeue the next .stop( "alternate", false, false ) // this test .delay( 1 ) .queue( function() { storage.default1 = true; assert.ok( false, "This queue should never run" ); } ) // stop( clearQueue ) should clear the queue .stop( true, false ); assert.deepEqual( storage, { alt1: true, alt2: true }, "Queue ran the proper functions" ); setTimeout( function() { done(); }, 1500 ); } ); QUnit[ includesModule( "effects" ) ? "test" : "skip" ]( "queue stop hooks", function( assert ) { assert.expect( 2 ); var done = assert.async(); var foo = jQuery( "#foo" ); foo.queue( function( next, hooks ) { hooks.stop = function( gotoEnd ) { assert.equal( !!gotoEnd, false, "Stopped without gotoEnd" ); }; } ); foo.stop(); foo.queue( function( next, hooks ) { hooks.stop = function( gotoEnd ) { assert.equal( gotoEnd, true, "Stopped with gotoEnd" ); done(); }; } ); foo.stop( false, true ); } ); } )();
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
false
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/test/unit/traversing.js
test/unit/traversing.js
QUnit.module( "traversing", { afterEach: moduleTeardown } ); QUnit.test( "find(String)", function( assert ) { assert.expect( 1 ); assert.equal( jQuery( "#foo" ).find( ".blogTest" ).text(), "Yahoo", "Basic selector" ); } ); QUnit.test( "find(String) under non-elements", function( assert ) { assert.expect( 2 ); var j = jQuery( "#nonnodes" ).contents(); assert.equal( j.find( "div" ).length, 0, "Check node,textnode,comment to find zero divs" ); assert.equal( j.find( "div" ).addBack().length, 3, "Check node,textnode,comment to find zero divs, but preserves pushStack" ); } ); QUnit.test( "find(leading combinator)", function( assert ) { assert.expect( 4 ); assert.deepEqual( jQuery( "#qunit-fixture" ).find( "> div" ).get(), q( "foo", "nothiddendiv", "moretests", "tabindex-tests", "liveHandlerOrder", "siblingTest", "fx-test-group" ), "find child elements" ); assert.deepEqual( jQuery( "#qunit-fixture" ).find( "> #foo, > #moretests" ).get(), q( "foo", "moretests" ), "find child elements" ); assert.deepEqual( jQuery( "#qunit-fixture" ).find( "> #foo > p" ).get(), q( "sndp", "en", "sap" ), "find child elements" ); assert.deepEqual( jQuery( "#siblingTest, #siblingfirst" ).find( "+ *" ).get(), q( "siblingnext", "fx-test-group" ), "ensure document order" ); } ); QUnit.test( "find(node|jQuery object)", function( assert ) { assert.expect( 13 ); var $foo = jQuery( "#foo" ), $blog = jQuery( ".blogTest" ), $first = jQuery( "#first" ), $two = $blog.add( $first ), $twoMore = jQuery( "#ap" ).add( $blog ), $fooTwo = $foo.add( $blog ); assert.equal( $foo.find( $blog ).text(), "Yahoo", "Find with blog jQuery object" ); assert.equal( $foo.find( $blog[ 0 ] ).text(), "Yahoo", "Find with blog node" ); assert.equal( $foo.find( $first ).length, 0, "#first is not in #foo" ); assert.equal( $foo.find( $first[ 0 ] ).length, 0, "#first not in #foo (node)" ); assert.deepEqual( $foo.find( $two ).get(), $blog.get(), "Find returns only nodes within #foo" ); assert.deepEqual( $foo.find( $twoMore ).get(), $blog.get(), "...regardless of order" ); assert.ok( $fooTwo.find( $blog ).is( ".blogTest" ), "Blog is part of the collection, but also within foo" ); assert.ok( $fooTwo.find( $blog[ 0 ] ).is( ".blogTest" ), "Blog is part of the collection, but also within foo(node)" ); assert.equal( $two.find( $foo ).length, 0, "Foo is not in two elements" ); assert.equal( $two.find( $foo[ 0 ] ).length, 0, "Foo is not in two elements(node)" ); assert.equal( $two.find( $first ).length, 0, "first is in the collection and not within two" ); assert.equal( $two.find( $first ).length, 0, "first is in the collection and not within two(node)" ); assert.equal( $two.find( $foo[ 0 ] ).addBack().length, 2, "find preserves the pushStack, see trac-12009" ); } ); QUnit.test( "is(falsy|invalid)", function( assert ) { assert.expect( 5 ); assert.ok( !jQuery( "#foo" ).is( 0 ), "Expected false for an invalid expression - 0" ); assert.ok( !jQuery( "#foo" ).is( null ), "Expected false for an invalid expression - null" ); assert.ok( !jQuery( "#foo" ).is( "" ), "Expected false for an invalid expression - \"\"" ); assert.ok( !jQuery( "#foo" ).is( undefined ), "Expected false for an invalid expression - undefined" ); assert.ok( !jQuery( "#foo" ).is( { plain: "object" } ), "Check passing invalid object" ); } ); QUnit.test( "is(String)", function( assert ) { assert.expect( 33 ); var link = document.getElementById( "john1" ), input = document.getElementById( "text1" ), option = document.getElementById( "option1a" ), disconnected = document.createElement( "div" ); assert.ok( jQuery( "#form" ).is( "form" ), "Check for element: A form must be a form" ); assert.ok( !jQuery( "#form" ).is( "div" ), "Check for element: A form is not a div" ); assert.ok( jQuery( "#mozilla" ).is( ".blog" ), "Check for class: Expected class 'blog'" ); assert.ok( !jQuery( "#mozilla" ).is( ".link" ), "Check for class: Did not expect class 'link'" ); assert.ok( jQuery( "#timmy" ).is( ".blog.link" ), "Check for multiple classes: Expected classes 'blog' and 'link'" ); assert.ok( !jQuery( "#timmy" ).is( ".blogTest" ), "Check for multiple classes: Expected classes 'blog' and 'link', but not 'blogTest'" ); assert.ok( jQuery( "#en" ).is( "[lang=\"en\"]" ), "Check for attribute: Expected attribute lang to be 'en'" ); assert.ok( !jQuery( "#en" ).is( "[lang=\"de\"]" ), "Check for attribute: Expected attribute lang to be 'en', not 'de'" ); assert.ok( jQuery( "#text1" ).is( "[type=\"text\"]" ), "Check for attribute: Expected attribute type to be 'text'" ); assert.ok( !jQuery( "#text1" ).is( "[type=\"radio\"]" ), "Check for attribute: Expected attribute type to be 'text', not 'radio'" ); assert.ok( jQuery( "#text2" ).is( ":disabled" ), "Check for pseudoclass: Expected to be disabled" ); assert.ok( !jQuery( "#text1" ).is( ":disabled" ), "Check for pseudoclass: Expected not disabled" ); assert.ok( jQuery( "#radio2" ).is( ":checked" ), "Check for pseudoclass: Expected to be checked" ); assert.ok( !jQuery( "#radio1" ).is( ":checked" ), "Check for pseudoclass: Expected not checked" ); // test is() with comma-separated expressions assert.ok( jQuery( "#en" ).is( "[lang=\"en\"],[lang=\"de\"]" ), "Comma-separated; Check for lang attribute: Expect en or de" ); assert.ok( jQuery( "#en" ).is( "[lang=\"de\"],[lang=\"en\"]" ), "Comma-separated; Check for lang attribute: Expect en or de" ); assert.ok( jQuery( "#en" ).is( "[lang=\"en\"] , [lang=\"de\"]" ), "Comma-separated; Check for lang attribute: Expect en or de" ); assert.ok( jQuery( "#en" ).is( "[lang=\"de\"] , [lang=\"en\"]" ), "Comma-separated; Check for lang attribute: Expect en or de" ); link.title = "Don't click me"; assert.ok( jQuery( link ).is( "[rel='bookmark']" ), "attribute-equals string (delimited via apostrophes)" ); assert.ok( jQuery( link ).is( "[rel=bookmark]" ), "attribute-equals identifier" ); assert.ok( jQuery( link ).is( "[\nrel = bookmark\t]" ), "attribute-equals identifier (whitespace ignored)" ); assert.ok( jQuery( link ).is( "a[title=\"Don't click me\"]" ), "attribute-equals string containing single quote" ); // jQuery trac-12303 input.setAttribute( "data-pos", ":first" ); assert.ok( jQuery( input ).is( "input[data-pos=\\:first]" ), "attribute-equals POS in identifier" ); assert.ok( jQuery( input ).is( "input[data-pos=':first']" ), "attribute-equals POS in string" ); if ( QUnit.jQuerySelectors ) { assert.ok( jQuery( input ).is( ":input[data-pos=':first']" ), "attribute-equals POS in string after pseudo" ); } else { assert.ok( "skip", ":input not supported in selector-native" ); } option.setAttribute( "test", "" ); assert.ok( jQuery( option ).is( "[id=option1a]" ), "id attribute-equals identifier" ); if ( QUnit.jQuerySelectors ) { assert.ok( jQuery( option ).is( "[id*=option1][type!=checkbox]" ), "attribute-not-equals identifier" ); } else { assert.ok( "skip", "attribute-not-equals not supported in selector-native" ); } assert.ok( jQuery( option ).is( "[id*=option1]" ), "attribute-contains identifier" ); assert.ok( !jQuery( option ).is( "[test^='']" ), "attribute-starts-with empty string (negative)" ); option.className = "=]"; assert.ok( jQuery( option ).is( ".\\=\\]" ), "class selector with attribute-equals confusable" ); assert.ok( jQuery( disconnected ).is( "div" ), "disconnected element" ); assert.ok( jQuery( link ).is( "* > *" ), "child combinator matches in document" ); assert.ok( !jQuery( disconnected ).is( "* > *" ), "child combinator fails in fragment" ); } ); QUnit.test( "is() against non-elements (trac-10178)", function( assert ) { assert.expect( 14 ); var label, i, test, collection = jQuery( document ), tests = [ "a", "*" ], nonelements = { text: document.createTextNode( "" ), comment: document.createComment( "" ), document: document, window: window, array: [], "plain object": {}, "function": function() {} }; for ( label in nonelements ) { collection[ 0 ] = nonelements[ label ]; for ( i = 0; i < tests.length; i++ ) { test = tests[ i ]; assert.ok( !collection.is( test ), label + " does not match \"" + test + "\"" ); } } } ); QUnit.test( "is(jQuery)", function( assert ) { assert.expect( 19 ); assert.ok( jQuery( "#form" ).is( jQuery( "form" ) ), "Check for element: A form is a form" ); assert.ok( !jQuery( "#form" ).is( jQuery( "div" ) ), "Check for element: A form is not a div" ); assert.ok( jQuery( "#mozilla" ).is( jQuery( ".blog" ) ), "Check for class: Expected class 'blog'" ); assert.ok( !jQuery( "#mozilla" ).is( jQuery( ".link" ) ), "Check for class: Did not expect class 'link'" ); assert.ok( jQuery( "#timmy" ).is( jQuery( ".blog.link" ) ), "Check for multiple classes: Expected classes 'blog' and 'link'" ); assert.ok( !jQuery( "#timmy" ).is( jQuery( ".blogTest" ) ), "Check for multiple classes: Expected classes 'blog' and 'link', but not 'blogTest'" ); assert.ok( jQuery( "#en" ).is( jQuery( "[lang=\"en\"]" ) ), "Check for attribute: Expected attribute lang to be 'en'" ); assert.ok( !jQuery( "#en" ).is( jQuery( "[lang=\"de\"]" ) ), "Check for attribute: Expected attribute lang to be 'en', not 'de'" ); assert.ok( jQuery( "#text1" ).is( jQuery( "[type=\"text\"]" ) ), "Check for attribute: Expected attribute type to be 'text'" ); assert.ok( !jQuery( "#text1" ).is( jQuery( "[type=\"radio\"]" ) ), "Check for attribute: Expected attribute type to be 'text', not 'radio'" ); assert.ok( !jQuery( "#text1" ).is( jQuery( "input:disabled" ) ), "Check for pseudoclass: Expected not disabled" ); assert.ok( jQuery( "#radio2" ).is( jQuery( "input:checked" ) ), "Check for pseudoclass: Expected to be checked" ); assert.ok( !jQuery( "#radio1" ).is( jQuery( "input:checked" ) ), "Check for pseudoclass: Expected not checked" ); // Some raw elements assert.ok( jQuery( "#form" ).is( jQuery( "#qunit-fixture form" )[ 0 ] ), "Check for element: A form is a form" ); assert.ok( !jQuery( "#form" ).is( jQuery( "div" )[ 0 ] ), "Check for element: A form is not a div" ); assert.ok( jQuery( "#mozilla" ).is( jQuery( ".blog" )[ 0 ] ), "Check for class: Expected class 'blog'" ); assert.ok( !jQuery( "#mozilla" ).is( jQuery( ".link" )[ 0 ] ), "Check for class: Did not expect class 'link'" ); assert.ok( jQuery( "#timmy" ).is( jQuery( ".blog.link" )[ 0 ] ), "Check for multiple classes: Expected classes 'blog' and 'link'" ); assert.ok( !jQuery( "#timmy" ).is( jQuery( ".blogTest" )[ 0 ] ), "Check for multiple classes: Expected classes 'blog' and 'link', but not 'blogTest'" ); } ); QUnit[ QUnit.jQuerySelectors ? "test" : "skip" ]( "is() with :has() selectors", function( assert ) { assert.expect( 6 ); assert.ok( jQuery( "#foo" ).is( ":has(p)" ), "Check for child: Expected a child 'p' element" ); assert.ok( !jQuery( "#foo" ).is( ":has(ul)" ), "Check for child: Did not expect 'ul' element" ); assert.ok( jQuery( "#foo" ).is( ":has(p):has(a):has(code)" ), "Check for children: Expected 'p', 'a' and 'code' child elements" ); assert.ok( !jQuery( "#foo" ).is( ":has(p):has(a):has(code):has(ol)" ), "Check for children: Expected 'p', 'a' and 'code' child elements, but no 'ol'" ); assert.ok( jQuery( "#foo" ).is( jQuery( "div:has(p)" ) ), "Check for child: Expected a child 'p' element" ); assert.ok( !jQuery( "#foo" ).is( jQuery( "div:has(ul)" ) ), "Check for child: Did not expect 'ul' element" ); } ); QUnit[ QUnit.jQuerySelectorsPos ? "test" : "skip" ]( "is() with positional selectors", function( assert ) { assert.expect( 27 ); var posp = jQuery( "<p id='posp'><a class='firsta' href='#'><em>first</em></a>" + "<a class='seconda' href='#'><b>test</b></a><em></em></p>" ).appendTo( "#qunit-fixture" ), isit = function( sel, match, expect ) { assert.equal( jQuery( sel ).is( match ), expect, "jQuery('" + sel + "').is('" + match + "')" ); }; isit( "#posp", "p:last", true ); isit( "#posp", "#posp:first", true ); isit( "#posp", "#posp:eq(2)", false ); isit( "#posp", "#posp a:first", false ); isit( "#posp .firsta", "#posp a:first", true ); isit( "#posp .firsta", "#posp a:last", false ); isit( "#posp .firsta", "#posp a:even", true ); isit( "#posp .firsta", "#posp a:odd", false ); isit( "#posp .firsta", "#posp a:eq(0)", true ); isit( "#posp .firsta", "#posp a:eq(9)", false ); isit( "#posp .firsta", "#posp em:eq(0)", false ); isit( "#posp .firsta", "#posp em:first", false ); isit( "#posp .firsta", "#posp:first", false ); isit( "#posp .seconda", "#posp a:first", false ); isit( "#posp .seconda", "#posp a:last", true ); isit( "#posp .seconda", "#posp a:gt(0)", true ); isit( "#posp .seconda", "#posp a:lt(5)", true ); isit( "#posp .seconda", "#posp a:lt(1)", false ); isit( "#posp em", "#posp a:eq(0) em", true ); isit( "#posp em", "#posp a:lt(1) em", true ); isit( "#posp em", "#posp a:gt(1) em", false ); isit( "#posp em", "#posp a:first em", true ); isit( "#posp em", "#posp a em:last", true ); isit( "#posp em", "#posp a em:eq(2)", false ); assert.ok( jQuery( "#option1b" ).is( "#select1 option:not(:first)" ), "POS inside of :not() (trac-10970)" ); assert.ok( jQuery( posp[ 0 ] ).is( "p:last" ), "context constructed from a single node (trac-13797)" ); assert.ok( !jQuery( posp[ 0 ] ).find( "#firsta" ).is( "a:first" ), "context derived from a single node (trac-13797)" ); } ); QUnit.test( "index()", function( assert ) { assert.expect( 2 ); assert.equal( jQuery( "#text2" ).index(), 2, "Returns the index of a child amongst its siblings" ); assert.equal( jQuery( "<div></div>" ).index(), -1, "Node without parent returns -1" ); } ); QUnit.test( "index(Object|String|undefined)", function( assert ) { assert.expect( 16 ); var elements = jQuery( [ window, document ] ), inputElements = jQuery( "#radio1,#radio2,#check1,#check2" ); // Passing a node assert.equal( elements.index( window ), 0, "Check for index of elements" ); assert.equal( elements.index( document ), 1, "Check for index of elements" ); assert.equal( inputElements.index( document.getElementById( "radio1" ) ), 0, "Check for index of elements" ); assert.equal( inputElements.index( document.getElementById( "radio2" ) ), 1, "Check for index of elements" ); assert.equal( inputElements.index( document.getElementById( "check1" ) ), 2, "Check for index of elements" ); assert.equal( inputElements.index( document.getElementById( "check2" ) ), 3, "Check for index of elements" ); assert.equal( inputElements.index( window ), -1, "Check for not found index" ); assert.equal( inputElements.index( document ), -1, "Check for not found index" ); // Passing a jQuery object // enabled since [5500] assert.equal( elements.index( elements ), 0, "Pass in a jQuery object" ); assert.equal( elements.index( elements.eq( 1 ) ), 1, "Pass in a jQuery object" ); assert.equal( jQuery( "#form input[type='radio']" ).index( jQuery( "#radio2" ) ), 1, "Pass in a jQuery object" ); // Passing a selector or nothing // enabled since [6330] assert.equal( jQuery( "#text2" ).index(), 2, "Check for index amongst siblings" ); assert.equal( jQuery( "#form" ).children().eq( 4 ).index(), 4, "Check for index amongst siblings" ); assert.equal( jQuery( "#radio2" ).index( "#form input[type='radio']" ), 1, "Check for index within a selector" ); assert.equal( jQuery( "#form input[type='radio']" ).index( jQuery( "#radio2" ) ), 1, "Check for index within a selector" ); assert.equal( jQuery( "#radio2" ).index( "#form input[type='text']" ), -1, "Check for index not found within a selector" ); } ); QUnit.test( "filter(Selector|undefined)", function( assert ) { assert.expect( 9 ); assert.deepEqual( jQuery( "#form input" ).filter( ":checked" ).get(), q( "radio2", "check1" ), "filter(String)" ); assert.deepEqual( jQuery( "p" ).filter( "#ap, #sndp" ).get(), q( "ap", "sndp" ), "filter('String, String')" ); assert.deepEqual( jQuery( "p" ).filter( "#ap,#sndp" ).get(), q( "ap", "sndp" ), "filter('String,String')" ); assert.deepEqual( jQuery( "p" ).filter( null ).get(), [], "filter(null) should return an empty jQuery object" ); assert.deepEqual( jQuery( "p" ).filter( undefined ).get(), [], "filter(undefined) should return an empty jQuery object" ); assert.deepEqual( jQuery( "p" ).filter( 0 ).get(), [], "filter(0) should return an empty jQuery object" ); assert.deepEqual( jQuery( "p" ).filter( "" ).get(), [], "filter('') should return an empty jQuery object" ); // using contents will get comments regular, text, and comment nodes var j = jQuery( "#nonnodes" ).contents(); assert.equal( j.filter( "span" ).length, 1, "Check node,textnode,comment to filter the one span" ); assert.equal( j.filter( "[name]" ).length, 0, "Check node,textnode,comment to filter the one span" ); } ); QUnit.test( "filter(Function)", function( assert ) { assert.expect( 2 ); assert.deepEqual( jQuery( "#qunit-fixture p" ).filter( function() { return !jQuery( "a", this ).length; } ).get(), q( "sndp", "first" ), "filter(Function)" ); assert.deepEqual( jQuery( "#qunit-fixture p" ).filter( function( i, elem ) { return !jQuery( "a", elem ).length; } ).get(), q( "sndp", "first" ), "filter(Function) using arg" ); } ); QUnit.test( "filter(Element)", function( assert ) { assert.expect( 1 ); var element = document.getElementById( "text1" ); assert.deepEqual( jQuery( "#form input" ).filter( element ).get(), q( "text1" ), "filter(Element)" ); } ); QUnit.test( "filter(Array)", function( assert ) { assert.expect( 1 ); var elements = [ document.getElementById( "text1" ) ]; assert.deepEqual( jQuery( "#form input" ).filter( elements ).get(), q( "text1" ), "filter(Element)" ); } ); QUnit.test( "filter(jQuery)", function( assert ) { assert.expect( 1 ); var elements = jQuery( "#text1" ); assert.deepEqual( jQuery( "#form input" ).filter( elements ).get(), q( "text1" ), "filter(Element)" ); } ); QUnit[ QUnit.jQuerySelectorsPos ? "test" : "skip" ]( "filter() with positional selectors", function( assert ) { assert.expect( 19 ); var filterit = function( sel, filter, length ) { assert.equal( jQuery( sel ).filter( filter ).length, length, "jQuery( " + sel + " ).filter( " + filter + " )" ); }; jQuery( "" + "<p id='posp'>" + "<a class='firsta' href='#'>" + "<em>first</em>" + "</a>" + "<a class='seconda' href='#'>" + "<b>test</b>" + "</a>" + "<em></em>" + "</p>" ).appendTo( "#qunit-fixture" ); filterit( "#posp", "#posp:first", 1 ); filterit( "#posp", "#posp:eq(2)", 0 ); filterit( "#posp", "#posp a:first", 0 ); // Keep in mind this is within the selection and // not in relation to other elements (.is() is a different story) filterit( "#posp .firsta", "#posp a:first", 1 ); filterit( "#posp .firsta", "#posp a:last", 1 ); filterit( "#posp .firsta", "#posp a:last-child", 0 ); filterit( "#posp .firsta", "#posp a:even", 1 ); filterit( "#posp .firsta", "#posp a:odd", 0 ); filterit( "#posp .firsta", "#posp a:eq(0)", 1 ); filterit( "#posp .firsta", "#posp a:eq(9)", 0 ); filterit( "#posp .firsta", "#posp em:eq(0)", 0 ); filterit( "#posp .firsta", "#posp em:first", 0 ); filterit( "#posp .firsta", "#posp:first", 0 ); filterit( "#posp .seconda", "#posp a:first", 1 ); filterit( "#posp .seconda", "#posp em:first", 0 ); filterit( "#posp .seconda", "#posp a:last", 1 ); filterit( "#posp .seconda", "#posp a:gt(0)", 0 ); filterit( "#posp .seconda", "#posp a:lt(5)", 1 ); filterit( "#posp .seconda", "#posp a:lt(1)", 1 ); } ); QUnit.test( "closest()", function( assert ) { assert.expect( 14 ); var jq; assert.deepEqual( jQuery( "body" ).closest( "body" ).get(), q( "body" ), "closest(body)" ); assert.deepEqual( jQuery( "body" ).closest( "html" ).get(), q( "html" ), "closest(html)" ); assert.deepEqual( jQuery( "body" ).closest( "div" ).get(), [], "closest(div)" ); assert.deepEqual( jQuery( "#qunit-fixture" ).closest( "span,#html" ).get(), q( "html" ), "closest(span,#html)" ); // Test .closest() limited by the context jq = jQuery( "#nothiddendivchild" ); assert.deepEqual( jq.closest( "html", document.body ).get(), [], "Context limited." ); assert.deepEqual( jq.closest( "body", document.body ).get(), [], "Context limited." ); assert.deepEqual( jq.closest( "#nothiddendiv", document.body ).get(), q( "nothiddendiv" ), "Context not reached." ); //Test that .closest() returns unique'd set assert.equal( jQuery( "#qunit-fixture p" ).closest( "#qunit-fixture" ).length, 1, "Closest should return a unique set" ); // Test on disconnected node assert.equal( jQuery( "<div><p></p></div>" ).find( "p" ).closest( "table" ).length, 0, "Make sure disconnected closest work." ); assert.deepEqual( jQuery( "#firstp" ).closest( q( "qunit-fixture" ) ).get(), q( "qunit-fixture" ), "Non-string match target" ); // Bug trac-7369 assert.equal( jQuery( "<div foo='bar'></div>" ).closest( "[foo]" ).length, 1, "Disconnected nodes with attribute selector" ); assert.equal( jQuery( "<div>text</div>" ).closest( "[lang]" ).length, 0, "Disconnected nodes with text and non-existent attribute selector" ); assert.ok( !jQuery( document ).closest( "#foo" ).length, "Calling closest on a document fails silently" ); jq = jQuery( "<div>text</div>" ); assert.deepEqual( jq.contents().closest( "*" ).get(), jq.get(), "Text node input (trac-13332)" ); } ); QUnit[ QUnit.jQuerySelectorsPos ? "test" : "skip" ]( "closest() with positional selectors", function( assert ) { assert.expect( 3 ); assert.deepEqual( jQuery( "#qunit-fixture" ).closest( "div:first" ).get(), [], "closest(div:first)" ); assert.deepEqual( jQuery( "#qunit-fixture div" ).closest( "body:first div:last" ).get(), [], "closest(body:first div:last)" ); assert.deepEqual( jQuery( "#qunit-fixture div" ).closest( "body:first div:last", document ).get(), [], "closest(body:first div:last, document)" ); } ); QUnit.test( "closest(jQuery)", function( assert ) { assert.expect( 8 ); var $child = jQuery( "#nothiddendivchild" ), $parent = jQuery( "#nothiddendiv" ), $sibling = jQuery( "#foo" ), $body = jQuery( "body" ); assert.ok( $child.closest( $parent ).is( "#nothiddendiv" ), "closest( jQuery('#nothiddendiv') )" ); assert.ok( $child.closest( $parent[ 0 ] ).is( "#nothiddendiv" ), "closest( jQuery('#nothiddendiv') ) :: node" ); assert.ok( $child.closest( $child ).is( "#nothiddendivchild" ), "child is included" ); assert.ok( $child.closest( $child[ 0 ] ).is( "#nothiddendivchild" ), "child is included :: node" ); assert.equal( $child.closest( document.createElement( "div" ) ).length, 0, "created element is not related" ); assert.equal( $child.closest( $sibling ).length, 0, "Sibling not a parent of child" ); assert.equal( $child.closest( $sibling[ 0 ] ).length, 0, "Sibling not a parent of child :: node" ); assert.ok( $child.closest( $body.add( $parent ) ).is( "#nothiddendiv" ), "Closest ancestor retrieved." ); } ); // Support: IE 11+ // IE doesn't support complex selectors inside `:not()`. QUnit.testUnlessIE( "not(Selector)", function( assert ) { assert.expect( 7 ); assert.equal( jQuery( "#qunit-fixture > p#ap > a" ).not( "#google" ).length, 2, "not('selector')" ); assert.deepEqual( jQuery( "#qunit-fixture p" ).not( ".result" ).get(), q( "firstp", "ap", "sndp", "en", "sap", "first" ), "not('.class')" ); assert.deepEqual( jQuery( "#qunit-fixture p" ).not( "#ap, #sndp, .result" ).get(), q( "firstp", "en", "sap", "first" ), "not('selector, selector')" ); assert.deepEqual( jQuery( "#ap *" ).not( "code" ).get(), q( "google", "groups", "anchor1", "mozilla" ), "not('tag selector')" ); assert.deepEqual( jQuery( "#ap *" ).not( "code, #mozilla" ).get(), q( "google", "groups", "anchor1" ), "not('tag, ID selector')" ); assert.deepEqual( jQuery( "#ap *" ).not( "#mozilla, code" ).get(), q( "google", "groups", "anchor1" ), "not('ID, tag selector')" ); if ( QUnit.jQuerySelectors ) { assert.deepEqual( jQuery( "#form option" ).not( "option.emptyopt:contains('Nothing'),optgroup *,[value='1']" ).get(), q( "option1c", "option1d", "option2c", "option2d", "option3c", "option3d", "option3e", "option4d", "option4e", "option5a", "option5b" ), "not('complex selector')" ); } else { assert.ok( "skip", ":contains not supported in selector-native" ); } } ); QUnit.test( "not(undefined)", function( assert ) { assert.expect( 4 ); var all = jQuery( "p" ).get(); assert.deepEqual( jQuery( "p" ).not( null ).get(), all, "not(null) should have no effect" ); assert.deepEqual( jQuery( "p" ).not( undefined ).get(), all, "not(undefined) should have no effect" ); assert.deepEqual( jQuery( "p" ).not( 0 ).get(), all, "not(0) should have no effect" ); assert.deepEqual( jQuery( "p" ).not( "" ).get(), all, "not('') should have no effect" ); } ); QUnit.test( "not(Element)", function( assert ) { assert.expect( 1 ); var selects = jQuery( "#form select" ); assert.deepEqual( selects.not( selects[ 1 ] ).get(), q( "select1", "select3", "select4", "select5" ), "filter out DOM element" ); } ); QUnit.test( "not(Function)", function( assert ) { assert.expect( 1 ); assert.deepEqual( jQuery( "#qunit-fixture p" ).not( function() { return jQuery( "a", this ).length; } ).get(), q( "sndp", "first" ), "not(Function)" ); } ); QUnit.test( "not(Array)", function( assert ) { assert.expect( 2 ); assert.equal( jQuery( "#qunit-fixture > p#ap > a" ).not( document.getElementById( "google" ) ).length, 2, "not(DOMElement)" ); assert.equal( jQuery( "p" ).not( document.getElementsByTagName( "p" ) ).length, 0, "not(Array-like DOM collection)" ); } ); QUnit.test( "not(jQuery)", function( assert ) { assert.expect( 1 ); assert.deepEqual( jQuery( "#qunit-fixture p" ).not( jQuery( "#ap, #sndp, .result" ) ).get(), q( "firstp", "en", "sap", "first" ), "not(jQuery)" ); } ); // Support: IE 11+ // IE doesn't support complex selectors inside `:not()`. QUnit.testUnlessIE( "not(Selector) excludes non-element nodes (gh-2808)", function( assert ) { assert.expect( 3 ); var mixedContents = jQuery( "#nonnodes" ).contents(), childElements = q( "nonnodesElement" ); assert.deepEqual( mixedContents.not( "*" ).get(), [], "not *" ); assert.deepEqual( mixedContents.not( "[id=a],[id=b]" ).get(), childElements, "not [id=a],[id=b]" ); assert.deepEqual( mixedContents.not( "[id=a],*,[id=b]" ).get(), [], "not [id=a],*,[id=b]" ); } ); QUnit.test( "not(arraylike) passes non-element nodes (gh-3226)", function( assert ) { assert.expect( 5 ); var mixedContents = jQuery( "<span id='nonnodesElement'>hi</span> there <!-- mon ami -->" ), mixedLength = mixedContents.length, firstElement = mixedContents.first(); assert.deepEqual( mixedContents.not( mixedContents ).get(), [], "not everything" ); assert.deepEqual( mixedContents.not( firstElement ).length, mixedLength - 1, "not firstElement" ); assert.deepEqual( mixedContents.not( [ firstElement[ 0 ].nextSibling ] ).length, mixedLength - 1, "not textnode array" ); assert.deepEqual( mixedContents.not( firstElement[ 0 ].nextSibling ).length, mixedLength - 1, "not textnode" ); assert.deepEqual( mixedContents.not( document.body ).get(), mixedContents.get(), "not with unmatched element" ); } ); QUnit.test( "has(Element)", function( assert ) { assert.expect( 3 ); var obj, detached, multipleParent; obj = jQuery( "#qunit-fixture" ).has( jQuery( "#sndp" )[ 0 ] ); assert.deepEqual( obj.get(), q( "qunit-fixture" ), "Keeps elements that have the element as a descendant" ); detached = jQuery( "<a><b><i></i></b></a>" ); assert.deepEqual( detached.has( detached.find( "i" )[ 0 ] ).get(), detached.get(), "...Even when detached" ); multipleParent = jQuery( "#qunit-fixture, #header" ).has( jQuery( "#sndp" )[ 0 ] ); assert.deepEqual( multipleParent.get(), q( "qunit-fixture" ), "Does not include elements that do not have the element as a descendant" ); } ); QUnit.test( "has(Selector)", function( assert ) { assert.expect( 5 ); var obj, detached, multipleParent, multipleHas; obj = jQuery( "#qunit-fixture" ).has( "#sndp" ); assert.deepEqual( obj.get(), q( "qunit-fixture" ), "Keeps elements that have any element matching the selector as a descendant" ); detached = jQuery( "<a><b><i></i></b></a>" ); assert.deepEqual( detached.has( "i" ).get(), detached.get(), "...Even when detached" ); multipleParent = jQuery( "#qunit-fixture, #header" ).has( "#sndp" ); assert.deepEqual( multipleParent.get(), q( "qunit-fixture" ), "Does not include elements that do not have the element as a descendant" ); multipleParent = jQuery( "#select1, #select2, #select3" ).has( "#option1a, #option3a" ); assert.deepEqual( multipleParent.get(), q( "select1", "select3" ), "Multiple contexts are checks correctly" ); multipleHas = jQuery( "#qunit-fixture" ).has( "#sndp, #first" ); assert.deepEqual( multipleHas.get(), q( "qunit-fixture" ), "Only adds elements once" ); } ); QUnit.test( "has(Arrayish)", function( assert ) { assert.expect( 4 ); var simple, detached, multipleParent, multipleHas; simple = jQuery( "#qunit-fixture" ).has( jQuery( "#sndp" ) ); assert.deepEqual( simple.get(), q( "qunit-fixture" ), "Keeps elements that have any element in the jQuery list as a descendant" ); detached = jQuery( "<a><b><i></i></b></a>" ); assert.deepEqual( detached.has( detached.find( "i" ) ).get(), detached.get(), "...Even when detached" ); multipleParent = jQuery( "#qunit-fixture, #header" ).has( jQuery( "#sndp" ) ); assert.deepEqual( multipleParent.get(), q( "qunit-fixture" ), "Does not include elements that do not have an element in the jQuery list as a descendant" ); multipleHas = jQuery( "#qunit-fixture" ).has( jQuery( "#sndp, #first" ) ); assert.deepEqual( multipleHas.get(), q( "qunit-fixture" ), "Only adds elements once" ); } ); QUnit.test( "addBack()", function( assert ) { assert.expect( 5 ); assert.deepEqual( jQuery( "#en" ).siblings().addBack().get(), q( "sndp", "en", "sap" ), "Check for siblings and self" ); assert.deepEqual( jQuery( "#foo" ).children().addBack().get(), q( "foo", "sndp", "en", "sap" ), "Check for children and self" ); assert.deepEqual( jQuery( "#sndp, #en" ).parent().addBack().get(), q( "foo", "sndp", "en" ), "Check for parent and self" ); assert.deepEqual( jQuery( "#groups" ).parents( "p, div" ).addBack().get(), q( "qunit-fixture", "ap", "groups" ), "Check for parents and self" ); assert.deepEqual( jQuery( "#select1 > option" ).filter( ":first-child" ).addBack( ":last-child" ).get(), q( "option1a", "option1d" ), "Should contain the last elems plus the *filtered* prior set elements" ); } ); QUnit.test( "siblings([String])", function( assert ) { assert.expect( 6 ); assert.deepEqual( jQuery( "#en" ).siblings().get(), q( "sndp", "sap" ), "Check for siblings" ); assert.deepEqual( jQuery( "#nonnodes" ).contents().eq( 1 ).siblings().get(), q( "nonnodesElement" ), "Check for text node siblings" ); assert.deepEqual( jQuery( "#foo" ).siblings( "form, b" ).get(), q( "form", "floatTest", "lengthtest", "name-tests", "testForm", "disabled-tests" ), "Check for multiple filters" ); var set = q( "sndp", "en", "sap" ); assert.deepEqual( jQuery( "#en, #sndp" ).siblings().get(), set, "Check for unique results from siblings" ); assert.deepEqual( jQuery( "#option5a" ).siblings( "option[data-attr]" ).get(), q( "option5c" ), "Has attribute selector in siblings (trac-9261)" ); assert.equal( jQuery( "<a></a>" ).siblings().length, 0, "Detached elements have no siblings (trac-11370)" ); } ); QUnit[ QUnit.jQuerySelectors ? "test" : "skip" ]( "siblings([String])", function( assert ) { assert.expect( 2 ); assert.deepEqual( jQuery( "#sndp" ).siblings( ":has(code)" ).get(), q( "sap" ), "Check for filtered siblings (has code child element)" ); assert.deepEqual( jQuery( "#sndp" ).siblings( ":has(a)" ).get(), q( "en", "sap" ), "Check for filtered siblings (has anchor child element)" ); } ); QUnit.test( "children([String])", function( assert ) { assert.expect( 2 ); assert.deepEqual( jQuery( "#foo" ).children().get(), q( "sndp", "en", "sap" ), "Check for children" ); assert.deepEqual( jQuery( "#foo" ).children( "#en, #sap" ).get(), q( "en", "sap" ), "Check for multiple filters" ); } ); QUnit[ QUnit.jQuerySelectors ? "test" : "skip" ]( "children([String])", function( assert ) { assert.expect( 1 ); assert.deepEqual( jQuery( "#foo" ).children( ":has(code)" ).get(), q( "sndp", "sap" ), "Check for filtered children" ); } ); QUnit.test( "parent([String])", function( assert ) { assert.expect( 6 ); var $el; assert.equal( jQuery( "#groups" ).parent()[ 0 ].id, "ap", "Simple parent check" ); assert.equal( jQuery( "#groups" ).parent( "p" )[ 0 ].id, "ap", "Filtered parent check" );
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
true
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/test/data/nomodule.js
test/data/nomodule.js
/* global outerExternalCallback */ outerExternalCallback( "evaluated: nomodule script with src" );
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
false
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/test/data/csp-nonce-external.js
test/data/csp-nonce-external.js
jQuery( function() { $( "body" ).append( "<script nonce='jquery+hardcoded+nonce' src='csp-nonce.js'></script>" ); } );
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
false
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/test/data/jquery-3.7.1.js
test/data/jquery-3.7.1.js
/*! * jQuery JavaScript Library v3.7.1 * https://jquery.com/ * * Copyright OpenJS Foundation and other contributors * Released under the MIT license * https://jquery.org/license * * Date: 2023-08-28T13:37Z */ ( function( global, factory ) { "use strict"; if ( typeof module === "object" && typeof module.exports === "object" ) { // For CommonJS and CommonJS-like environments where a proper `window` // is present, execute the factory and get jQuery. // For environments that do not have a `window` with a `document` // (such as Node.js), expose a factory as module.exports. // This accentuates the need for the creation of a real `window`. // e.g. var jQuery = require("jquery")(window); // See ticket trac-14549 for more info. module.exports = global.document ? factory( global, true ) : function( w ) { if ( !w.document ) { throw new Error( "jQuery requires a window with a document" ); } return factory( w ); }; } else { factory( global ); } // Pass this if window is not defined yet } )( typeof window !== "undefined" ? window : this, function( window, noGlobal ) { // Edge <= 12 - 13+, Firefox <=18 - 45+, IE 10 - 11, Safari 5.1 - 9+, iOS 6 - 9.1 // throw exceptions when non-strict code (e.g., ASP.NET 4.5) accesses strict mode // arguments.callee.caller (trac-13335). But as of jQuery 3.0 (2016), strict mode should be common // enough that all such attempts are guarded in a try block. "use strict"; var arr = []; var getProto = Object.getPrototypeOf; var slice = arr.slice; var flat = arr.flat ? function( array ) { return arr.flat.call( array ); } : function( array ) { return arr.concat.apply( [], array ); }; var push = arr.push; var indexOf = arr.indexOf; var class2type = {}; var toString = class2type.toString; var hasOwn = class2type.hasOwnProperty; var fnToString = hasOwn.toString; var ObjectFunctionString = fnToString.call( Object ); var support = {}; var isFunction = function isFunction( obj ) { // Support: Chrome <=57, Firefox <=52 // In some browsers, typeof returns "function" for HTML <object> elements // (i.e., `typeof document.createElement( "object" ) === "function"`). // We don't want to classify *any* DOM node as a function. // Support: QtWeb <=3.8.5, WebKit <=534.34, wkhtmltopdf tool <=0.12.5 // Plus for old WebKit, typeof returns "function" for HTML collections // (e.g., `typeof document.getElementsByTagName("div") === "function"`). (gh-4756) return typeof obj === "function" && typeof obj.nodeType !== "number" && typeof obj.item !== "function"; }; var isWindow = function isWindow( obj ) { return obj != null && obj === obj.window; }; var document = window.document; var preservedScriptAttributes = { type: true, src: true, nonce: true, noModule: true }; function DOMEval( code, node, doc ) { doc = doc || document; var i, val, script = doc.createElement( "script" ); script.text = code; if ( node ) { for ( i in preservedScriptAttributes ) { // Support: Firefox 64+, Edge 18+ // Some browsers don't support the "nonce" property on scripts. // On the other hand, just using `getAttribute` is not enough as // the `nonce` attribute is reset to an empty string whenever it // becomes browsing-context connected. // See https://github.com/whatwg/html/issues/2369 // See https://html.spec.whatwg.org/#nonce-attributes // The `node.getAttribute` check was added for the sake of // `jQuery.globalEval` so that it can fake a nonce-containing node // via an object. val = node[ i ] || node.getAttribute && node.getAttribute( i ); if ( val ) { script.setAttribute( i, val ); } } } doc.head.appendChild( script ).parentNode.removeChild( script ); } function toType( obj ) { if ( obj == null ) { return obj + ""; } // Support: Android <=2.3 only (functionish RegExp) return typeof obj === "object" || typeof obj === "function" ? class2type[ toString.call( obj ) ] || "object" : typeof obj; } /* global Symbol */ // Defining this global in .eslintrc.json would create a danger of using the global // unguarded in another place, it seems safer to define global only for this module var version = "3.7.1", rhtmlSuffix = /HTML$/i, // Define a local copy of jQuery jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' // Need init if jQuery is called (just allow error to be thrown if not included) return new jQuery.fn.init( selector, context ); }; jQuery.fn = jQuery.prototype = { // The current version of jQuery being used jquery: version, constructor: jQuery, // The default length of a jQuery object is 0 length: 0, toArray: function() { return slice.call( this ); }, // Get the Nth element in the matched element set OR // Get the whole matched element set as a clean array get: function( num ) { // Return all the elements in a clean array if ( num == null ) { return slice.call( this ); } // Return just the one element from the set return num < 0 ? this[ num + this.length ] : this[ num ]; }, // Take an array of elements and push it onto the stack // (returning the new matched element set) pushStack: function( elems ) { // Build a new jQuery matched element set var ret = jQuery.merge( this.constructor(), elems ); // Add the old object onto the stack (as a reference) ret.prevObject = this; // Return the newly-formed element set return ret; }, // Execute a callback for every element in the matched set. each: function( callback ) { return jQuery.each( this, callback ); }, map: function( callback ) { return this.pushStack( jQuery.map( this, function( elem, i ) { return callback.call( elem, i, elem ); } ) ); }, slice: function() { return this.pushStack( slice.apply( this, arguments ) ); }, first: function() { return this.eq( 0 ); }, last: function() { return this.eq( -1 ); }, even: function() { return this.pushStack( jQuery.grep( this, function( _elem, i ) { return ( i + 1 ) % 2; } ) ); }, odd: function() { return this.pushStack( jQuery.grep( this, function( _elem, i ) { return i % 2; } ) ); }, eq: function( i ) { var len = this.length, j = +i + ( i < 0 ? len : 0 ); return this.pushStack( j >= 0 && j < len ? [ this[ j ] ] : [] ); }, end: function() { return this.prevObject || this.constructor(); }, // For internal use only. // Behaves like an Array's method, not like a jQuery method. push: push, sort: arr.sort, splice: arr.splice }; jQuery.extend = jQuery.fn.extend = function() { var options, name, src, copy, copyIsArray, clone, target = arguments[ 0 ] || {}, i = 1, length = arguments.length, deep = false; // Handle a deep copy situation if ( typeof target === "boolean" ) { deep = target; // Skip the boolean and the target target = arguments[ i ] || {}; i++; } // Handle case when target is a string or something (possible in deep copy) if ( typeof target !== "object" && !isFunction( target ) ) { target = {}; } // Extend jQuery itself if only one argument is passed if ( i === length ) { target = this; i--; } for ( ; i < length; i++ ) { // Only deal with non-null/undefined values if ( ( options = arguments[ i ] ) != null ) { // Extend the base object for ( name in options ) { copy = options[ name ]; // Prevent Object.prototype pollution // Prevent never-ending loop if ( name === "__proto__" || target === copy ) { continue; } // Recurse if we're merging plain objects or arrays if ( deep && copy && ( jQuery.isPlainObject( copy ) || ( copyIsArray = Array.isArray( copy ) ) ) ) { src = target[ name ]; // Ensure proper type for the source value if ( copyIsArray && !Array.isArray( src ) ) { clone = []; } else if ( !copyIsArray && !jQuery.isPlainObject( src ) ) { clone = {}; } else { clone = src; } copyIsArray = false; // Never move original objects, clone them target[ name ] = jQuery.extend( deep, clone, copy ); // Don't bring in undefined values } else if ( copy !== undefined ) { target[ name ] = copy; } } } } // Return the modified object return target; }; jQuery.extend( { // Unique for each copy of jQuery on the page expando: "jQuery" + ( version + Math.random() ).replace( /\D/g, "" ), // Assume jQuery is ready without the ready module isReady: true, error: function( msg ) { throw new Error( msg ); }, noop: function() {}, isPlainObject: function( obj ) { var proto, Ctor; // Detect obvious negatives // Use toString instead of jQuery.type to catch host objects if ( !obj || toString.call( obj ) !== "[object Object]" ) { return false; } proto = getProto( obj ); // Objects with no prototype (e.g., `Object.create( null )`) are plain if ( !proto ) { return true; } // Objects with prototype are plain iff they were constructed by a global Object function Ctor = hasOwn.call( proto, "constructor" ) && proto.constructor; return typeof Ctor === "function" && fnToString.call( Ctor ) === ObjectFunctionString; }, isEmptyObject: function( obj ) { var name; for ( name in obj ) { return false; } return true; }, // Evaluates a script in a provided context; falls back to the global one // if not specified. globalEval: function( code, options, doc ) { DOMEval( code, { nonce: options && options.nonce }, doc ); }, each: function( obj, callback ) { var length, i = 0; if ( isArrayLike( obj ) ) { length = obj.length; for ( ; i < length; i++ ) { if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) { break; } } } else { for ( i in obj ) { if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) { break; } } } return obj; }, // Retrieve the text value of an array of DOM nodes text: function( elem ) { var node, ret = "", i = 0, nodeType = elem.nodeType; if ( !nodeType ) { // If no nodeType, this is expected to be an array while ( ( node = elem[ i++ ] ) ) { // Do not traverse comment nodes ret += jQuery.text( node ); } } if ( nodeType === 1 || nodeType === 11 ) { return elem.textContent; } if ( nodeType === 9 ) { return elem.documentElement.textContent; } if ( nodeType === 3 || nodeType === 4 ) { return elem.nodeValue; } // Do not include comment or processing instruction nodes return ret; }, // results is for internal usage only makeArray: function( arr, results ) { var ret = results || []; if ( arr != null ) { if ( isArrayLike( Object( arr ) ) ) { jQuery.merge( ret, typeof arr === "string" ? [ arr ] : arr ); } else { push.call( ret, arr ); } } return ret; }, inArray: function( elem, arr, i ) { return arr == null ? -1 : indexOf.call( arr, elem, i ); }, isXMLDoc: function( elem ) { var namespace = elem && elem.namespaceURI, docElem = elem && ( elem.ownerDocument || elem ).documentElement; // Assume HTML when documentElement doesn't yet exist, such as inside // document fragments. return !rhtmlSuffix.test( namespace || docElem && docElem.nodeName || "HTML" ); }, // Support: Android <=4.0 only, PhantomJS 1 only // push.apply(_, arraylike) throws on ancient WebKit merge: function( first, second ) { var len = +second.length, j = 0, i = first.length; for ( ; j < len; j++ ) { first[ i++ ] = second[ j ]; } first.length = i; return first; }, grep: function( elems, callback, invert ) { var callbackInverse, matches = [], i = 0, length = elems.length, callbackExpect = !invert; // Go through the array, only saving the items // that pass the validator function for ( ; i < length; i++ ) { callbackInverse = !callback( elems[ i ], i ); if ( callbackInverse !== callbackExpect ) { matches.push( elems[ i ] ); } } return matches; }, // arg is for internal usage only map: function( elems, callback, arg ) { var length, value, i = 0, ret = []; // Go through the array, translating each of the items to their new values if ( isArrayLike( elems ) ) { length = elems.length; for ( ; i < length; i++ ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret.push( value ); } } // Go through every key on the object, } else { for ( i in elems ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret.push( value ); } } } // Flatten any nested arrays return flat( ret ); }, // A global GUID counter for objects guid: 1, // jQuery.support is not used in Core but other projects attach their // properties to it so it needs to exist. support: support } ); if ( typeof Symbol === "function" ) { jQuery.fn[ Symbol.iterator ] = arr[ Symbol.iterator ]; } // Populate the class2type map jQuery.each( "Boolean Number String Function Array Date RegExp Object Error Symbol".split( " " ), function( _i, name ) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); } ); function isArrayLike( obj ) { // Support: real iOS 8.2 only (not reproducible in simulator) // `in` check used to prevent JIT error (gh-2145) // hasOwn isn't used here due to false negatives // regarding Nodelist length in IE var length = !!obj && "length" in obj && obj.length, type = toType( obj ); if ( isFunction( obj ) || isWindow( obj ) ) { return false; } return type === "array" || length === 0 || typeof length === "number" && length > 0 && ( length - 1 ) in obj; } function nodeName( elem, name ) { return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); } var pop = arr.pop; var sort = arr.sort; var splice = arr.splice; var whitespace = "[\\x20\\t\\r\\n\\f]"; var rtrimCSS = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ); // Note: an element does not contain itself jQuery.contains = function( a, b ) { var bup = b && b.parentNode; return a === bup || !!( bup && bup.nodeType === 1 && ( // Support: IE 9 - 11+ // IE doesn't have `contains` on SVG. a.contains ? a.contains( bup ) : a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 ) ); }; // CSS string/identifier serialization // https://drafts.csswg.org/cssom/#common-serializing-idioms var rcssescape = /([\0-\x1f\x7f]|^-?\d)|^-$|[^\x80-\uFFFF\w-]/g; function fcssescape( ch, asCodePoint ) { if ( asCodePoint ) { // U+0000 NULL becomes U+FFFD REPLACEMENT CHARACTER if ( ch === "\0" ) { return "\uFFFD"; } // Control characters and (dependent upon position) numbers get escaped as code points return ch.slice( 0, -1 ) + "\\" + ch.charCodeAt( ch.length - 1 ).toString( 16 ) + " "; } // Other potentially-special ASCII characters get backslash-escaped return "\\" + ch; } jQuery.escapeSelector = function( sel ) { return ( sel + "" ).replace( rcssescape, fcssescape ); }; var preferredDoc = document, pushNative = push; ( function() { var i, Expr, outermostContext, sortInput, hasDuplicate, push = pushNative, // Local document vars document, documentElement, documentIsHTML, rbuggyQSA, matches, // Instance-specific data expando = jQuery.expando, dirruns = 0, done = 0, classCache = createCache(), tokenCache = createCache(), compilerCache = createCache(), nonnativeSelectorCache = createCache(), sortOrder = function( a, b ) { if ( a === b ) { hasDuplicate = true; } return 0; }, booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|" + "loop|multiple|open|readonly|required|scoped", // Regular expressions // https://www.w3.org/TR/css-syntax-3/#ident-token-diagram identifier = "(?:\\\\[\\da-fA-F]{1,6}" + whitespace + "?|\\\\[^\\r\\n\\f]|[\\w-]|[^\0-\\x7f])+", // Attribute selectors: https://www.w3.org/TR/selectors/#attribute-selectors attributes = "\\[" + whitespace + "*(" + identifier + ")(?:" + whitespace + // Operator (capture 2) "*([*^$|!~]?=)" + whitespace + // "Attribute values must be CSS identifiers [capture 5] or strings [capture 3 or capture 4]" "*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + whitespace + "*\\]", pseudos = ":(" + identifier + ")(?:\\((" + // To reduce the number of selectors needing tokenize in the preFilter, prefer arguments: // 1. quoted (capture 3; capture 4 or capture 5) "('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" + // 2. simple (capture 6) "((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" + // 3. anything else (capture 2) ".*" + ")\\)|)", // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter rwhitespace = new RegExp( whitespace + "+", "g" ), rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), rleadingCombinator = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ), rdescend = new RegExp( whitespace + "|>" ), rpseudo = new RegExp( pseudos ), ridentifier = new RegExp( "^" + identifier + "$" ), matchExpr = { ID: new RegExp( "^#(" + identifier + ")" ), CLASS: new RegExp( "^\\.(" + identifier + ")" ), TAG: new RegExp( "^(" + identifier + "|[*])" ), ATTR: new RegExp( "^" + attributes ), PSEUDO: new RegExp( "^" + pseudos ), CHILD: new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), bool: new RegExp( "^(?:" + booleans + ")$", "i" ), // For use in libraries implementing .is() // We use this for POS matching in `select` needsContext: new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) }, rinputs = /^(?:input|select|textarea|button)$/i, rheader = /^h\d$/i, // Easily-parseable/retrievable ID or TAG or CLASS selectors rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, rsibling = /[+~]/, // CSS escapes // https://www.w3.org/TR/CSS21/syndata.html#escaped-characters runescape = new RegExp( "\\\\[\\da-fA-F]{1,6}" + whitespace + "?|\\\\([^\\r\\n\\f])", "g" ), funescape = function( escape, nonHex ) { var high = "0x" + escape.slice( 1 ) - 0x10000; if ( nonHex ) { // Strip the backslash prefix from a non-hex escape sequence return nonHex; } // Replace a hexadecimal escape sequence with the encoded Unicode code point // Support: IE <=11+ // For values outside the Basic Multilingual Plane (BMP), manually construct a // surrogate pair return high < 0 ? String.fromCharCode( high + 0x10000 ) : String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); }, // Used for iframes; see `setDocument`. // Support: IE 9 - 11+, Edge 12 - 18+ // Removing the function wrapper causes a "Permission Denied" // error in IE/Edge. unloadHandler = function() { setDocument(); }, inDisabledFieldset = addCombinator( function( elem ) { return elem.disabled === true && nodeName( elem, "fieldset" ); }, { dir: "parentNode", next: "legend" } ); // Support: IE <=9 only // Accessing document.activeElement can throw unexpectedly // https://bugs.jquery.com/ticket/13393 function safeActiveElement() { try { return document.activeElement; } catch ( err ) { } } // Optimize for push.apply( _, NodeList ) try { push.apply( ( arr = slice.call( preferredDoc.childNodes ) ), preferredDoc.childNodes ); // Support: Android <=4.0 // Detect silently failing push.apply // eslint-disable-next-line no-unused-expressions arr[ preferredDoc.childNodes.length ].nodeType; } catch ( e ) { push = { apply: function( target, els ) { pushNative.apply( target, slice.call( els ) ); }, call: function( target ) { pushNative.apply( target, slice.call( arguments, 1 ) ); } }; } function find( selector, context, results, seed ) { var m, i, elem, nid, match, groups, newSelector, newContext = context && context.ownerDocument, // nodeType defaults to 9, since context defaults to document nodeType = context ? context.nodeType : 9; results = results || []; // Return early from calls with invalid selector or context if ( typeof selector !== "string" || !selector || nodeType !== 1 && nodeType !== 9 && nodeType !== 11 ) { return results; } // Try to shortcut find operations (as opposed to filters) in HTML documents if ( !seed ) { setDocument( context ); context = context || document; if ( documentIsHTML ) { // If the selector is sufficiently simple, try using a "get*By*" DOM method // (excepting DocumentFragment context, where the methods don't exist) if ( nodeType !== 11 && ( match = rquickExpr.exec( selector ) ) ) { // ID selector if ( ( m = match[ 1 ] ) ) { // Document context if ( nodeType === 9 ) { if ( ( elem = context.getElementById( m ) ) ) { // Support: IE 9 only // getElementById can match elements by name instead of ID if ( elem.id === m ) { push.call( results, elem ); return results; } } else { return results; } // Element context } else { // Support: IE 9 only // getElementById can match elements by name instead of ID if ( newContext && ( elem = newContext.getElementById( m ) ) && find.contains( context, elem ) && elem.id === m ) { push.call( results, elem ); return results; } } // Type selector } else if ( match[ 2 ] ) { push.apply( results, context.getElementsByTagName( selector ) ); return results; // Class selector } else if ( ( m = match[ 3 ] ) && context.getElementsByClassName ) { push.apply( results, context.getElementsByClassName( m ) ); return results; } } // Take advantage of querySelectorAll if ( !nonnativeSelectorCache[ selector + " " ] && ( !rbuggyQSA || !rbuggyQSA.test( selector ) ) ) { newSelector = selector; newContext = context; // qSA considers elements outside a scoping root when evaluating child or // descendant combinators, which is not what we want. // In such cases, we work around the behavior by prefixing every selector in the // list with an ID selector referencing the scope context. // The technique has to be used as well when a leading combinator is used // as such selectors are not recognized by querySelectorAll. // Thanks to Andrew Dupont for this technique. if ( nodeType === 1 && ( rdescend.test( selector ) || rleadingCombinator.test( selector ) ) ) { // Expand context for sibling selectors newContext = rsibling.test( selector ) && testContext( context.parentNode ) || context; // We can use :scope instead of the ID hack if the browser // supports it & if we're not changing the context. // Support: IE 11+, Edge 17 - 18+ // IE/Edge sometimes throw a "Permission denied" error when // strict-comparing two documents; shallow comparisons work. // eslint-disable-next-line eqeqeq if ( newContext != context || !support.scope ) { // Capture the context ID, setting it first if necessary if ( ( nid = context.getAttribute( "id" ) ) ) { nid = jQuery.escapeSelector( nid ); } else { context.setAttribute( "id", ( nid = expando ) ); } } // Prefix every selector in the list groups = tokenize( selector ); i = groups.length; while ( i-- ) { groups[ i ] = ( nid ? "#" + nid : ":scope" ) + " " + toSelector( groups[ i ] ); } newSelector = groups.join( "," ); } try { push.apply( results, newContext.querySelectorAll( newSelector ) ); return results; } catch ( qsaError ) { nonnativeSelectorCache( selector, true ); } finally { if ( nid === expando ) { context.removeAttribute( "id" ); } } } } } // All others return select( selector.replace( rtrimCSS, "$1" ), context, results, seed ); } /** * Create key-value caches of limited size * @returns {function(string, object)} Returns the Object data after storing it on itself with * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) * deleting the oldest entry */ function createCache() { var keys = []; function cache( key, value ) { // Use (key + " ") to avoid collision with native prototype properties // (see https://github.com/jquery/sizzle/issues/157) if ( keys.push( key + " " ) > Expr.cacheLength ) { // Only keep the most recent entries delete cache[ keys.shift() ]; } return ( cache[ key + " " ] = value ); } return cache; } /** * Mark a function for special use by jQuery selector module * @param {Function} fn The function to mark */ function markFunction( fn ) { fn[ expando ] = true; return fn; } /** * Support testing using an element * @param {Function} fn Passed the created element and returns a boolean result */ function assert( fn ) { var el = document.createElement( "fieldset" ); try { return !!fn( el ); } catch ( e ) { return false; } finally { // Remove from its parent by default if ( el.parentNode ) { el.parentNode.removeChild( el ); } // release memory in IE el = null; } } /** * Returns a function to use in pseudos for input types * @param {String} type */ function createInputPseudo( type ) { return function( elem ) { return nodeName( elem, "input" ) && elem.type === type; }; } /** * Returns a function to use in pseudos for buttons * @param {String} type */ function createButtonPseudo( type ) { return function( elem ) { return ( nodeName( elem, "input" ) || nodeName( elem, "button" ) ) && elem.type === type; }; } /** * Returns a function to use in pseudos for :enabled/:disabled * @param {Boolean} disabled true for :disabled; false for :enabled */ function createDisabledPseudo( disabled ) { // Known :disabled false positives: fieldset[disabled] > legend:nth-of-type(n+2) :can-disable return function( elem ) { // Only certain elements can match :enabled or :disabled // https://html.spec.whatwg.org/multipage/scripting.html#selector-enabled // https://html.spec.whatwg.org/multipage/scripting.html#selector-disabled if ( "form" in elem ) { // Check for inherited disabledness on relevant non-disabled elements: // * listed form-associated elements in a disabled fieldset // https://html.spec.whatwg.org/multipage/forms.html#category-listed // https://html.spec.whatwg.org/multipage/forms.html#concept-fe-disabled // * option elements in a disabled optgroup // https://html.spec.whatwg.org/multipage/forms.html#concept-option-disabled // All such elements have a "form" property. if ( elem.parentNode && elem.disabled === false ) { // Option elements defer to a parent optgroup if present if ( "label" in elem ) { if ( "label" in elem.parentNode ) { return elem.parentNode.disabled === disabled; } else { return elem.disabled === disabled; } } // Support: IE 6 - 11+ // Use the isDisabled shortcut property to check for disabled fieldset ancestors return elem.isDisabled === disabled || // Where there is no isDisabled, check manually elem.isDisabled !== !disabled && inDisabledFieldset( elem ) === disabled; } return elem.disabled === disabled; // Try to winnow out elements that can't be disabled before trusting the disabled property. // Some victims get caught in our net (label, legend, menu, track), but it shouldn't // even exist on them, let alone have a boolean value. } else if ( "label" in elem ) { return elem.disabled === disabled; } // Remaining elements are neither :enabled nor :disabled return false; }; } /** * Returns a function to use in pseudos for positionals * @param {Function} fn */ function createPositionalPseudo( fn ) { return markFunction( function( argument ) { argument = +argument; return markFunction( function( seed, matches ) { var j, matchIndexes = fn( [], seed.length, argument ), i = matchIndexes.length; // Match elements found at the specified indexes while ( i-- ) { if ( seed[ ( j = matchIndexes[ i ] ) ] ) { seed[ j ] = !( matches[ j ] = seed[ j ] ); } } } ); } ); } /** * Checks a node for validity as a jQuery selector context * @param {Element|Object=} context * @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value */ function testContext( context ) { return context && typeof context.getElementsByTagName !== "undefined" && context; } /** * Sets document-related variables once based on the current document * @param {Element|Object} [node] An element or document object to use to set the document * @returns {Object} Returns the current document */ function setDocument( node ) { var subWindow, doc = node ? node.ownerDocument || node : preferredDoc; // Return early if doc is invalid or already selected // Support: IE 11+, Edge 17 - 18+ // IE/Edge sometimes throw a "Permission denied" error when strict-comparing // two documents; shallow comparisons work. // eslint-disable-next-line eqeqeq if ( doc == document || doc.nodeType !== 9 || !doc.documentElement ) { return document; } // Update global variables document = doc; documentElement = document.documentElement; documentIsHTML = !jQuery.isXMLDoc( document ); // Support: iOS 7 only, IE 9 - 11+ // Older browsers didn't support unprefixed `matches`. matches = documentElement.matches || documentElement.webkitMatchesSelector || documentElement.msMatchesSelector; // Support: IE 9 - 11+, Edge 12 - 18+ // Accessing iframe documents after unload throws "permission denied" errors // (see trac-13936). // Limit the fix to IE & Edge Legacy; despite Edge 15+ implementing `matches`, // all IE 9+ and Edge Legacy versions implement `msMatchesSelector` as well. if ( documentElement.msMatchesSelector && // Support: IE 11+, Edge 17 - 18+ // IE/Edge sometimes throw a "Permission denied" error when strict-comparing // two documents; shallow comparisons work. // eslint-disable-next-line eqeqeq preferredDoc != document && ( subWindow = document.defaultView ) && subWindow.top !== subWindow ) { // Support: IE 9 - 11+, Edge 12 - 18+ subWindow.addEventListener( "unload", unloadHandler ); } // Support: IE <10 // Check if getElementById returns elements by name // The broken getElementById methods don't pick up programmatically-set names, // so use a roundabout getElementsByName test support.getById = assert( function( el ) { documentElement.appendChild( el ).id = jQuery.expando; return !document.getElementsByName || !document.getElementsByName( jQuery.expando ).length; } ); // Support: IE 9 only // Check to see if it's possible to do matchesSelector // on a disconnected node. support.disconnectedMatch = assert( function( el ) { return matches.call( el, "*" ); } ); // Support: IE 9 - 11+, Edge 12 - 18+ // IE/Edge don't support the :scope pseudo-class. support.scope = assert( function() { return document.querySelectorAll( ":scope" ); } ); // Support: Chrome 105 - 111 only, Safari 15.4 - 16.3 only // Make sure the `:has()` argument is parsed unforgivingly. // We include `*` in the test to detect buggy implementations that are // _selectively_ forgiving (specifically when the list includes at least // one valid selector). // Note that we treat complete lack of support for `:has()` as if it were // spec-compliant support, which is fine because use of `:has()` in such // environments will fail in the qSA path and fall back to jQuery traversal // anyway. support.cssHas = assert( function() { try { document.querySelector( ":has(*,:jqfake)" ); return false; } catch ( e ) { return true; } } ); // ID filter and find if ( support.getById ) { Expr.filter.ID = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { return elem.getAttribute( "id" ) === attrId; }; }; Expr.find.ID = function( id, context ) { if ( typeof context.getElementById !== "undefined" && documentIsHTML ) { var elem = context.getElementById( id ); return elem ? [ elem ] : []; } }; } else { Expr.filter.ID = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) {
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
true
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/test/data/csp-ajax-script-downloaded.js
test/data/csp-ajax-script-downloaded.js
window.downloadedScriptCalled = true;
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
false
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/test/data/inner_nomodule.js
test/data/inner_nomodule.js
/* global innerExternalCallback */ innerExternalCallback( "evaluated: inner nomodule script with src" );
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
false
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/test/data/json_obj.js
test/data/json_obj.js
{ "data": {"lang": "en", "length": 25} }
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
false
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/test/data/csp-nonce-globaleval.js
test/data/csp-nonce-globaleval.js
jQuery( function() { $.globalEval( "startIframeTest()", { nonce: "jquery+hardcoded+nonce" } ); } );
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
false
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/test/data/inner_module.js
test/data/inner_module.js
/* global innerExternalCallback */ innerExternalCallback( "evaluated: inner module with src" );
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
false
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/test/data/testrunner.js
test/data/testrunner.js
( function() { "use strict"; // Store the old count so that we only assert on tests that have actually leaked, // instead of asserting every time a test has leaked sometime in the past var oldActive = 0, splice = [].splice, ajaxSettings = jQuery.ajaxSettings; /** * QUnit configuration */ // Max time for done() to fire in an async test. QUnit.config.testTimeout = 60e3; // 1 minute // Enforce an "expect" argument or expect() call in all test bodies. QUnit.config.requireExpects = true; /** * Ensures that tests have cleaned up properly after themselves. Should be passed as the * teardown function on all modules' lifecycle object. */ window.moduleTeardown = function( assert ) { // Check for (and clean up, if possible) incomplete animations/requests/etc. if ( jQuery.timers && jQuery.timers.length !== 0 ) { assert.equal( jQuery.timers.length, 0, "No timers are still running" ); splice.call( jQuery.timers, 0, jQuery.timers.length ); jQuery.fx.stop(); } if ( jQuery.active !== undefined && jQuery.active !== oldActive ) { assert.equal( jQuery.active, oldActive, "No AJAX requests are still active" ); if ( ajaxTest.abort ) { ajaxTest.abort( "active requests" ); } oldActive = jQuery.active; } Globals.cleanup(); }; QUnit.done( function() { // Remove our own fixtures outside #qunit-fixture supportjQuery( "#qunit ~ *" ).remove(); } ); QUnit.testDone( function() { // Ensure jQuery events and data on the fixture are properly removed jQuery( "#qunit-fixture" ).empty(); // ...even if the jQuery under test has a broken .empty() supportjQuery( "#qunit-fixture" ).empty(); // Remove the iframe fixture supportjQuery( "#qunit-fixture-iframe" ).remove(); // Reset internal jQuery state if ( ajaxSettings ) { jQuery.ajaxSettings = jQuery.extend( true, {}, ajaxSettings ); } else { delete jQuery.ajaxSettings; } // Cleanup globals Globals.cleanup(); } ); // Register globals for cleanup and the cleanup code itself window.Globals = ( function() { var globals = {}; return { register: function( name ) { window[ name ] = globals[ name ] = true; }, cleanup: function() { var name; for ( name in globals ) { delete window[ name ]; } globals = {}; } }; } )(); } )();
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
false
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/test/data/badcall.js
test/data/badcall.js
undefined();
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
false
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/test/data/badjson.js
test/data/badjson.js
{bad: toTheBone}
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
false
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/test/data/iframeTest.js
test/data/iframeTest.js
window.startIframeTest = function() { var args = Array.prototype.slice.call( arguments ); // Note: jQuery may be undefined if page did not load it args.unshift( window.jQuery, window, document ); window.parent.iframeCallback.apply( null, args ); };
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
false
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/test/data/csp-nonce.js
test/data/csp-nonce.js
jQuery( function() { var script = document.createElement( "script" ); script.setAttribute( "nonce", "jquery+hardcoded+nonce" ); script.innerHTML = "startIframeTest()"; $( document.head ).append( script ); } );
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
false
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/test/data/testinit.js
test/data/testinit.js
/* eslint no-multi-str: "off" */ "use strict"; var parentUrl = window.location.protocol + "//" + window.location.host, // baseURL is intentionally set to "data/" instead of "". // This is not just for convenience (since most files are in data/) // but also to ensure that urls without prefix fail. baseURL = parentUrl + "/test/data/", supportjQuery = this.jQuery, // NOTE: keep it in sync with build/tasks/lib/slim-exclude.js excludedFromSlim = [ "ajax", "callbacks", "deferred", "effects", "queue" ]; // see RFC 2606 this.externalHost = "releases.jquery.com"; this.hasPHP = true; this.isLocal = window.location.protocol === "file:"; // Setup global variables before loading jQuery for testing .noConflict() supportjQuery.noConflict( true ); window.originaljQuery = this.jQuery = undefined; window.original$ = this.$ = "replaced"; /** * Returns an array of elements with the given IDs * @example q( "main", "foo", "bar" ) * @result [<div id="main">, <span id="foo">, <input id="bar">] */ this.q = function() { var r = [], i = 0; for ( ; i < arguments.length; i++ ) { r.push( document.getElementById( arguments[ i ] ) ); } return r; }; /** * Asserts that a select matches the given IDs * @param {String} message - Assertion name * @param {String} selector - jQuery selector * @param {String} expectedIds - Array of ids to construct what is expected * @param {(String|Node)=document} context - Selector context * @example match("Check for something", "p", ["foo", "bar"]); */ function match( message, selector, expectedIds, context, assert ) { var elems = jQuery( selector, context ).get(); assert.deepEqual( elems, q.apply( q, expectedIds ), message + " (" + selector + ")" ); } /** * Asserts that a select matches the given IDs. * The select is not bound by a context. * @param {String} message - Assertion name * @param {String} selector - jQuery selector * @param {String} expectedIds - Array of ids to construct what is expected * @example t("Check for something", "p", ["foo", "bar"]); */ QUnit.assert.t = function( message, selector, expectedIds ) { match( message, selector, expectedIds, undefined, QUnit.assert ); }; /** * Asserts that a select matches the given IDs. * The select is performed within the `#qunit-fixture` context. * @param {String} message - Assertion name * @param {String} selector - jQuery selector * @param {String} expectedIds - Array of ids to construct what is expected * @example selectInFixture("Check for something", "p", ["foo", "bar"]); */ QUnit.assert.selectInFixture = function( message, selector, expectedIds ) { match( message, selector, expectedIds, "#qunit-fixture", QUnit.assert ); }; this.createDashboardXML = function() { var string = "<?xml version='1.0' encoding='UTF-8'?> \ <dashboard> \ <locations class='foo'> \ <location for='bar' checked='different'> \ <infowindowtab normal='ab' mixedCase='yes'> \ <tab title='Location'><![CDATA[blabla]]></tab> \ <tab title='Users'><![CDATA[blublu]]></tab> \ </infowindowtab> \ </location> \ </locations> \ </dashboard>"; return jQuery.parseXML( string ); }; this.createWithFriesXML = function() { var string = "<?xml version='1.0' encoding='UTF-8'?> \ <soap:Envelope xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/' \ xmlns:xsd='http://www.w3.org/2001/XMLSchema' \ xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'> \ <soap:Body> \ <jsconf xmlns='http://www.example.com/ns1'> \ <response xmlns:ab='http://www.example.com/ns2'> \ <meta> \ <component id='seite1' class='component'> \ <properties xmlns:cd='http://www.example.com/ns3'> \ <property name='prop1'> \ <thing /> \ <value>1</value> \ </property> \ <property name='prop2'> \ <thing att='something' /> \ </property> \ <foo_bar>foo</foo_bar> \ </properties> \ </component> \ </meta> \ </response> \ </jsconf> \ </soap:Body> \ </soap:Envelope>"; return jQuery.parseXML( string ); }; this.createXMLFragment = function() { var frag, xml = document.implementation.createDocument( "", "", null ); if ( xml ) { frag = xml.createElement( "data" ); } return frag; }; window.fireNative = function( node, type ) { var event = document.createEvent( "HTMLEvents" ); event.initEvent( type, true, true ); node.dispatchEvent( event ); }; /** * Add random number to url to stop caching * * Also prefixes with baseURL automatically. * * @example url("index.html") * @result "data/index.html?10538358428943" * * @example url("mock.php?foo=bar") * @result "data/mock.php?foo=bar&10538358345554" */ function url( value ) { return baseURL + value + ( /\?/.test( value ) ? "&" : "?" ) + new Date().getTime() + "" + parseInt( Math.random() * 100000, 10 ); } // Ajax testing helper this.ajaxTest = function( title, expect, options, wrapper ) { if ( !wrapper ) { wrapper = QUnit.test; } wrapper.call( QUnit, title, function( assert ) { assert.expect( expect ); var requestOptions; if ( typeof options === "function" ) { options = options( assert ); } options = options || []; requestOptions = options.requests || options.request || options; if ( !Array.isArray( requestOptions ) ) { requestOptions = [ requestOptions ]; } var done = assert.async(); if ( options.setup ) { options.setup(); } var completed = false, remaining = requestOptions.length, complete = function() { if ( !completed && --remaining === 0 ) { completed = true; delete ajaxTest.abort; if ( options.teardown ) { options.teardown(); } // Make sure all events will be called before done() setTimeout( done ); } }, requests = jQuery.map( requestOptions, function( options ) { var request = ( options.create || jQuery.ajax )( options ), callIfDefined = function( deferType, optionType ) { var handler = options[ deferType ] || !!options[ optionType ]; return function( _, status ) { if ( !completed ) { if ( !handler ) { assert.ok( false, "unexpected " + status ); } else if ( typeof handler === "function" ) { handler.apply( this, arguments ); } } }; }; if ( options.afterSend ) { options.afterSend( request, assert ); } return request .done( callIfDefined( "done", "success" ) ) .fail( callIfDefined( "fail", "error" ) ) .always( complete ); } ); ajaxTest.abort = function( reason ) { if ( !completed ) { completed = true; delete ajaxTest.abort; assert.ok( false, "aborted " + reason ); jQuery.each( requests, function( _i, request ) { request.abort(); } ); } }; } ); }; this.testIframe = function( title, fileName, func, wrapper, iframeStyles ) { if ( !wrapper ) { wrapper = QUnit.test; } wrapper.call( QUnit, title, function( assert ) { var done = assert.async(), $iframe = supportjQuery( "<iframe></iframe>" ) .css( { position: "absolute", top: "0", left: "-600px", width: "500px" } ) .attr( { id: "qunit-fixture-iframe", src: url( fileName ) } ); // Add other iframe styles if ( iframeStyles ) { $iframe.css( iframeStyles ); } // Test iframes are expected to invoke this via startIframeTest (cf. iframeTest.js) window.iframeCallback = function() { var args = Array.prototype.slice.call( arguments ); args.unshift( assert ); setTimeout( function() { var result; this.iframeCallback = undefined; result = func.apply( this, args ); function finish() { func = function() {}; $iframe.remove(); done(); } // Wait for promises returned by `func`. if ( result && result.then ) { result.then( finish ); } else { finish(); } } ); }; // Attach iframe to the body for visibility-dependent code // It will be removed by either the above code, or the testDone callback in testrunner.js $iframe.prependTo( document.body ); } ); }; this.iframeCallback = undefined; QUnit.config.autostart = false; // Leverage QUnit URL parsing to detect "basic" testing mode QUnit.basicTests = ( QUnit.urlParams.module + "" ) === "basic"; // Support: IE 11+ // A variable to make it easier to skip specific tests in IE, mostly // testing integrations with newer Web features not supported by it. QUnit.isIE = !!window.document.documentMode; QUnit.testUnlessIE = QUnit.isIE ? QUnit.skip : QUnit.test; // Returns whether a particular module like "ajax" or "deprecated" // is included in the current jQuery build; it handles the slim build // as well. The util was created so that we don't treat presence of // particular APIs to decide whether to run a test as then if we // accidentally remove an API, the tests would still not fail. this.includesModule = function( moduleName ) { var excludedModulesPart, excludedModules; // A short-cut for the slim build, e.g. "4.0.0-pre+slim" if ( jQuery.fn.jquery.indexOf( "+slim" ) > -1 ) { // The module is included if it does NOT exist on the list // of modules excluded in the slim build return excludedFromSlim.indexOf( moduleName ) === -1; } // example version for `npm run build -- -e deprecated`: // "v4.0.0-pre+14dc9347 -deprecated,-deprecated/ajax-event-alias,-deprecated/event" excludedModulesPart = jQuery.fn.jquery // Take the flags out of the version string. // Example: "-deprecated,-deprecated/ajax-event-alias,-deprecated/event" .split( " " )[ 1 ]; if ( !excludedModulesPart ) { // No build part => the full build where everything is included. return true; } excludedModules = excludedModulesPart // Turn to an array. // Example: [ "-deprecated", "-deprecated/ajax-event-alias", "-deprecated/event" ] .split( "," ) // Remove the leading "-". // Example: [ "deprecated", "deprecated/ajax-event-alias", "deprecated/event" ] .map( function( moduleName ) { return moduleName.slice( 1 ); } ) // Filter out deep names - ones that contain a slash. // Example: [ "deprecated" ] .filter( function( moduleName ) { return moduleName.indexOf( "/" ) === -1; } ); return excludedModules.indexOf( moduleName ) === -1; }; this.loadTests = function() { // QUnit.config is populated from QUnit.urlParams but only at the beginning // of the test run. We need to read both. var esmodules = QUnit.config.esmodules || QUnit.urlParams.esmodules; var jsdom = QUnit.config.jsdom || QUnit.urlParams.jsdom; if ( jsdom ) { // JSDOM doesn't implement scrollTo QUnit.config.scrolltop = false; } // Directly load tests that need evaluation before DOMContentLoaded. if ( !jsdom && ( !esmodules || document.readyState === "loading" ) ) { document.write( "<script src='" + parentUrl + "/test/unit/ready.js'><\x2Fscript>" ); } else { QUnit.module( "ready", function() { QUnit.skip( "jQuery ready tests skipped in async mode", function() {} ); } ); } // Get testSubproject from testrunner first require( [ parentUrl + "/test/data/testrunner.js" ], function() { // Says whether jQuery positional selector extensions are supported. // A full selector engine is required to support them as they need to // be evaluated left-to-right. Remove that property when support for // positional selectors is dropped. QUnit.jQuerySelectorsPos = includesModule( "selector" ); // Says whether jQuery selector extensions are supported. Change that // to `false` if your custom jQuery versions relies more on native qSA. // This doesn't include support for positional selectors (see above). QUnit.jQuerySelectors = includesModule( "selector" ); var i = 0, tests = [ // A special module with basic tests, meant for not fully // supported environments like jsdom. We run it everywhere, // though, to make sure tests are not broken. "unit/basic.js", "unit/core.js", "unit/callbacks.js", "unit/deferred.js", "unit/deprecated.js", "unit/support.js", "unit/data.js", "unit/queue.js", "unit/attributes.js", "unit/event.js", "unit/selector.js", "unit/traversing.js", "unit/manipulation.js", "unit/wrap.js", "unit/css.js", "unit/serialize.js", "unit/ajax.js", "unit/effects.js", "unit/offset.js", "unit/dimensions.js", "unit/animation.js", "unit/tween.js" ]; // Ensure load order (to preserve test numbers) ( function loadDep() { var dep = tests[ i++ ]; if ( dep ) { if ( !QUnit.basicTests || i === 1 ) { require( [ parentUrl + "/test/" + dep ], loadDep ); // When running basic tests, replace other modules with dummies to avoid overloading // impaired clients. } else { QUnit.module( dep.replace( /^.*\/|\.js$/g, "" ) ); loadDep(); } } else { /** * Run in noConflict mode */ jQuery.noConflict(); QUnit.start(); } } )(); } ); };
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
false
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/test/data/csp-ajax-script.js
test/data/csp-ajax-script.js
/* global startIframeTest */ var timeoutId, type; function finalize() { startIframeTest( type, window.downloadedScriptCalled ); } timeoutId = setTimeout( function() { finalize(); }, 1000 ); jQuery .ajax( { url: "csp-ajax-script-downloaded.js", dataType: "script", method: "POST", beforeSend: function( _jqXhr, settings ) { type = settings.type; } } ) .then( function() { clearTimeout( timeoutId ); finalize(); } );
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
false
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/test/data/module.js
test/data/module.js
/* global outerExternalCallback */ outerExternalCallback( "evaluated: module with src" );
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
false
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/test/data/trusted-types-attributes.js
test/data/trusted-types-attributes.js
window.testMessage = "script run";
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
false
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/test/data/support/getComputedSupport.js
test/data/support/getComputedSupport.js
function getComputedSupport( support ) { var prop, result = {}; for ( prop in support ) { if ( typeof support[ prop ] === "function" ) { result[ prop ] = support[ prop ](); } else { result[ prop ] = support[ prop ]; } } return result; }
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
false
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/test/data/support/csp.js
test/data/support/csp.js
jQuery( function() { startIframeTest( getComputedSupport( jQuery.support ) ); } );
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
false
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/test/data/manipulation/set-global-scripttest.js
test/data/manipulation/set-global-scripttest.js
window.scriptTest = true; parent.finishTest();
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
false
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/test/data/core/jquery-iterability-transpiled-es6.js
test/data/core/jquery-iterability-transpiled-es6.js
/* global startIframeTest */ jQuery( function() { "use strict"; var elem = jQuery( "<div></div><span></span><a></a>" ); var result = ""; var i; for ( i of elem ) { result += i.nodeName; } startIframeTest( result ); } );
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
false
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/test/node_smoke_tests/module/lib/ensure_iterability_es6.js
test/node_smoke_tests/module/lib/ensure_iterability_es6.js
import assert from "node:assert/strict"; const { JSDOM } = await import( "jsdom" ); const { ensureJQuery } = await import( "./ensure_jquery.js" ); export const ensureIterability = async( jQueryModuleSpecifier ) => { const { window } = new JSDOM( "" ); const { jQueryFactory } = await import( jQueryModuleSpecifier ); const jQuery = jQueryFactory( window ); const elem = jQuery( "<div></div><span></span><a></a>" ); ensureJQuery( jQuery ); let result = ""; for ( const node of elem ) { result += node.nodeName; } assert.strictEqual( result, "DIVSPANA", "for-of works on jQuery objects" ); };
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
false
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/test/node_smoke_tests/module/lib/ensure_jquery.js
test/node_smoke_tests/module/lib/ensure_jquery.js
import assert from "node:assert/strict"; // Check if the object we got is the jQuery object by invoking a basic API. export const ensureJQuery = ( jQuery ) => { assert( /^jQuery/.test( jQuery.expando ), "jQuery.expando was not detected, the jQuery bootstrap process has failed" ); };
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
false
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/test/node_smoke_tests/module/lib/ensure_global_not_created.js
test/node_smoke_tests/module/lib/ensure_global_not_created.js
import assert from "node:assert/strict"; // Ensure the jQuery property on global/window/module "this"/etc. was not // created in a CommonJS environment. // `global` is always checked in addition to passed parameters. export const ensureGlobalNotCreated = ( ...args ) => { [ ...args, global ].forEach( function( object ) { assert.strictEqual( object.jQuery, undefined, "A jQuery global was created in a module environment." ); } ); };
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
false
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/test/node_smoke_tests/module/lib/jquery-module-specifier.js
test/node_smoke_tests/module/lib/jquery-module-specifier.js
import path from "node:path"; import { fileURLToPath } from "node:url"; const dirname = path.dirname( fileURLToPath( import.meta.url ) ); const ROOT_DIR = path.resolve( dirname, "..", "..", "..", ".." ); // import does not work with Windows-style paths function ensureUnixPath( path ) { return path.replace( /^[a-z]:/i, "" ).replace( /\\+/g, "/" ); } // If `jQueryModuleSpecifier` is a real relative path, make it absolute // to make sure it resolves to the same file inside utils from // a subdirectory. Otherwise, leave it as-is as we may be testing `exports` // so we need input as-is. export const getJQueryModuleSpecifier = () => { const jQueryModuleInputSpecifier = process.argv[ 2 ]; if ( !jQueryModuleInputSpecifier ) { throw new Error( "jQuery module specifier not passed" ); } return jQueryModuleInputSpecifier.startsWith( "." ) ? ensureUnixPath( path.resolve( ROOT_DIR, jQueryModuleInputSpecifier ) ) : jQueryModuleInputSpecifier; };
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
false
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/test/node_smoke_tests/module/regular/window_present_originally.js
test/node_smoke_tests/module/regular/window_present_originally.js
import { JSDOM } from "jsdom"; import { ensureJQuery } from "../lib/ensure_jquery.js"; import { ensureGlobalNotCreated } from "../lib/ensure_global_not_created.js"; import { getJQueryModuleSpecifier } from "../lib/jquery-module-specifier.js"; const jQueryModuleSpecifier = getJQueryModuleSpecifier(); const { window } = new JSDOM( "" ); // Set the window global. globalThis.window = window; const { jQuery } = await import( jQueryModuleSpecifier ); ensureJQuery( jQuery ); ensureGlobalNotCreated( window );
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
false
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/test/node_smoke_tests/module/factory/iterable_with_native_symbol.js
test/node_smoke_tests/module/factory/iterable_with_native_symbol.js
import process from "node:process"; import { ensureIterability } from "../lib/ensure_iterability_es6.js"; import { getJQueryModuleSpecifier } from "../lib/jquery-module-specifier.js"; if ( typeof Symbol === "undefined" ) { console.log( "Symbols not supported, skipping the test..." ); process.exit(); } const jQueryModuleSpecifier = getJQueryModuleSpecifier(); await ensureIterability( jQueryModuleSpecifier );
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
false
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/test/node_smoke_tests/module/factory/document_passed.js
test/node_smoke_tests/module/factory/document_passed.js
import { JSDOM } from "jsdom"; import { ensureJQuery } from "../lib/ensure_jquery.js"; import { ensureGlobalNotCreated } from "../lib/ensure_global_not_created.js"; import { getJQueryModuleSpecifier } from "../lib/jquery-module-specifier.js"; const { window } = new JSDOM( "" ); const jQueryModuleSpecifier = getJQueryModuleSpecifier(); const { jQueryFactory } = await import( jQueryModuleSpecifier ); const jQuery = jQueryFactory( window ); ensureJQuery( jQuery ); ensureGlobalNotCreated();
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
false
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/test/node_smoke_tests/module/factory/document_missing.js
test/node_smoke_tests/module/factory/document_missing.js
import assert from "node:assert/strict"; import { ensureGlobalNotCreated } from "../lib/ensure_global_not_created.js"; import { getJQueryModuleSpecifier } from "../lib/jquery-module-specifier.js"; const jQueryModuleSpecifier = getJQueryModuleSpecifier(); const { jQueryFactory } = await import( jQueryModuleSpecifier ); assert.throws( () => { jQueryFactory( {} ); }, /jQuery requires a window with a document/ ); ensureGlobalNotCreated();
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
false
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/test/node_smoke_tests/dual/regular/import-and-require.js
test/node_smoke_tests/dual/regular/import-and-require.js
import assert from "node:assert/strict"; import { JSDOM } from "jsdom"; const { window } = new JSDOM( "" ); // Set the window global. globalThis.window = window; const { $: $imported } = await import( process.argv[ 2 ] ); const { $: $required } = await import( "../lib/jquery-require.cjs" ); assert( $imported === $required, "More than one copy of jQuery exists" ); assert( /^jQuery/.test( $imported.expando ), "jQuery.expando should be detected" );
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
false
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/test/node_smoke_tests/dual/factory/import-and-require-factory.js
test/node_smoke_tests/dual/factory/import-and-require-factory.js
import assert from "node:assert/strict"; import { JSDOM } from "jsdom"; const { window } = new JSDOM( "" ); const { jQueryFactory: factoryImported } = await import( process.argv[ 2 ] ); const { jQueryFactory: factoryRequired } = await import( "../lib/jquery-require-factory.cjs" ); assert( factoryImported === factoryRequired, "More than one copy of jQueryFactory exists" ); assert( !( "expando" in factoryImported ), "jQuery.expando should not be attached to the factory" ); const $ = factoryImported( window ); assert( /^jQuery/.test( $.expando ), "jQuery.expando should be detected" );
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
false
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/build/command.js
build/command.js
import yargs from "yargs/yargs"; import { build } from "./tasks/build.js"; import slimExclude from "./tasks/lib/slim-exclude.js"; const argv = yargs( process.argv.slice( 2 ) ) .version( false ) .command( { command: "[options]", describe: "Build a jQuery bundle" } ) .option( "filename", { alias: "f", type: "string", description: "Set the filename of the built file. Defaults to jquery.js." } ) .option( "dir", { alias: "d", type: "string", description: "Set the dir to which to output the built file. Defaults to /dist." } ) .option( "version", { alias: "v", type: "string", description: "Set the version to include in the built file. " + "Defaults to the version in package.json plus the " + "short commit SHA and any excluded modules." } ) .option( "watch", { alias: "w", type: "boolean", description: "Watch the source files and rebuild when they change." } ) .option( "exclude", { alias: "e", type: "array", description: "Modules to exclude from the build. " + "Specifying this option will cause the " + "specified modules to be excluded from the build." } ) .option( "include", { alias: "i", type: "array", description: "Modules to include in the build. " + "Specifying this option will override the " + "default included modules and only include these modules." } ) .option( "esm", { type: "boolean", description: "Build an ES module (ESM) bundle. " + "By default, a UMD bundle is built." } ) .option( "factory", { type: "boolean", description: "Build the factory bundle. " + "By default, a UMD bundle is built." } ) .option( "slim", { alias: "s", type: "boolean", description: "Build a slim bundle, which excludes " + slimExclude.join( ", " ) } ) .option( "amd", { type: "string", description: "Set the name of the AMD module. Leave blank to make an anonymous module." } ) .help() .argv; build( argv );
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
false
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/build/tasks/npmcopy.js
build/tasks/npmcopy.js
import fs from "node:fs/promises"; import path from "node:path"; const projectDir = path.resolve( "." ); const files = { "bootstrap/bootstrap.css": "bootstrap/dist/css/bootstrap.css", "bootstrap/bootstrap.min.css": "bootstrap/dist/css/bootstrap.min.css", "bootstrap/bootstrap.min.css.map": "bootstrap/dist/css/bootstrap.min.css.map", "core-js-bundle/core-js-bundle.js": "core-js-bundle/minified.js", "core-js-bundle/LICENSE": "core-js-bundle/LICENSE", "npo/npo.js": "native-promise-only/lib/npo.src.js", "qunit/qunit.js": "qunit/qunit/qunit.js", "qunit/qunit.css": "qunit/qunit/qunit.css", "qunit/LICENSE.txt": "qunit/LICENSE.txt", "requirejs/require.js": "requirejs/require.js", "sinon/sinon.js": "sinon/pkg/sinon.js", "sinon/LICENSE.txt": "sinon/LICENSE" }; async function npmcopy() { await fs.mkdir( path.resolve( projectDir, "external" ), { recursive: true } ); for ( const [ dest, source ] of Object.entries( files ) ) { const from = path.resolve( projectDir, "node_modules", source ); const to = path.resolve( projectDir, "external", dest ); const toDir = path.dirname( to ); await fs.mkdir( toDir, { recursive: true } ); await fs.copyFile( from, to ); console.log( `${ source } → ${ dest }` ); } } npmcopy();
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
false
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/build/tasks/build.js
build/tasks/build.js
/** * Special build task to handle various jQuery build requirements. * Compiles JS modules into one bundle, sets the custom AMD name, * and includes/excludes specified modules */ import fs from "node:fs/promises"; import path from "node:path"; import util from "node:util"; import { exec as nodeExec } from "node:child_process"; import * as rollup from "rollup"; import excludedFromSlim from "./lib/slim-exclude.js"; import rollupFileOverrides from "./lib/rollupFileOverridesPlugin.js"; import isCleanWorkingDir from "./lib/isCleanWorkingDir.js"; import processForDist from "./dist.js"; import minify from "./minify.js"; import getTimestamp from "./lib/getTimestamp.js"; import { compareSize } from "./lib/compareSize.js"; const exec = util.promisify( nodeExec ); const pkg = JSON.parse( await fs.readFile( "./package.json", "utf8" ) ); const minimum = [ "core" ]; // Exclude specified modules if the module matching the key is removed const removeWith = { ajax: [ "manipulation/_evalUrl", "deprecated/ajax-event-alias" ], callbacks: [ "deferred" ], css: [ "effects", "dimensions", "offset" ], "css/showHide": [ "effects" ], deferred: { remove: [ "ajax", "effects", "queue", "core/ready" ], include: [ "core/ready-no-deferred" ] }, event: [ "deprecated/ajax-event-alias", "deprecated/event" ], selector: [ "css/hiddenVisibleSelectors", "effects/animatedSelector" ] }; async function read( filename ) { return fs.readFile( path.join( "./src", filename ), "utf8" ); } // Remove the src folder and file extension // and ensure unix-style path separators function moduleName( filename ) { return filename .replace( new RegExp( `.*\\${ path.sep }src\\${ path.sep }` ), "" ) .replace( /\.js$/, "" ) .split( path.sep ) .join( path.posix.sep ); } async function readdirRecursive( dir, all = [] ) { let files; try { files = await fs.readdir( path.join( "./src", dir ), { withFileTypes: true } ); } catch ( e ) { return all; } for ( const file of files ) { const filepath = path.join( dir, file.name ); if ( file.isDirectory() ) { all.push( ...( await readdirRecursive( filepath ) ) ); } else { all.push( moduleName( filepath ) ); } } return all; } async function getOutputRollupOptions( { esm = false, factory = false } = {} ) { const wrapperFileName = `wrapper${ factory ? "-factory" : "" }${ esm ? "-esm" : "" }.js`; const wrapperSource = await read( wrapperFileName ); // Catch `// @CODE` and subsequent comment lines event if they don't start // in the first column. const wrapper = wrapperSource.split( /[\x20\t]*\/\/ @CODE\n(?:[\x20\t]*\/\/[^\n]+\n)*/ ); return { // The ESM format is not actually used as we strip it during the // build, inserting our own wrappers; it's just that it doesn't // generate any extra wrappers so there's nothing for us to remove. format: "esm", intro: wrapper[ 0 ].replace( /\n*$/, "" ), outro: wrapper[ 1 ].replace( /^\n*/, "" ) }; } function unique( array ) { return [ ...new Set( array ) ]; } async function checkExclude( exclude, include ) { const included = [ ...include ]; const excluded = [ ...exclude ]; for ( const module of exclude ) { if ( minimum.indexOf( module ) !== -1 ) { throw new Error( `Module \"${ module }\" is a minimum requirement.` ); } // Exclude all files in the dir of the same name // These are the removable dependencies // It's fine if the directory is not there // `selector` is a special case as we don't just remove // the module, but we replace it with `selector-native` // which re-uses parts of the `src/selector` dir. if ( module !== "selector" ) { const files = await readdirRecursive( module ); excluded.push( ...files ); } // Check removeWith list const additional = removeWith[ module ]; if ( additional ) { const [ additionalExcluded, additionalIncluded ] = await checkExclude( additional.remove || additional, additional.include || [] ); excluded.push( ...additionalExcluded ); included.push( ...additionalIncluded ); } } return [ unique( excluded ), unique( included ) ]; } async function getLastModifiedDate() { const { stdout } = await exec( "git log -1 --format=\"%at\"" ); return new Date( parseInt( stdout, 10 ) * 1000 ); } async function writeCompiled( { code, dir, filename, version } ) { // Use the last modified date so builds are reproducible const date = process.env.RELEASE_DATE ? new Date( process.env.RELEASE_DATE ) : await getLastModifiedDate(); const compiledContents = code // Embed Version .replace( /@VERSION/g, version ) // Embed Date // yyyy-mm-ddThh:mmZ .replace( /@DATE/g, date.toISOString().replace( /:\d+\.\d+Z$/, "Z" ) ); await fs.writeFile( path.join( dir, filename ), compiledContents ); console.log( `[${ getTimestamp() }] ${ filename } v${ version } created.` ); } // Build jQuery ECMAScript modules export async function build( { amd, dir = "dist", exclude = [], filename = "jquery.js", include = [], esm = false, factory = false, slim = false, version, watch = false } = {} ) { const pureSlim = slim && !exclude.length && !include.length; const fileOverrides = new Map(); function setOverride( filePath, source ) { // We want normalized paths in overrides as they will be matched // against normalized paths in the file overrides Rollup plugin. fileOverrides.set( path.resolve( filePath ), source ); } // Add the short commit hash to the version string // when the version is not for a release. if ( !version ) { const { stdout } = await exec( "git rev-parse --short HEAD" ); const isClean = await isCleanWorkingDir(); // "+[slim.]SHA" is semantically correct // Add ".dirty" as well if the working dir is not clean version = `${ pkg.version }+${ slim ? "slim." : "" }${ stdout.trim() }${ isClean ? "" : ".dirty" }`; } else if ( slim ) { version += "+slim"; } await fs.mkdir( dir, { recursive: true } ); // Exclude slim modules when slim is true const [ excluded, included ] = await checkExclude( slim ? exclude.concat( excludedFromSlim ) : exclude, include ); // Replace exports/global with a noop noConflict if ( excluded.includes( "exports/global" ) ) { const index = excluded.indexOf( "exports/global" ); setOverride( "./src/exports/global.js", "import { jQuery } from \"../core.js\";\n\n" + "jQuery.noConflict = function() {};" ); excluded.splice( index, 1 ); } // Set a desired AMD name. if ( amd != null ) { if ( amd ) { console.log( "Naming jQuery with AMD name: " + amd ); } else { console.log( "AMD name now anonymous" ); } // Replace the AMD name in the AMD export // No name means an anonymous define const amdExportContents = await read( "exports/amd.js" ); setOverride( "./src/exports/amd.js", amdExportContents.replace( // Remove the comma for anonymous defines /(\s*)"jquery"(,\s*)/, amd ? `$1\"${ amd }\"$2` : " " ) ); } // Append excluded modules to version. // Skip adding exclusions for slim builds. // Don't worry about semver syntax for these. if ( !pureSlim && excluded.length ) { version += " -" + excluded.join( ",-" ); } // Append extra included modules to version. if ( !pureSlim && included.length ) { version += " +" + included.join( ",+" ); } const inputOptions = { input: "./src/jquery.js" }; const includedImports = included .map( ( module ) => `import "./${ module }.js";` ) .join( "\n" ); const jQueryFileContents = await read( "jquery.js" ); if ( include.length ) { // If include is specified, only add those modules. setOverride( inputOptions.input, includedImports ); } else { // Remove the jQuery export from the entry file, we'll use our own // custom wrapper. setOverride( inputOptions.input, jQueryFileContents.replace( /\n*export \{ jQuery, jQuery as \$ };\n*/, "\n" ) + includedImports ); } // Replace excluded modules with empty sources. for ( const module of excluded ) { setOverride( `./src/${ module }.js`, // The `selector` module is not removed, but replaced // with `selector-native`. module === "selector" ? await read( "selector-native.js" ) : "" ); } const outputOptions = await getOutputRollupOptions( { esm, factory } ); if ( watch ) { const watcher = rollup.watch( { ...inputOptions, output: [ outputOptions ], plugins: [ rollupFileOverrides( fileOverrides ) ], watch: { include: "./src/**", skipWrite: true } } ); watcher.on( "event", async( event ) => { switch ( event.code ) { case "ERROR": console.error( event.error ); break; case "BUNDLE_END": const { output: [ { code } ] } = await event.result.generate( outputOptions ); await writeCompiled( { code, dir, filename, version } ); // Don't minify factory files; they are not meant // for the browser anyway. if ( !factory ) { await minify( { dir, filename, esm } ); } break; } } ); return watcher; } else { const bundle = await rollup.rollup( { ...inputOptions, plugins: [ rollupFileOverrides( fileOverrides ) ] } ); const { output: [ { code } ] } = await bundle.generate( outputOptions ); await writeCompiled( { code, dir, filename, version } ); // Don't minify factory files; they are not meant // for the browser anyway. if ( !factory ) { await minify( { dir, filename, esm } ); } else { // We normally process for dist during minification to save // file reads. However, some files are not minified and then // we need to do it separately. const contents = await fs.readFile( path.join( dir, filename ), "utf8" ); processForDist( contents, filename ); } } } export async function buildDefaultFiles( { version = process.env.VERSION, watch } = {} ) { await Promise.all( [ build( { version, watch } ), build( { filename: "jquery.slim.js", slim: true, version, watch } ), build( { dir: "dist-module", filename: "jquery.module.js", esm: true, version, watch } ), build( { dir: "dist-module", filename: "jquery.slim.module.js", esm: true, slim: true, version, watch } ), build( { filename: "jquery.factory.js", factory: true, version, watch } ), build( { filename: "jquery.factory.slim.js", slim: true, factory: true, version, watch } ), build( { dir: "dist-module", filename: "jquery.factory.module.js", esm: true, factory: true, version, watch } ), build( { dir: "dist-module", filename: "jquery.factory.slim.module.js", esm: true, slim: true, factory: true, version, watch } ) ] ); if ( watch ) { console.log( "Watching files..." ); } else { return compareSize( { files: [ "dist/jquery.min.js", "dist/jquery.slim.min.js", "dist-module/jquery.module.min.js", "dist-module/jquery.slim.module.min.js" ] } ); } }
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
false
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/build/tasks/node_smoke_tests.js
build/tasks/node_smoke_tests.js
import fs from "node:fs/promises"; import util from "node:util"; import { exec as nodeExec } from "node:child_process"; const exec = util.promisify( nodeExec ); const allowedLibraryTypes = new Set( [ "regular", "factory" ] ); const allowedSourceTypes = new Set( [ "commonjs", "module", "dual" ] ); // Fire up all tests defined in test/node_smoke_tests/*.js in spawned sub-processes. // All the files under test/node_smoke_tests/*.js are supposed to exit with 0 code // on success or another one on failure. Spawning in sub-processes is // important so that the tests & the main process don't interfere with // each other, e.g. so that they don't share the `require` cache. async function runTests( { libraryType, sourceType, module } ) { if ( !allowedLibraryTypes.has( libraryType ) || !allowedSourceTypes.has( sourceType ) ) { throw new Error( `Incorrect libraryType or sourceType value; passed: ${ libraryType } ${ sourceType } "${ module }"` ); } const dir = `./test/node_smoke_tests/${ sourceType }/${ libraryType }`; const files = await fs.readdir( dir, { withFileTypes: true } ); const testFiles = files.filter( ( testFilePath ) => testFilePath.isFile() ); if ( !testFiles.length ) { throw new Error( `No test files found for ${ libraryType } ${ sourceType } "${ module }"` ); } await Promise.all( testFiles.map( ( testFile ) => exec( `node "${ dir }/${ testFile.name }" "${ module }"` ) ) ); console.log( `Node smoke tests passed for ${ libraryType } ${ sourceType } "${ module }".` ); } async function runDefaultTests() { await Promise.all( [ runTests( { libraryType: "regular", sourceType: "commonjs", module: "jquery" } ), runTests( { libraryType: "regular", sourceType: "commonjs", module: "jquery/slim" } ), runTests( { libraryType: "regular", sourceType: "commonjs", module: "./dist/jquery.js" } ), runTests( { libraryType: "regular", sourceType: "commonjs", module: "./dist/jquery.slim.js" } ), runTests( { libraryType: "regular", sourceType: "module", module: "jquery" } ), runTests( { libraryType: "regular", sourceType: "module", module: "jquery/slim" } ), runTests( { libraryType: "regular", sourceType: "module", module: "./dist-module/jquery.module.js" } ), runTests( { libraryType: "regular", sourceType: "module", module: "./dist-module/jquery.slim.module.js" } ), runTests( { libraryType: "factory", sourceType: "commonjs", module: "jquery/factory" } ), runTests( { libraryType: "factory", sourceType: "commonjs", module: "jquery/factory-slim" } ), runTests( { libraryType: "factory", sourceType: "commonjs", module: "./dist/jquery.factory.js" } ), runTests( { libraryType: "factory", sourceType: "commonjs", module: "./dist/jquery.factory.slim.js" } ), runTests( { libraryType: "factory", sourceType: "module", module: "jquery/factory" } ), runTests( { libraryType: "factory", sourceType: "module", module: "jquery/factory-slim" } ), runTests( { libraryType: "factory", sourceType: "module", module: "./dist-module/jquery.factory.module.js" } ), runTests( { libraryType: "factory", sourceType: "module", module: "./dist-module/jquery.factory.slim.module.js" } ), runTests( { libraryType: "regular", sourceType: "dual", module: "jquery" } ), runTests( { libraryType: "regular", sourceType: "dual", module: "jquery/slim" } ), runTests( { libraryType: "factory", sourceType: "dual", module: "jquery/factory" } ), runTests( { libraryType: "factory", sourceType: "dual", module: "jquery/factory-slim" } ) ] ); } runDefaultTests();
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
false
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/build/tasks/qunit-fixture.js
build/tasks/qunit-fixture.js
import fs from "node:fs/promises"; async function generateFixture() { const fixture = await fs.readFile( "./test/data/qunit-fixture.html", "utf8" ); await fs.writeFile( "./test/data/qunit-fixture.js", "// Generated by build/tasks/qunit-fixture.js\n" + "QUnit.config.fixture = " + JSON.stringify( fixture.replace( /\r\n/g, "\n" ) ) + ";\n" ); console.log( "Updated ./test/data/qunit-fixture.js" ); } generateFixture();
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
false
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/build/tasks/dist.js
build/tasks/dist.js
// Process files for distribution. export default function processForDist( text, filename ) { if ( !text ) { throw new Error( "text required for processForDist" ); } if ( !filename ) { throw new Error( "filename required for processForDist" ); } // Ensure files use only \n for line endings, not \r\n if ( /\x0d\x0a/.test( text ) ) { throw new Error( filename + ": Incorrect line endings (\\r\\n)" ); } // Ensure only ASCII chars so script tags don't need a charset attribute if ( text.length !== Buffer.byteLength( text, "utf8" ) ) { let message = filename + ": Non-ASCII characters detected:\n"; for ( let i = 0; i < text.length; i++ ) { const c = text.charCodeAt( i ); if ( c > 127 ) { message += "- position " + i + ": " + c + "\n"; message += "==> " + text.substring( i - 20, i + 20 ); break; } } throw new Error( message ); } }
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
false
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/build/tasks/promises_aplus_tests.js
build/tasks/promises_aplus_tests.js
import path from "node:path"; import os from "node:os"; import { spawn } from "node:child_process"; const command = path.resolve( `node_modules/.bin/promises-aplus-tests${ os.platform() === "win32" ? ".cmd" : "" }` ); const args = [ "--reporter", "dot", "--timeout", "2000" ]; const tests = [ "test/promises_aplus_adapters/deferred.cjs", "test/promises_aplus_adapters/when.cjs" ]; async function runTests() { tests.forEach( ( test ) => { spawn( command, [ test ].concat( args ), { shell: true, stdio: "inherit" } ); } ); } runTests();
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
false
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/build/tasks/minify.js
build/tasks/minify.js
import fs from "node:fs/promises"; import path from "node:path"; import swc from "@swc/core"; import processForDist from "./dist.js"; import getTimestamp from "./lib/getTimestamp.js"; const rjs = /\.js$/; export default async function minify( { filename, dir, esm } ) { const contents = await fs.readFile( path.join( dir, filename ), "utf8" ); const version = /jQuery JavaScript Library ([^\n]+)/.exec( contents )[ 1 ]; const { code, map: incompleteMap } = await swc.minify( contents, { compress: { ecma: esm ? 2015 : 5, hoist_funs: false, loops: false }, format: { ecma: esm ? 2015 : 5, asciiOnly: true, comments: false, preamble: `/*! jQuery ${ version }` + " | (c) OpenJS Foundation and other contributors" + " | jquery.com/license */\n" }, inlineSourcesContent: false, mangle: true, module: esm, sourceMap: true } ); const minFilename = filename.replace( rjs, ".min.js" ); const mapFilename = filename.replace( rjs, ".min.map" ); // The map's `files` & `sources` property are set incorrectly, fix // them via overrides from the task config. // See https://github.com/swc-project/swc/issues/7588#issuecomment-1624345254 const map = JSON.stringify( { ...JSON.parse( incompleteMap ), file: minFilename, sources: [ filename ] } ); await Promise.all( [ fs.writeFile( path.join( dir, minFilename ), code ), fs.writeFile( path.join( dir, mapFilename ), map ) ] ); // Always process files for dist // Doing it here avoids extra file reads processForDist( contents, filename ); processForDist( code, minFilename ); processForDist( map, mapFilename ); console.log( `[${ getTimestamp() }] ${ minFilename } ${ version } with ${ mapFilename } created.` ); }
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
false
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/build/tasks/lib/getTimestamp.js
build/tasks/lib/getTimestamp.js
export default function getTimestamp() { const now = new Date(); const hours = now.getHours().toString().padStart( 2, "0" ); const minutes = now.getMinutes().toString().padStart( 2, "0" ); const seconds = now.getSeconds().toString().padStart( 2, "0" ); return `${ hours }:${ minutes }:${ seconds }`; }
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
false
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/build/tasks/lib/rollupFileOverridesPlugin.js
build/tasks/lib/rollupFileOverridesPlugin.js
/** * A Rollup plugin accepting a file overrides map and changing * module sources to the overridden ones where provided. Files * without overrides are loaded from disk. * * @param {Map<string, string>} fileOverrides */ export default function rollupFileOverrides( fileOverrides ) { return { name: "jquery-file-overrides", load( id ) { if ( fileOverrides.has( id ) ) { // Replace the module by a fake source. return fileOverrides.get( id ); } // Handle this module via the file system. return null; } }; }
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
false
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/build/tasks/lib/slim-exclude.js
build/tasks/lib/slim-exclude.js
// NOTE: keep it in sync with test/data/testinit.js export default [ "ajax", "callbacks", "deferred", "effects", "queue" ];
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
false
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/build/tasks/lib/isCleanWorkingDir.js
build/tasks/lib/isCleanWorkingDir.js
import util from "node:util"; import { exec as nodeExec } from "node:child_process"; const exec = util.promisify( nodeExec ); export default async function isCleanWorkingDir() { const { stdout } = await exec( "git status --untracked-files=no --porcelain" ); return !stdout.trim(); }
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
false
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/build/tasks/lib/compareSize.js
build/tasks/lib/compareSize.js
import fs from "node:fs/promises"; import { promisify } from "node:util"; import zlib from "node:zlib"; import { exec as nodeExec } from "node:child_process"; import chalk from "chalk"; import isCleanWorkingDir from "./isCleanWorkingDir.js"; const VERSION = 2; const lastRunBranch = " last run"; const gzip = promisify( zlib.gzip ); const brotli = promisify( zlib.brotliCompress ); const exec = promisify( nodeExec ); async function getBranchName() { const { stdout } = await exec( "git rev-parse --abbrev-ref HEAD" ); return stdout.trim(); } async function getCommitHash() { const { stdout } = await exec( "git rev-parse HEAD" ); return stdout.trim(); } function getBranchHeader( branch, commit ) { let branchHeader = branch.trim(); if ( commit ) { branchHeader = chalk.bold( branchHeader ) + chalk.gray( ` @${ commit }` ); } else { branchHeader = chalk.italic( branchHeader ); } return branchHeader; } async function getCache( loc ) { let cache; try { const contents = await fs.readFile( loc, "utf8" ); cache = JSON.parse( contents ); } catch ( err ) { return {}; } const lastRun = cache[ lastRunBranch ]; if ( !lastRun || !lastRun.meta || lastRun.meta.version !== VERSION ) { console.log( "Compare cache version mismatch. Rewriting..." ); return {}; } return cache; } function cacheResults( results ) { const files = Object.create( null ); results.forEach( function( result ) { files[ result.filename ] = { raw: result.raw, gz: result.gz, br: result.br }; } ); return files; } function saveCache( loc, cache ) { // Keep cache readable for manual edits return fs.writeFile( loc, JSON.stringify( cache, null, " " ) + "\n" ); } function compareSizes( existing, current, padLength ) { if ( typeof current !== "number" ) { return chalk.grey( `${ existing }`.padStart( padLength ) ); } const delta = current - existing; if ( delta > 0 ) { return chalk.red( `+${ delta }`.padStart( padLength ) ); } return chalk.green( `${ delta }`.padStart( padLength ) ); } function sortBranches( a, b ) { if ( a === lastRunBranch ) { return 1; } if ( b === lastRunBranch ) { return -1; } if ( a < b ) { return -1; } if ( a > b ) { return 1; } return 0; } export async function compareSize( { cache = ".sizecache.json", files } = {} ) { if ( !files || !files.length ) { throw new Error( "No files specified" ); } const branch = await getBranchName(); const commit = await getCommitHash(); const sizeCache = await getCache( cache ); let rawPadLength = 0; let gzPadLength = 0; let brPadLength = 0; const results = await Promise.all( files.map( async function( filename ) { let contents = await fs.readFile( filename, "utf8" ); // Remove the short SHA and .dirty from comparisons. // The short SHA so commits can be compared against each other // and .dirty to compare with the existing branch during development. const sha = /jQuery v\d+.\d+.\d+(?:-[\w\.]+)?(?:\+slim\.|\+)?(\w+(?:\.dirty)?)?/.exec( contents )[ 1 ]; contents = contents.replace( new RegExp( sha, "g" ), "" ); const size = Buffer.byteLength( contents, "utf8" ); const gzippedSize = ( await gzip( contents ) ).length; const brotlifiedSize = ( await brotli( contents ) ).length; // Add one to give space for the `+` or `-` in the comparison rawPadLength = Math.max( rawPadLength, size.toString().length + 1 ); gzPadLength = Math.max( gzPadLength, gzippedSize.toString().length + 1 ); brPadLength = Math.max( brPadLength, brotlifiedSize.toString().length + 1 ); return { filename, raw: size, gz: gzippedSize, br: brotlifiedSize }; } ) ); const sizeHeader = "raw".padStart( rawPadLength ) + "gz".padStart( gzPadLength + 1 ) + "br".padStart( brPadLength + 1 ) + " Filename"; const sizes = results.map( function( result ) { const rawSize = result.raw.toString().padStart( rawPadLength ); const gzSize = result.gz.toString().padStart( gzPadLength ); const brSize = result.br.toString().padStart( brPadLength ); return `${ rawSize } ${ gzSize } ${ brSize } ${ result.filename }`; } ); const comparisons = Object.keys( sizeCache ).sort( sortBranches ).map( function( branch ) { const meta = sizeCache[ branch ].meta || {}; const commit = meta.commit; const files = sizeCache[ branch ].files; const branchSizes = Object.keys( files ).map( function( filename ) { const branchResult = files[ filename ]; const compareResult = results.find( function( result ) { return result.filename === filename; } ) || {}; const compareRaw = compareSizes( branchResult.raw, compareResult.raw, rawPadLength ); const compareGz = compareSizes( branchResult.gz, compareResult.gz, gzPadLength ); const compareBr = compareSizes( branchResult.br, compareResult.br, brPadLength ); return `${ compareRaw } ${ compareGz } ${ compareBr } ${ filename }`; } ); return [ "", // New line before each branch getBranchHeader( branch, commit ), sizeHeader, ...branchSizes ].join( "\n" ); } ); const output = [ "", // Opening new line chalk.bold( "Sizes" ), sizeHeader, ...sizes, ...comparisons, "" // Closing new line ].join( "\n" ); console.log( output ); // Always save the last run // Save version under last run sizeCache[ lastRunBranch ] = { meta: { version: VERSION }, files: cacheResults( results ) }; // Only save cache for the current branch // if the working directory is clean. if ( await isCleanWorkingDir() ) { sizeCache[ branch ] = { meta: { commit }, files: cacheResults( results ) }; console.log( `Saved cache for ${ branch }.` ); } await saveCache( cache, sizeCache ); return results; }
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
false
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/build/release/archive.js
build/release/archive.js
import { readdir, writeFile } from "node:fs/promises"; import { createReadStream, createWriteStream } from "node:fs"; import path from "node:path"; import util from "node:util"; import os from "node:os"; import { exec as nodeExec } from "node:child_process"; import archiver from "archiver"; const exec = util.promisify( nodeExec ); async function md5sum( files, folder ) { if ( os.platform() === "win32" ) { const rmd5 = /[a-f0-9]{32}/; const sum = []; for ( let i = 0; i < files.length; i++ ) { const { stdout } = await exec( "certutil -hashfile " + files[ i ] + " MD5", { cwd: folder } ); sum.push( rmd5.exec( stdout )[ 0 ] + " " + files[ i ] ); } return sum.join( "\n" ); } const { stdout } = await exec( "md5 -r " + files.join( " " ), { cwd: folder } ); return stdout; } export default function archive( { cdn, folder, version } ) { return new Promise( async( resolve, reject ) => { console.log( `Creating production archive for ${ cdn }...` ); const md5file = cdn + "-md5.txt"; const output = createWriteStream( path.join( folder, cdn + "-jquery-" + version + ".zip" ) ); output.on( "close", resolve ); output.on( "error", reject ); const archive = archiver( "zip" ); archive.pipe( output ); const files = await readdir( folder ); const sum = await md5sum( files, folder ); await writeFile( path.join( folder, md5file ), sum ); files.push( md5file ); files.forEach( ( file ) => { const stream = createReadStream( path.join( folder, file ) ); archive.append( stream, { name: path.basename( file ) } ); } ); archive.finalize(); } ); }
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
false
jquery/jquery
https://github.com/jquery/jquery/blob/546a1eb03c345e1bafb72ae1aeb898abb5b3e51b/build/release/authors.js
build/release/authors.js
import fs from "node:fs/promises"; import util from "node:util"; import { exec as nodeExec } from "node:child_process"; const exec = util.promisify( nodeExec ); const rnewline = /\r?\n/; const rdate = /^\[(\d+)\] /; const ignore = [ /dependabot\[bot\]/ ]; function compareAuthors( a, b ) { const aName = a.replace( rdate, "" ).replace( / <.*>/, "" ); const bName = b.replace( rdate, "" ).replace( / <.*>/, "" ); return aName === bName; } function uniq( arr ) { const unique = []; for ( const item of arr ) { if ( ignore.some( re => re.test( item ) ) ) { continue; } if ( item && !unique.find( ( e ) => compareAuthors( e, item ) ) ) { unique.push( item ); } } return unique; } function cleanupSizzle() { console.log( "Cleaning up..." ); return exec( "npx rimraf .sizzle" ); } function cloneSizzle() { console.log( "Cloning Sizzle..." ); return exec( "git clone https://github.com/jquery/sizzle .sizzle" ); } async function getLastAuthor() { const authorsTxt = await fs.readFile( "AUTHORS.txt", "utf8" ); return authorsTxt.trim().split( rnewline ).pop(); } async function logAuthors( preCommand ) { let command = "git log --pretty=format:\"[%at] %aN <%aE>\""; if ( preCommand ) { command = `${ preCommand } && ${ command }`; } const { stdout } = await exec( command ); return uniq( stdout.trim().split( rnewline ).reverse() ); } async function getSizzleAuthors() { await cloneSizzle(); const authors = await logAuthors( "cd .sizzle" ); await cleanupSizzle(); return authors; } function sortAuthors( a, b ) { const [ , aDate ] = rdate.exec( a ); const [ , bDate ] = rdate.exec( b ); return Number( aDate ) - Number( bDate ); } function formatAuthor( author ) { return author.replace( rdate, "" ); } export async function getAuthors() { console.log( "Getting authors..." ); const authors = await logAuthors(); const sizzleAuthors = await getSizzleAuthors(); return uniq( authors.concat( sizzleAuthors ) ).sort( sortAuthors ).map( formatAuthor ); } export async function checkAuthors() { const authors = await getAuthors(); const lastAuthor = await getLastAuthor(); if ( authors[ authors.length - 1 ] !== lastAuthor ) { console.log( "AUTHORS.txt: ", lastAuthor ); console.log( "Last 20 in git: ", authors.slice( -20 ) ); throw new Error( "Last author in AUTHORS.txt does not match last git author" ); } console.log( "AUTHORS.txt is up to date" ); } export async function updateAuthors() { const authors = await getAuthors(); const authorsTxt = "Authors ordered by first contribution.\n\n" + authors.join( "\n" ) + "\n"; await fs.writeFile( "AUTHORS.txt", authorsTxt ); console.log( "AUTHORS.txt updated" ); }
javascript
MIT
546a1eb03c345e1bafb72ae1aeb898abb5b3e51b
2026-01-04T14:56:53.033090Z
false