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 ( arguments
.length
=== 2 && typeof localEnv
=== 'function' ) {
68 executeNow
= localEnv
;
72 localEnv
= localEnv
|| {};
75 var config
= sinon
.getConfig( sinon
.config
);
76 config
.injectInto
= this;
77 sinon
.sandbox
.create( config
);
79 if ( localEnv
.setup
) {
80 localEnv
.setup
.call( this );
83 teardown: function () {
84 if ( localEnv
.teardown
) {
85 localEnv
.teardown
.call( this );
89 this.sandbox
.verifyAndRestore();
96 // Extend QUnit.module to provide a fixture element.
98 var orgModule
= QUnit
.module
;
100 QUnit
.module = function ( name
, localEnv
, executeNow
) {
103 if ( arguments
.length
=== 2 && typeof localEnv
=== 'function' ) {
104 executeNow
= localEnv
;
105 localEnv
= undefined;
108 localEnv
= localEnv
|| {};
111 fixture
= document
.createElement( 'div' );
112 fixture
.id
= 'qunit-fixture';
113 document
.body
.appendChild( fixture
);
115 if ( localEnv
.setup
) {
116 localEnv
.setup
.call( this );
119 teardown: function () {
120 if ( localEnv
.teardown
) {
121 localEnv
.teardown
.call( this );
124 fixture
.parentNode
.removeChild( fixture
);
131 * Reset mw.config and others to a fresh copy of the live config for each test(),
132 * and restore it back to the live one afterwards.
134 * @param {Object} [localEnv]
135 * @example (see test suite at the bottom of this file)
138 QUnit
.newMwEnvironment
= ( function () {
139 var warn
, error
, liveConfig
, liveMessages
,
140 MwMap
= mw
.config
.constructor, // internal use only
143 liveConfig
= mw
.config
;
144 liveMessages
= mw
.messages
;
146 function suppressWarnings() {
147 if ( warn
=== undefined ) {
149 error
= mw
.log
.error
;
150 mw
.log
.warn
= mw
.log
.error
= $.noop
;
154 function restoreWarnings() {
155 // Guard against calls not balanced with suppressWarnings()
156 if ( warn
!== undefined ) {
158 mw
.log
.error
= error
;
159 warn
= error
= undefined;
163 function freshConfigCopy( custom
) {
165 // Tests should mock all factors that directly influence the tested code.
166 // For backwards compatibility though we set mw.config to a fresh copy of the live
167 // config. This way any modifications made to mw.config during the test will not
168 // affect other tests, nor the global scope outside the test runner.
169 // This is a shallow copy, since overriding an array or object value via "custom"
170 // should replace it. Setting a config property means you override it, not extend it.
171 // NOTE: It is important that we suppress warnings because extend() will also access
172 // deprecated properties and trigger deprecation warnings from mw.log#deprecate.
174 copy
= $.extend( {}, liveConfig
.get(), custom
);
180 function freshMessagesCopy( custom
) {
181 return $.extend( /* deep */true, {}, liveMessages
.get(), custom
);
185 * @param {jQuery.Event} event
186 * @param {jqXHR} jqXHR
187 * @param {Object} ajaxOptions
189 function trackAjax( event
, jqXHR
, ajaxOptions
) {
190 ajaxRequests
.push( { xhr
: jqXHR
, options
: ajaxOptions
} );
193 return function ( localEnv
) {
194 localEnv
= $.extend( {
205 // Greetings, mock environment!
206 mw
.config
= new MwMap();
207 mw
.config
.set( freshConfigCopy( localEnv
.config
) );
208 mw
.messages
= new MwMap();
209 mw
.messages
.set( freshMessagesCopy( localEnv
.messages
) );
210 // Update reference to mw.messages
211 mw
.jqueryMsg
.setParserDefaults( {
212 messages
: mw
.messages
215 this.suppressWarnings
= suppressWarnings
;
216 this.restoreWarnings
= restoreWarnings
;
218 // Start tracking ajax requests
219 $( document
).on( 'ajaxSend', trackAjax
);
221 localEnv
.setup
.call( this );
224 teardown: function () {
225 var timers
, pending
, $activeLen
;
227 localEnv
.teardown
.call( this );
229 // Stop tracking ajax requests
230 $( document
).off( 'ajaxSend', trackAjax
);
232 // As a convenience feature, automatically restore warnings if they're
233 // still suppressed by the end of the test.
236 // Farewell, mock environment!
237 mw
.config
= liveConfig
;
238 mw
.messages
= liveMessages
;
239 // Restore reference to mw.messages
240 mw
.jqueryMsg
.setParserDefaults( {
241 messages
: liveMessages
244 // Tests should use fake timers or wait for animations to complete
245 // Check for incomplete animations/requests/etc and throw if there are any.
246 if ( $.timers
&& $.timers
.length
!== 0 ) {
247 timers
= $.timers
.length
;
248 $.each( $.timers
, function ( i
, timer
) {
249 var node
= timer
.elem
;
250 mw
.log
.warn( 'Unfinished animation #' + i
+ ' in ' + timer
.queue
+ ' queue on ' +
251 mw
.html
.element( node
.nodeName
.toLowerCase(), $( node
).getAttrs() )
254 // Force animations to stop to give the next test a clean start
258 throw new Error( 'Unfinished animations: ' + timers
);
261 // Test should use fake XHR, wait for requests, or call abort()
262 $activeLen
= $.active
;
263 if ( $activeLen
!== undefined && $activeLen
!== 0 ) {
264 pending
= $.grep( ajaxRequests
, function ( ajax
) {
265 return ajax
.xhr
.state() === 'pending';
267 if ( pending
.length
!== $activeLen
) {
268 mw
.log
.warn( 'Pending requests does not match jQuery.active count' );
270 // Force requests to stop to give the next test a clean start
271 $.each( ajaxRequests
, function ( i
, ajax
) {
273 'AJAX request #' + i
+ ' (state: ' + ajax
.xhr
.state() + ')',
280 throw new Error( 'Pending AJAX requests: ' + pending
.length
+ ' (active: ' + $activeLen
+ ')' );
287 // $.when stops as soon as one fails, which makes sense in most
288 // practical scenarios, but not in a unit test where we really do
289 // need to wait until all of them are finished.
290 QUnit
.whenPromisesComplete = function () {
291 var altPromises
= [];
293 $.each( arguments
, function ( i
, arg
) {
294 var alt
= $.Deferred();
295 altPromises
.push( alt
);
297 // Whether this one fails or not, forwards it to
298 // the 'done' (resolve) callback of the alternative promise.
299 arg
.always( alt
.resolve
);
302 return $.when
.apply( $, altPromises
);
306 * Recursively convert a node to a plain object representing its structure.
307 * Only considers attributes and contents (elements and text nodes).
308 * Attribute values are compared strictly and not normalised.
311 * @return {Object|string} Plain JavaScript value representing the node.
313 function getDomStructure( node
) {
314 var $node
, children
, processedChildren
, i
, len
, el
;
316 if ( node
.nodeType
=== Node
.ELEMENT_NODE
) {
317 children
= $node
.contents();
318 processedChildren
= [];
319 for ( i
= 0, len
= children
.length
; i
< len
; i
++ ) {
321 if ( el
.nodeType
=== Node
.ELEMENT_NODE
|| el
.nodeType
=== Node
.TEXT_NODE
) {
322 processedChildren
.push( getDomStructure( el
) );
327 tagName
: node
.tagName
,
328 attributes
: $node
.getAttrs(),
329 contents
: processedChildren
332 // Should be text node
338 * Gets structure of node for this HTML.
340 * @param {string} html HTML markup for one or more nodes.
342 function getHtmlStructure( html
) {
343 var el
= $( '<div>' ).append( html
)[ 0 ];
344 return getDomStructure( el
);
348 * Add-on assertion helpers
350 // Define the add-ons
353 // Expect boolean true
354 assertTrue: function ( actual
, message
) {
355 QUnit
.push( actual
=== true, actual
, true, message
);
358 // Expect boolean false
359 assertFalse: function ( actual
, message
) {
360 QUnit
.push( actual
=== false, actual
, false, message
);
363 // Expect numerical value less than X
364 lt: function ( actual
, expected
, message
) {
365 QUnit
.push( actual
< expected
, actual
, 'less than ' + expected
, message
);
368 // Expect numerical value less than or equal to X
369 ltOrEq: function ( actual
, expected
, message
) {
370 QUnit
.push( actual
<= expected
, actual
, 'less than or equal to ' + expected
, message
);
373 // Expect numerical value greater than X
374 gt: function ( actual
, expected
, message
) {
375 QUnit
.push( actual
> expected
, actual
, 'greater than ' + expected
, message
);
378 // Expect numerical value greater than or equal to X
379 gtOrEq: function ( actual
, expected
, message
) {
380 QUnit
.push( actual
>= expected
, actual
, 'greater than or equal to ' + expected
, message
);
384 * Asserts that two HTML strings are structurally equivalent.
386 * @param {string} actualHtml Actual HTML markup.
387 * @param {string} expectedHtml Expected HTML markup
388 * @param {string} message Assertion message.
390 htmlEqual: function ( actualHtml
, expectedHtml
, message
) {
391 var actual
= getHtmlStructure( actualHtml
),
392 expected
= getHtmlStructure( expectedHtml
);
406 * Asserts that two HTML strings are not structurally equivalent.
408 * @param {string} actualHtml Actual HTML markup.
409 * @param {string} expectedHtml Expected HTML markup.
410 * @param {string} message Assertion message.
412 notHtmlEqual: function ( actualHtml
, expectedHtml
, message
) {
413 var actual
= getHtmlStructure( actualHtml
),
414 expected
= getHtmlStructure( expectedHtml
);
428 $.extend( QUnit
.assert
, addons
);
431 * Small test suite to confirm proper functionality of the utilities and
432 * initializations defined above in this file.
434 QUnit
.module( 'test.mediawiki.qunit.testrunner', QUnit
.newMwEnvironment( {
436 this.mwHtmlLive
= mw
.html
;
438 escape: function () {
443 teardown: function () {
444 mw
.html
= this.mwHtmlLive
;
454 QUnit
.test( 'Setup', function ( assert
) {
455 assert
.equal( mw
.html
.escape( 'foo' ), 'mocked', 'setup() callback was ran.' );
456 assert
.equal( mw
.config
.get( 'testVar' ), 'foo', 'config object applied' );
457 assert
.equal( mw
.messages
.get( 'testMsg' ), 'Foo.', 'messages object applied' );
459 mw
.config
.set( 'testVar', 'bar' );
460 mw
.messages
.set( 'testMsg', 'Bar.' );
463 QUnit
.test( 'Teardown', function ( assert
) {
464 assert
.equal( mw
.config
.get( 'testVar' ), 'foo', 'config object restored and re-applied after test()' );
465 assert
.equal( mw
.messages
.get( 'testMsg' ), 'Foo.', 'messages object restored and re-applied after test()' );
468 QUnit
.test( 'Loader status', function ( assert
) {
470 modules
= mw
.loader
.getModuleNames(),
474 for ( i
= 0, len
= modules
.length
; i
< len
; i
++ ) {
475 state
= mw
.loader
.getState( modules
[ i
] );
476 if ( state
=== 'error' ) {
477 error
.push( modules
[ i
] );
478 } else if ( state
=== 'missing' ) {
479 missing
.push( modules
[ i
] );
483 assert
.deepEqual( error
, [], 'Modules in error state' );
484 assert
.deepEqual( missing
, [], 'Modules in missing state' );
487 QUnit
.test( 'htmlEqual', function ( assert
) {
489 '<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>',
490 '<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>',
491 'Attribute order, spacing and quotation marks (equal)'
495 '<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>',
496 '<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>',
497 'Attribute order, spacing and quotation marks (not equal)'
501 '<label for="firstname" accesskey="f" class="important">First</label><input id="firstname" /><label for="lastname" accesskey="l" class="minor">Last</label><input id="lastname" />',
502 '<label for="firstname" accesskey="f" class="important">First</label><input id="firstname" /><label for="lastname" accesskey="l" class="minor">Last</label><input id="lastname" />',
503 'Multiple root nodes (equal)'
507 '<label for="firstname" accesskey="f" class="important">First</label><input id="firstname" /><label for="lastname" accesskey="l" class="minor">Last</label><input id="lastname" />',
508 '<label for="firstname" accesskey="f" class="important">First</label><input id="firstname" /><label for="lastname" accesskey="l" class="important" >Last</label><input id="lastname" />',
509 'Multiple root nodes (not equal, last label node is different)'
513 'fo"o<br/>b>ar',
515 'Extra escaping is equal'
520 'Text escaping (not equal)'
524 'foo<a href="http://example.com">example</a>bar',
525 'foo<a href="http://example.com">example</a>bar',
526 'Outer text nodes are compared (equal)'
530 'foo<a href="http://example.com">example</a>bar',
531 'foo<a href="http://example.com">example</a>quux',
532 'Outer text nodes are compared (last text node different)'
537 QUnit
.module( 'test.mediawiki.qunit.testrunner-after', QUnit
.newMwEnvironment() );
539 QUnit
.test( 'Teardown', function ( assert
) {
540 assert
.equal( mw
.html
.escape( '<' ), '<', 'teardown() callback was ran.' );
541 assert
.equal( mw
.config
.get( 'testVar' ), null, 'config object restored to live in next module()' );
542 assert
.equal( mw
.messages
.get( 'testMsg' ), null, 'messages object restored to live in next module()' );
545 }( jQuery
, mediaWiki
, QUnit
) );