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( {
206 // Greetings, mock environment!
207 mw
.config
= new MwMap();
208 mw
.config
.set( freshConfigCopy( localEnv
.config
) );
209 mw
.messages
= new MwMap();
210 mw
.messages
.set( freshMessagesCopy( localEnv
.messages
) );
211 // Update reference to mw.messages
212 mw
.jqueryMsg
.setParserDefaults( {
213 messages
: mw
.messages
216 this.suppressWarnings
= suppressWarnings
;
217 this.restoreWarnings
= restoreWarnings
;
219 // Start tracking ajax requests
220 $( document
).on( 'ajaxSend', trackAjax
);
222 localEnv
.setup
.call( this );
225 teardown: function () {
226 var timers
, pending
, $activeLen
;
228 localEnv
.teardown
.call( this );
230 // Stop tracking ajax requests
231 $( document
).off( 'ajaxSend', trackAjax
);
233 // As a convenience feature, automatically restore warnings if they're
234 // still suppressed by the end of the test.
237 // Farewell, mock environment!
238 mw
.config
= liveConfig
;
239 mw
.messages
= liveMessages
;
240 // Restore reference to mw.messages
241 mw
.jqueryMsg
.setParserDefaults( {
242 messages
: liveMessages
245 // Tests should use fake timers or wait for animations to complete
246 // Check for incomplete animations/requests/etc and throw if there are any.
247 if ( $.timers
&& $.timers
.length
!== 0 ) {
248 timers
= $.timers
.length
;
249 $.each( $.timers
, function ( i
, timer
) {
250 var node
= timer
.elem
;
251 mw
.log
.warn( 'Unfinished animation #' + i
+ ' in ' + timer
.queue
+ ' queue on ' +
252 mw
.html
.element( node
.nodeName
.toLowerCase(), $( node
).getAttrs() )
255 // Force animations to stop to give the next test a clean start
259 throw new Error( 'Unfinished animations: ' + timers
);
262 // Test should use fake XHR, wait for requests, or call abort()
263 $activeLen
= $.active
;
264 if ( $activeLen
!== undefined && $activeLen
!== 0 ) {
265 pending
= $.grep( ajaxRequests
, function ( ajax
) {
266 return ajax
.xhr
.state() === 'pending';
268 if ( pending
.length
!== $activeLen
) {
269 mw
.log
.warn( 'Pending requests does not match jQuery.active count' );
271 // Force requests to stop to give the next test a clean start
272 $.each( ajaxRequests
, function ( i
, ajax
) {
274 'AJAX request #' + i
+ ' (state: ' + ajax
.xhr
.state() + ')',
281 throw new Error( 'Pending AJAX requests: ' + pending
.length
+ ' (active: ' + $activeLen
+ ')' );
288 // $.when stops as soon as one fails, which makes sense in most
289 // practical scenarios, but not in a unit test where we really do
290 // need to wait until all of them are finished.
291 QUnit
.whenPromisesComplete = function () {
292 var altPromises
= [];
294 $.each( arguments
, function ( i
, arg
) {
295 var alt
= $.Deferred();
296 altPromises
.push( alt
);
298 // Whether this one fails or not, forwards it to
299 // the 'done' (resolve) callback of the alternative promise.
300 arg
.always( alt
.resolve
);
303 return $.when
.apply( $, altPromises
);
307 * Recursively convert a node to a plain object representing its structure.
308 * Only considers attributes and contents (elements and text nodes).
309 * Attribute values are compared strictly and not normalised.
312 * @return {Object|string} Plain JavaScript value representing the node.
314 function getDomStructure( node
) {
315 var $node
, children
, processedChildren
, i
, len
, el
;
317 if ( node
.nodeType
=== Node
.ELEMENT_NODE
) {
318 children
= $node
.contents();
319 processedChildren
= [];
320 for ( i
= 0, len
= children
.length
; i
< len
; i
++ ) {
322 if ( el
.nodeType
=== Node
.ELEMENT_NODE
|| el
.nodeType
=== Node
.TEXT_NODE
) {
323 processedChildren
.push( getDomStructure( el
) );
328 tagName
: node
.tagName
,
329 attributes
: $node
.getAttrs(),
330 contents
: processedChildren
333 // Should be text node
339 * Gets structure of node for this HTML.
341 * @param {string} html HTML markup for one or more nodes.
343 function getHtmlStructure( html
) {
344 var el
= $( '<div>' ).append( html
)[ 0 ];
345 return getDomStructure( el
);
349 * Add-on assertion helpers
351 // Define the add-ons
354 // Expect boolean true
355 assertTrue: function ( actual
, message
) {
356 QUnit
.push( actual
=== true, actual
, true, message
);
359 // Expect boolean false
360 assertFalse: function ( actual
, message
) {
361 QUnit
.push( actual
=== false, actual
, false, message
);
364 // Expect numerical value less than X
365 lt: function ( actual
, expected
, message
) {
366 QUnit
.push( actual
< expected
, actual
, 'less than ' + expected
, message
);
369 // Expect numerical value less than or equal to X
370 ltOrEq: function ( actual
, expected
, message
) {
371 QUnit
.push( actual
<= expected
, actual
, 'less than or equal to ' + expected
, message
);
374 // Expect numerical value greater than X
375 gt: function ( actual
, expected
, message
) {
376 QUnit
.push( actual
> expected
, actual
, 'greater than ' + expected
, message
);
379 // Expect numerical value greater than or equal to X
380 gtOrEq: function ( actual
, expected
, message
) {
381 QUnit
.push( actual
>= expected
, actual
, 'greater than or equal to ' + expected
, message
);
385 * Asserts that two HTML strings are structurally equivalent.
387 * @param {string} actualHtml Actual HTML markup.
388 * @param {string} expectedHtml Expected HTML markup
389 * @param {string} message Assertion message.
391 htmlEqual: function ( actualHtml
, expectedHtml
, message
) {
392 var actual
= getHtmlStructure( actualHtml
),
393 expected
= getHtmlStructure( expectedHtml
);
407 * Asserts that two HTML strings are not structurally equivalent.
409 * @param {string} actualHtml Actual HTML markup.
410 * @param {string} expectedHtml Expected HTML markup.
411 * @param {string} message Assertion message.
413 notHtmlEqual: function ( actualHtml
, expectedHtml
, message
) {
414 var actual
= getHtmlStructure( actualHtml
),
415 expected
= getHtmlStructure( expectedHtml
);
429 $.extend( QUnit
.assert
, addons
);
432 * Small test suite to confirm proper functionality of the utilities and
433 * initializations defined above in this file.
435 QUnit
.module( 'test.mediawiki.qunit.testrunner', QUnit
.newMwEnvironment( {
437 this.mwHtmlLive
= mw
.html
;
439 escape: function () {
444 teardown: function () {
445 mw
.html
= this.mwHtmlLive
;
455 QUnit
.test( 'Setup', function ( assert
) {
456 assert
.equal( mw
.html
.escape( 'foo' ), 'mocked', 'setup() callback was ran.' );
457 assert
.equal( mw
.config
.get( 'testVar' ), 'foo', 'config object applied' );
458 assert
.equal( mw
.messages
.get( 'testMsg' ), 'Foo.', 'messages object applied' );
460 mw
.config
.set( 'testVar', 'bar' );
461 mw
.messages
.set( 'testMsg', 'Bar.' );
464 QUnit
.test( 'Teardown', function ( assert
) {
465 assert
.equal( mw
.config
.get( 'testVar' ), 'foo', 'config object restored and re-applied after test()' );
466 assert
.equal( mw
.messages
.get( 'testMsg' ), 'Foo.', 'messages object restored and re-applied after test()' );
469 QUnit
.test( 'Loader status', function ( assert
) {
471 modules
= mw
.loader
.getModuleNames(),
475 for ( i
= 0, len
= modules
.length
; i
< len
; i
++ ) {
476 state
= mw
.loader
.getState( modules
[ i
] );
477 if ( state
=== 'error' ) {
478 error
.push( modules
[ i
] );
479 } else if ( state
=== 'missing' ) {
480 missing
.push( modules
[ i
] );
484 assert
.deepEqual( error
, [], 'Modules in error state' );
485 assert
.deepEqual( missing
, [], 'Modules in missing state' );
488 QUnit
.test( 'htmlEqual', function ( assert
) {
490 '<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>',
491 '<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>',
492 'Attribute order, spacing and quotation marks (equal)'
496 '<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>',
497 '<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>',
498 'Attribute order, spacing and quotation marks (not equal)'
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 '<label for="firstname" accesskey="f" class="important">First</label><input id="firstname" /><label for="lastname" accesskey="l" class="minor">Last</label><input id="lastname" />',
504 'Multiple root nodes (equal)'
508 '<label for="firstname" accesskey="f" class="important">First</label><input id="firstname" /><label for="lastname" accesskey="l" class="minor">Last</label><input id="lastname" />',
509 '<label for="firstname" accesskey="f" class="important">First</label><input id="firstname" /><label for="lastname" accesskey="l" class="important" >Last</label><input id="lastname" />',
510 'Multiple root nodes (not equal, last label node is different)'
514 'fo"o<br/>b>ar',
516 'Extra escaping is equal'
521 'Text escaping (not equal)'
525 'foo<a href="http://example.com">example</a>bar',
526 'foo<a href="http://example.com">example</a>bar',
527 'Outer text nodes are compared (equal)'
531 'foo<a href="http://example.com">example</a>bar',
532 'foo<a href="http://example.com">example</a>quux',
533 'Outer text nodes are compared (last text node different)'
538 QUnit
.module( 'test.mediawiki.qunit.testrunner-after', QUnit
.newMwEnvironment() );
540 QUnit
.test( 'Teardown', function ( assert
) {
541 assert
.equal( mw
.html
.escape( '<' ), '<', 'teardown() callback was ran.' );
542 assert
.equal( mw
.config
.get( 'testVar' ), null, 'config object restored to live in next module()' );
543 assert
.equal( mw
.messages
.get( 'testMsg' ), null, 'messages object restored to live in next module()' );
546 }( jQuery
, mediaWiki
, QUnit
) );