2 ( function ( $, mw
, QUnit
) {
8 * Add bogus to url to prevent IE crazy caching
10 * @param {string} value a relative path (eg. 'data/foo.js'
11 * or 'data/test.php?foo=bar').
12 * @return {string} Such as 'data/foo.js?131031765087663960'
14 QUnit
.fixurl = function ( value
) {
15 return value
+ ( /\?/.test( value
) ? '&' : '?' )
16 + String( new Date().getTime() )
17 + String( parseInt( Math
.random() * 100000, 10 ) );
24 // For each test() that is asynchronous, allow this time to pass before
25 // killing the test and assuming timeout failure.
26 QUnit
.config
.testTimeout
= 60 * 1000;
28 // Reduce default animation duration from 400ms to 0ms for unit tests
29 // eslint-disable-next-line no-underscore-dangle
30 $.fx
.speeds
._default
= 0;
32 // Add a checkbox to QUnit header to toggle MediaWiki ResourceLoader debug mode.
33 QUnit
.config
.urlConfig
.push( {
35 label
: 'Enable ResourceLoaderDebug',
36 tooltip
: 'Enable debug mode in ResourceLoader',
43 * Glue code for nicer integration with QUnit setup/teardown
44 * Inspired by http://sinonjs.org/releases/sinon-qunit-1.0.0.js
46 * - Work properly with asynchronous QUnit by using module setup/teardown
47 * instead of synchronously wrapping QUnit.test.
49 sinon
.assert
.fail = function ( msg
) {
50 QUnit
.assert
.ok( false, msg
);
52 sinon
.assert
.pass = function ( msg
) {
53 QUnit
.assert
.ok( true, msg
);
58 properties
: [ 'spy', 'stub', 'mock', 'sandbox' ],
59 // Don't fake timers by default
64 var orgModule
= QUnit
.module
;
66 QUnit
.module = function ( name
, localEnv
, executeNow
) {
67 if ( QUnit
.config
.moduleStack
.length
) {
68 // When inside a nested module, don't add our Sinon
69 // setup/teardown a second time.
70 return orgModule
.apply( this, arguments
);
73 if ( arguments
.length
=== 2 && typeof localEnv
=== 'function' ) {
74 executeNow
= localEnv
;
78 localEnv
= localEnv
|| {};
81 var config
= sinon
.getConfig( sinon
.config
);
82 config
.injectInto
= this;
83 sinon
.sandbox
.create( config
);
85 if ( localEnv
.setup
) {
86 localEnv
.setup
.call( this );
89 teardown: function () {
90 if ( localEnv
.teardown
) {
91 localEnv
.teardown
.call( this );
94 this.sandbox
.verifyAndRestore();
100 // Extend QUnit.module to provide a fixture element.
102 var orgModule
= QUnit
.module
;
104 QUnit
.module = function ( name
, localEnv
, executeNow
) {
107 if ( arguments
.length
=== 2 && typeof localEnv
=== 'function' ) {
108 executeNow
= localEnv
;
109 localEnv
= undefined;
112 localEnv
= localEnv
|| {};
115 fixture
= document
.createElement( 'div' );
116 fixture
.id
= 'qunit-fixture';
117 document
.body
.appendChild( fixture
);
119 if ( localEnv
.setup
) {
120 localEnv
.setup
.call( this );
123 teardown: function () {
124 if ( localEnv
.teardown
) {
125 localEnv
.teardown
.call( this );
128 fixture
.parentNode
.removeChild( fixture
);
135 * Reset mw.config and others to a fresh copy of the live config for each test(),
136 * and restore it back to the live one afterwards.
138 * @param {Object} [localEnv]
139 * @example (see test suite at the bottom of this file)
142 QUnit
.newMwEnvironment
= ( function () {
143 var warn
, error
, liveConfig
, liveMessages
,
144 MwMap
= mw
.config
.constructor, // internal use only
147 liveConfig
= mw
.config
;
148 liveMessages
= mw
.messages
;
150 function suppressWarnings() {
151 if ( warn
=== undefined ) {
153 error
= mw
.log
.error
;
154 mw
.log
.warn
= mw
.log
.error
= $.noop
;
158 function restoreWarnings() {
159 // Guard against calls not balanced with suppressWarnings()
160 if ( warn
!== undefined ) {
162 mw
.log
.error
= error
;
163 warn
= error
= undefined;
167 function freshConfigCopy( custom
) {
169 // Tests should mock all factors that directly influence the tested code.
170 // For backwards compatibility though we set mw.config to a fresh copy of the live
171 // config. This way any modifications made to mw.config during the test will not
172 // affect other tests, nor the global scope outside the test runner.
173 // This is a shallow copy, since overriding an array or object value via "custom"
174 // should replace it. Setting a config property means you override it, not extend it.
175 // NOTE: It is important that we suppress warnings because extend() will also access
176 // deprecated properties and trigger deprecation warnings from mw.log#deprecate.
178 copy
= $.extend( {}, liveConfig
.get(), custom
);
184 function freshMessagesCopy( custom
) {
185 return $.extend( /* deep */true, {}, liveMessages
.get(), custom
);
189 * @param {jQuery.Event} event
190 * @param {jqXHR} jqXHR
191 * @param {Object} ajaxOptions
193 function trackAjax( event
, jqXHR
, ajaxOptions
) {
194 ajaxRequests
.push( { xhr
: jqXHR
, options
: ajaxOptions
} );
197 return function ( localEnv
) {
198 localEnv
= $.extend( {
209 // Greetings, mock environment!
210 mw
.config
= new MwMap();
211 mw
.config
.set( freshConfigCopy( localEnv
.config
) );
212 mw
.messages
= new MwMap();
213 mw
.messages
.set( freshMessagesCopy( localEnv
.messages
) );
214 // Update reference to mw.messages
215 mw
.jqueryMsg
.setParserDefaults( {
216 messages
: mw
.messages
219 this.suppressWarnings
= suppressWarnings
;
220 this.restoreWarnings
= restoreWarnings
;
222 // Start tracking ajax requests
223 $( document
).on( 'ajaxSend', trackAjax
);
225 localEnv
.setup
.call( this );
228 teardown: function () {
229 var timers
, pending
, $activeLen
;
231 localEnv
.teardown
.call( this );
233 // Stop tracking ajax requests
234 $( document
).off( 'ajaxSend', trackAjax
);
236 // As a convenience feature, automatically restore warnings if they're
237 // still suppressed by the end of the test.
240 // Farewell, mock environment!
241 mw
.config
= liveConfig
;
242 mw
.messages
= liveMessages
;
243 // Restore reference to mw.messages
244 mw
.jqueryMsg
.setParserDefaults( {
245 messages
: liveMessages
248 // Tests should use fake timers or wait for animations to complete
249 // Check for incomplete animations/requests/etc and throw if there are any.
250 if ( $.timers
&& $.timers
.length
!== 0 ) {
251 timers
= $.timers
.length
;
252 $.each( $.timers
, function ( i
, timer
) {
253 var node
= timer
.elem
;
254 mw
.log
.warn( 'Unfinished animation #' + i
+ ' in ' + timer
.queue
+ ' queue on ' +
255 mw
.html
.element( node
.nodeName
.toLowerCase(), $( node
).getAttrs() )
258 // Force animations to stop to give the next test a clean start
262 throw new Error( 'Unfinished animations: ' + timers
);
265 // Test should use fake XHR, wait for requests, or call abort()
266 $activeLen
= $.active
;
267 if ( $activeLen
!== undefined && $activeLen
!== 0 ) {
268 pending
= $.grep( ajaxRequests
, function ( ajax
) {
269 return ajax
.xhr
.state() === 'pending';
271 if ( pending
.length
!== $activeLen
) {
272 mw
.log
.warn( 'Pending requests does not match jQuery.active count' );
274 // Force requests to stop to give the next test a clean start
275 $.each( ajaxRequests
, function ( i
, ajax
) {
277 'AJAX request #' + i
+ ' (state: ' + ajax
.xhr
.state() + ')',
284 throw new Error( 'Pending AJAX requests: ' + pending
.length
+ ' (active: ' + $activeLen
+ ')' );
291 // $.when stops as soon as one fails, which makes sense in most
292 // practical scenarios, but not in a unit test where we really do
293 // need to wait until all of them are finished.
294 QUnit
.whenPromisesComplete = function () {
295 var altPromises
= [];
297 $.each( arguments
, function ( i
, arg
) {
298 var alt
= $.Deferred();
299 altPromises
.push( alt
);
301 // Whether this one fails or not, forwards it to
302 // the 'done' (resolve) callback of the alternative promise.
303 arg
.always( alt
.resolve
);
306 return $.when
.apply( $, altPromises
);
310 * Recursively convert a node to a plain object representing its structure.
311 * Only considers attributes and contents (elements and text nodes).
312 * Attribute values are compared strictly and not normalised.
315 * @return {Object|string} Plain JavaScript value representing the node.
317 function getDomStructure( node
) {
318 var $node
, children
, processedChildren
, i
, len
, el
;
320 if ( node
.nodeType
=== Node
.ELEMENT_NODE
) {
321 children
= $node
.contents();
322 processedChildren
= [];
323 for ( i
= 0, len
= children
.length
; i
< len
; i
++ ) {
325 if ( el
.nodeType
=== Node
.ELEMENT_NODE
|| el
.nodeType
=== Node
.TEXT_NODE
) {
326 processedChildren
.push( getDomStructure( el
) );
331 tagName
: node
.tagName
,
332 attributes
: $node
.getAttrs(),
333 contents
: processedChildren
336 // Should be text node
342 * Gets structure of node for this HTML.
344 * @param {string} html HTML markup for one or more nodes.
346 function getHtmlStructure( html
) {
347 var el
= $( '<div>' ).append( html
)[ 0 ];
348 return getDomStructure( el
);
352 * Add-on assertion helpers
354 // Define the add-ons
357 // Expect boolean true
358 assertTrue: function ( actual
, message
) {
359 QUnit
.push( actual
=== true, actual
, true, message
);
362 // Expect boolean false
363 assertFalse: function ( actual
, message
) {
364 QUnit
.push( actual
=== false, actual
, false, message
);
367 // Expect numerical value less than X
368 lt: function ( actual
, expected
, message
) {
369 QUnit
.push( actual
< expected
, actual
, 'less than ' + expected
, message
);
372 // Expect numerical value less than or equal to X
373 ltOrEq: function ( actual
, expected
, message
) {
374 QUnit
.push( actual
<= expected
, actual
, 'less than or equal to ' + expected
, message
);
377 // Expect numerical value greater than X
378 gt: function ( actual
, expected
, message
) {
379 QUnit
.push( actual
> expected
, actual
, 'greater than ' + expected
, message
);
382 // Expect numerical value greater than or equal to X
383 gtOrEq: function ( actual
, expected
, message
) {
384 QUnit
.push( actual
>= expected
, actual
, 'greater than or equal to ' + expected
, message
);
388 * Asserts that two HTML strings are structurally equivalent.
390 * @param {string} actualHtml Actual HTML markup.
391 * @param {string} expectedHtml Expected HTML markup
392 * @param {string} message Assertion message.
394 htmlEqual: function ( actualHtml
, expectedHtml
, message
) {
395 var actual
= getHtmlStructure( actualHtml
),
396 expected
= getHtmlStructure( expectedHtml
);
410 * Asserts that two HTML strings are not structurally equivalent.
412 * @param {string} actualHtml Actual HTML markup.
413 * @param {string} expectedHtml Expected HTML markup.
414 * @param {string} message Assertion message.
416 notHtmlEqual: function ( actualHtml
, expectedHtml
, message
) {
417 var actual
= getHtmlStructure( actualHtml
),
418 expected
= getHtmlStructure( expectedHtml
);
432 $.extend( QUnit
.assert
, addons
);
435 * Small test suite to confirm proper functionality of the utilities and
436 * initializations defined above in this file.
438 QUnit
.module( 'test.mediawiki.qunit.testrunner', QUnit
.newMwEnvironment( {
440 this.mwHtmlLive
= mw
.html
;
442 escape: function () {
447 teardown: function () {
448 mw
.html
= this.mwHtmlLive
;
458 QUnit
.test( 'Setup', function ( assert
) {
459 assert
.equal( mw
.html
.escape( 'foo' ), 'mocked', 'setup() callback was ran.' );
460 assert
.equal( mw
.config
.get( 'testVar' ), 'foo', 'config object applied' );
461 assert
.equal( mw
.messages
.get( 'testMsg' ), 'Foo.', 'messages object applied' );
463 mw
.config
.set( 'testVar', 'bar' );
464 mw
.messages
.set( 'testMsg', 'Bar.' );
467 QUnit
.test( 'Teardown', function ( assert
) {
468 assert
.equal( mw
.config
.get( 'testVar' ), 'foo', 'config object restored and re-applied after test()' );
469 assert
.equal( mw
.messages
.get( 'testMsg' ), 'Foo.', 'messages object restored and re-applied after test()' );
472 QUnit
.test( 'Loader status', function ( assert
) {
474 modules
= mw
.loader
.getModuleNames(),
478 for ( i
= 0, len
= modules
.length
; i
< len
; i
++ ) {
479 state
= mw
.loader
.getState( modules
[ i
] );
480 if ( state
=== 'error' ) {
481 error
.push( modules
[ i
] );
482 } else if ( state
=== 'missing' ) {
483 missing
.push( modules
[ i
] );
487 assert
.deepEqual( error
, [], 'Modules in error state' );
488 assert
.deepEqual( missing
, [], 'Modules in missing state' );
491 QUnit
.test( 'htmlEqual', function ( assert
) {
493 '<div><p class="some classes" data-length="10">Child paragraph with <a href="http://example.com">A link</a></p>Regular text<span>A span</span></div>',
494 '<div><p data-length=\'10\' class=\'some classes\'>Child paragraph with <a href=\'http://example.com\' >A link</a></p>Regular text<span>A span</span></div>',
495 'Attribute order, spacing and quotation marks (equal)'
499 '<div><p class="some classes" data-length="10">Child paragraph with <a href="http://example.com">A link</a></p>Regular text<span>A span</span></div>',
500 '<div><p data-length=\'10\' class=\'some more classes\'>Child paragraph with <a href=\'http://example.com\' >A link</a></p>Regular text<span>A span</span></div>',
501 'Attribute order, spacing and quotation marks (not equal)'
505 '<label for="firstname" accesskey="f" class="important">First</label><input id="firstname" /><label for="lastname" accesskey="l" class="minor">Last</label><input id="lastname" />',
506 '<label for="firstname" accesskey="f" class="important">First</label><input id="firstname" /><label for="lastname" accesskey="l" class="minor">Last</label><input id="lastname" />',
507 'Multiple root nodes (equal)'
511 '<label for="firstname" accesskey="f" class="important">First</label><input id="firstname" /><label for="lastname" accesskey="l" class="minor">Last</label><input id="lastname" />',
512 '<label for="firstname" accesskey="f" class="important">First</label><input id="firstname" /><label for="lastname" accesskey="l" class="important" >Last</label><input id="lastname" />',
513 'Multiple root nodes (not equal, last label node is different)'
517 'fo"o<br/>b>ar',
519 'Extra escaping is equal'
524 'Text escaping (not equal)'
528 'foo<a href="http://example.com">example</a>bar',
529 'foo<a href="http://example.com">example</a>bar',
530 'Outer text nodes are compared (equal)'
534 'foo<a href="http://example.com">example</a>bar',
535 'foo<a href="http://example.com">example</a>quux',
536 'Outer text nodes are compared (last text node different)'
541 QUnit
.module( 'test.mediawiki.qunit.testrunner-after', QUnit
.newMwEnvironment() );
543 QUnit
.test( 'Teardown', function ( assert
) {
544 assert
.equal( mw
.html
.escape( '<' ), '<', 'teardown() callback was ran.' );
545 assert
.equal( mw
.config
.get( 'testVar' ), null, 'config object restored to live in next module()' );
546 assert
.equal( mw
.messages
.get( 'testMsg' ), null, 'messages object restored to live in next module()' );
549 }( jQuery
, mediaWiki
, QUnit
) );