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
) {
67 localEnv
= localEnv
|| {};
70 var config
= sinon
.getConfig( sinon
.config
);
71 config
.injectInto
= this;
72 sinon
.sandbox
.create( config
);
74 if ( localEnv
.setup
) {
75 localEnv
.setup
.call( this );
78 teardown: function () {
79 if ( localEnv
.teardown
) {
80 localEnv
.teardown
.call( this );
83 this.sandbox
.verifyAndRestore();
89 // Extend QUnit.module to provide a fixture element.
91 var orgModule
= QUnit
.module
;
93 QUnit
.module = function ( name
, localEnv
) {
95 localEnv
= localEnv
|| {};
98 fixture
= document
.createElement( 'div' );
99 fixture
.id
= 'qunit-fixture';
100 document
.body
.appendChild( fixture
);
102 if ( localEnv
.setup
) {
103 localEnv
.setup
.call( this );
106 teardown: function () {
107 if ( localEnv
.teardown
) {
108 localEnv
.teardown
.call( this );
111 fixture
.parentNode
.removeChild( fixture
);
118 * Reset mw.config and others to a fresh copy of the live config for each test(),
119 * and restore it back to the live one afterwards.
121 * @param {Object} [localEnv]
122 * @example (see test suite at the bottom of this file)
125 QUnit
.newMwEnvironment
= ( function () {
126 var warn
, error
, liveConfig
, liveMessages
,
127 MwMap
= mw
.config
.constructor, // internal use only
130 liveConfig
= mw
.config
;
131 liveMessages
= mw
.messages
;
133 function suppressWarnings() {
134 if ( warn
=== undefined ) {
136 error
= mw
.log
.error
;
137 mw
.log
.warn
= mw
.log
.error
= $.noop
;
141 function restoreWarnings() {
142 // Guard against calls not balanced with suppressWarnings()
143 if ( warn
!== undefined ) {
145 mw
.log
.error
= error
;
146 warn
= error
= undefined;
150 function freshConfigCopy( custom
) {
152 // Tests should mock all factors that directly influence the tested code.
153 // For backwards compatibility though we set mw.config to a fresh copy of the live
154 // config. This way any modifications made to mw.config during the test will not
155 // affect other tests, nor the global scope outside the test runner.
156 // This is a shallow copy, since overriding an array or object value via "custom"
157 // should replace it. Setting a config property means you override it, not extend it.
158 // NOTE: It is important that we suppress warnings because extend() will also access
159 // deprecated properties and trigger deprecation warnings from mw.log#deprecate.
161 copy
= $.extend( {}, liveConfig
.get(), custom
);
167 function freshMessagesCopy( custom
) {
168 return $.extend( /* deep */true, {}, liveMessages
.get(), custom
);
172 * @param {jQuery.Event} event
173 * @param {jqXHR} jqXHR
174 * @param {Object} ajaxOptions
176 function trackAjax( event
, jqXHR
, ajaxOptions
) {
177 ajaxRequests
.push( { xhr
: jqXHR
, options
: ajaxOptions
} );
180 return function ( localEnv
) {
181 localEnv
= $.extend( {
193 // Greetings, mock environment!
194 mw
.config
= new MwMap();
195 mw
.config
.set( freshConfigCopy( localEnv
.config
) );
196 mw
.messages
= new MwMap();
197 mw
.messages
.set( freshMessagesCopy( localEnv
.messages
) );
198 // Update reference to mw.messages
199 mw
.jqueryMsg
.setParserDefaults( {
200 messages
: mw
.messages
203 this.suppressWarnings
= suppressWarnings
;
204 this.restoreWarnings
= restoreWarnings
;
206 // Start tracking ajax requests
207 $( document
).on( 'ajaxSend', trackAjax
);
209 localEnv
.setup
.call( this );
212 teardown: function () {
213 var timers
, pending
, $activeLen
;
215 localEnv
.teardown
.call( this );
217 // Stop tracking ajax requests
218 $( document
).off( 'ajaxSend', trackAjax
);
220 // As a convenience feature, automatically restore warnings if they're
221 // still suppressed by the end of the test.
224 // Farewell, mock environment!
225 mw
.config
= liveConfig
;
226 mw
.messages
= liveMessages
;
227 // Restore reference to mw.messages
228 mw
.jqueryMsg
.setParserDefaults( {
229 messages
: liveMessages
232 // Tests should use fake timers or wait for animations to complete
233 // Check for incomplete animations/requests/etc and throw if there are any.
234 if ( $.timers
&& $.timers
.length
!== 0 ) {
235 timers
= $.timers
.length
;
236 $.each( $.timers
, function ( i
, timer
) {
237 var node
= timer
.elem
;
238 mw
.log
.warn( 'Unfinished animation #' + i
+ ' in ' + timer
.queue
+ ' queue on ' +
239 mw
.html
.element( node
.nodeName
.toLowerCase(), $( node
).getAttrs() )
242 // Force animations to stop to give the next test a clean start
246 throw new Error( 'Unfinished animations: ' + timers
);
249 // Test should use fake XHR, wait for requests, or call abort()
250 $activeLen
= $.active
;
251 if ( $activeLen
!== undefined && $activeLen
!== 0 ) {
252 pending
= $.grep( ajaxRequests
, function ( ajax
) {
253 return ajax
.xhr
.state() === 'pending';
255 if ( pending
.length
!== $activeLen
) {
256 mw
.log
.warn( 'Pending requests does not match jQuery.active count' );
258 // Force requests to stop to give the next test a clean start
259 $.each( ajaxRequests
, function ( i
, ajax
) {
261 'AJAX request #' + i
+ ' (state: ' + ajax
.xhr
.state() + ')',
268 throw new Error( 'Pending AJAX requests: ' + pending
.length
+ ' (active: ' + $activeLen
+ ')' );
275 // $.when stops as soon as one fails, which makes sense in most
276 // practical scenarios, but not in a unit test where we really do
277 // need to wait until all of them are finished.
278 QUnit
.whenPromisesComplete = function () {
279 var altPromises
= [];
281 $.each( arguments
, function ( i
, arg
) {
282 var alt
= $.Deferred();
283 altPromises
.push( alt
);
285 // Whether this one fails or not, forwards it to
286 // the 'done' (resolve) callback of the alternative promise.
287 arg
.always( alt
.resolve
);
290 return $.when
.apply( $, altPromises
);
294 * Recursively convert a node to a plain object representing its structure.
295 * Only considers attributes and contents (elements and text nodes).
296 * Attribute values are compared strictly and not normalised.
299 * @return {Object|string} Plain JavaScript value representing the node.
301 function getDomStructure( node
) {
302 var $node
, children
, processedChildren
, i
, len
, el
;
304 if ( node
.nodeType
=== Node
.ELEMENT_NODE
) {
305 children
= $node
.contents();
306 processedChildren
= [];
307 for ( i
= 0, len
= children
.length
; i
< len
; i
++ ) {
309 if ( el
.nodeType
=== Node
.ELEMENT_NODE
|| el
.nodeType
=== Node
.TEXT_NODE
) {
310 processedChildren
.push( getDomStructure( el
) );
315 tagName
: node
.tagName
,
316 attributes
: $node
.getAttrs(),
317 contents
: processedChildren
320 // Should be text node
326 * Gets structure of node for this HTML.
328 * @param {string} html HTML markup for one or more nodes.
330 function getHtmlStructure( html
) {
331 var el
= $( '<div>' ).append( html
)[ 0 ];
332 return getDomStructure( el
);
336 * Add-on assertion helpers
338 // Define the add-ons
341 // Expect boolean true
342 assertTrue: function ( actual
, message
) {
343 QUnit
.push( actual
=== true, actual
, true, message
);
346 // Expect boolean false
347 assertFalse: function ( actual
, message
) {
348 QUnit
.push( actual
=== false, actual
, false, message
);
351 // Expect numerical value less than X
352 lt: function ( actual
, expected
, message
) {
353 QUnit
.push( actual
< expected
, actual
, 'less than ' + expected
, message
);
356 // Expect numerical value less than or equal to X
357 ltOrEq: function ( actual
, expected
, message
) {
358 QUnit
.push( actual
<= expected
, actual
, 'less than or equal to ' + expected
, message
);
361 // Expect numerical value greater than X
362 gt: function ( actual
, expected
, message
) {
363 QUnit
.push( actual
> expected
, actual
, 'greater than ' + expected
, message
);
366 // Expect numerical value greater than or equal to X
367 gtOrEq: function ( actual
, expected
, message
) {
368 QUnit
.push( actual
>= expected
, actual
, 'greater than or equal to ' + expected
, message
);
372 * Asserts that two HTML strings are structurally equivalent.
374 * @param {string} actualHtml Actual HTML markup.
375 * @param {string} expectedHtml Expected HTML markup
376 * @param {string} message Assertion message.
378 htmlEqual: function ( actualHtml
, expectedHtml
, message
) {
379 var actual
= getHtmlStructure( actualHtml
),
380 expected
= getHtmlStructure( expectedHtml
);
394 * Asserts that two HTML strings are not structurally equivalent.
396 * @param {string} actualHtml Actual HTML markup.
397 * @param {string} expectedHtml Expected HTML markup.
398 * @param {string} message Assertion message.
400 notHtmlEqual: function ( actualHtml
, expectedHtml
, message
) {
401 var actual
= getHtmlStructure( actualHtml
),
402 expected
= getHtmlStructure( expectedHtml
);
416 $.extend( QUnit
.assert
, addons
);
419 * Small test suite to confirm proper functionality of the utilities and
420 * initializations defined above in this file.
422 QUnit
.module( 'test.mediawiki.qunit.testrunner', QUnit
.newMwEnvironment( {
424 this.mwHtmlLive
= mw
.html
;
426 escape: function () {
431 teardown: function () {
432 mw
.html
= this.mwHtmlLive
;
442 QUnit
.test( 'Setup', function ( assert
) {
443 assert
.equal( mw
.html
.escape( 'foo' ), 'mocked', 'setup() callback was ran.' );
444 assert
.equal( mw
.config
.get( 'testVar' ), 'foo', 'config object applied' );
445 assert
.equal( mw
.messages
.get( 'testMsg' ), 'Foo.', 'messages object applied' );
447 mw
.config
.set( 'testVar', 'bar' );
448 mw
.messages
.set( 'testMsg', 'Bar.' );
451 QUnit
.test( 'Teardown', function ( assert
) {
452 assert
.equal( mw
.config
.get( 'testVar' ), 'foo', 'config object restored and re-applied after test()' );
453 assert
.equal( mw
.messages
.get( 'testMsg' ), 'Foo.', 'messages object restored and re-applied after test()' );
456 QUnit
.test( 'Loader status', function ( assert
) {
458 modules
= mw
.loader
.getModuleNames(),
462 for ( i
= 0, len
= modules
.length
; i
< len
; i
++ ) {
463 state
= mw
.loader
.getState( modules
[ i
] );
464 if ( state
=== 'error' ) {
465 error
.push( modules
[ i
] );
466 } else if ( state
=== 'missing' ) {
467 missing
.push( modules
[ i
] );
471 assert
.deepEqual( error
, [], 'Modules in error state' );
472 assert
.deepEqual( missing
, [], 'Modules in missing state' );
475 QUnit
.test( 'htmlEqual', function ( assert
) {
477 '<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>',
478 '<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>',
479 'Attribute order, spacing and quotation marks (equal)'
483 '<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>',
484 '<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>',
485 'Attribute order, spacing and quotation marks (not equal)'
489 '<label for="firstname" accesskey="f" class="important">First</label><input id="firstname" /><label for="lastname" accesskey="l" class="minor">Last</label><input id="lastname" />',
490 '<label for="firstname" accesskey="f" class="important">First</label><input id="firstname" /><label for="lastname" accesskey="l" class="minor">Last</label><input id="lastname" />',
491 'Multiple root nodes (equal)'
495 '<label for="firstname" accesskey="f" class="important">First</label><input id="firstname" /><label for="lastname" accesskey="l" class="minor">Last</label><input id="lastname" />',
496 '<label for="firstname" accesskey="f" class="important">First</label><input id="firstname" /><label for="lastname" accesskey="l" class="important" >Last</label><input id="lastname" />',
497 'Multiple root nodes (not equal, last label node is different)'
501 'fo"o<br/>b>ar',
503 'Extra escaping is equal'
508 'Text escaping (not equal)'
512 'foo<a href="http://example.com">example</a>bar',
513 'foo<a href="http://example.com">example</a>bar',
514 'Outer text nodes are compared (equal)'
518 'foo<a href="http://example.com">example</a>bar',
519 'foo<a href="http://example.com">example</a>quux',
520 'Outer text nodes are compared (last text node different)'
525 QUnit
.module( 'test.mediawiki.qunit.testrunner-after', QUnit
.newMwEnvironment() );
527 QUnit
.test( 'Teardown', function ( assert
) {
528 assert
.equal( mw
.html
.escape( '<' ), '<', 'teardown() callback was ran.' );
529 assert
.equal( mw
.config
.get( 'testVar' ), null, 'config object restored to live in next module()' );
530 assert
.equal( mw
.messages
.get( 'testMsg' ), null, 'messages object restored to live in next module()' );
533 }( jQuery
, mediaWiki
, QUnit
) );