b0118afbec88279befecf5e69f406acda7fb13c5
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() {
135 error
= mw
.log
.error
;
136 mw
.log
.warn
= mw
.log
.error
= $.noop
;
139 function restoreWarnings() {
140 // Guard against calls not balanced with suppressWarnings()
141 if ( warn
!== undefined ) {
143 mw
.log
.error
= error
;
144 warn
= error
= undefined;
148 function freshConfigCopy( custom
) {
150 // Tests should mock all factors that directly influence the tested code.
151 // For backwards compatibility though we set mw.config to a fresh copy of the live
152 // config. This way any modifications made to mw.config during the test will not
153 // affect other tests, nor the global scope outside the test runner.
154 // This is a shallow copy, since overriding an array or object value via "custom"
155 // should replace it. Setting a config property means you override it, not extend it.
156 // NOTE: It is important that we suppress warnings because extend() will also access
157 // deprecated properties and trigger deprecation warnings from mw.log#deprecate.
159 copy
= $.extend( {}, liveConfig
.get(), custom
);
165 function freshMessagesCopy( custom
) {
166 return $.extend( /* deep */true, {}, liveMessages
.get(), custom
);
170 * @param {jQuery.Event} event
171 * @param {jqXHR} jqXHR
172 * @param {Object} ajaxOptions
174 function trackAjax( event
, jqXHR
, ajaxOptions
) {
175 ajaxRequests
.push( { xhr
: jqXHR
, options
: ajaxOptions
} );
178 return function ( localEnv
) {
179 localEnv
= $.extend( {
191 // Greetings, mock environment!
192 mw
.config
= new MwMap();
193 mw
.config
.set( freshConfigCopy( localEnv
.config
) );
194 mw
.messages
= new MwMap();
195 mw
.messages
.set( freshMessagesCopy( localEnv
.messages
) );
196 // Update reference to mw.messages
197 mw
.jqueryMsg
.setParserDefaults( {
198 messages
: mw
.messages
201 this.suppressWarnings
= suppressWarnings
;
202 this.restoreWarnings
= restoreWarnings
;
204 // Start tracking ajax requests
205 $( document
).on( 'ajaxSend', trackAjax
);
207 localEnv
.setup
.call( this );
210 teardown: function () {
211 var timers
, pending
, $activeLen
;
213 localEnv
.teardown
.call( this );
215 // Stop tracking ajax requests
216 $( document
).off( 'ajaxSend', trackAjax
);
218 // Farewell, mock environment!
219 mw
.config
= liveConfig
;
220 mw
.messages
= liveMessages
;
221 // Restore reference to mw.messages
222 mw
.jqueryMsg
.setParserDefaults( {
223 messages
: liveMessages
226 // As a convenience feature, automatically restore warnings if they're
227 // still suppressed by the end of the test.
230 // Tests should use fake timers or wait for animations to complete
231 // Check for incomplete animations/requests/etc and throw if there are any.
232 if ( $.timers
&& $.timers
.length
!== 0 ) {
233 timers
= $.timers
.length
;
234 $.each( $.timers
, function ( i
, timer
) {
235 var node
= timer
.elem
;
236 mw
.log
.warn( 'Unfinished animation #' + i
+ ' in ' + timer
.queue
+ ' queue on ' +
237 mw
.html
.element( node
.nodeName
.toLowerCase(), $( node
).getAttrs() )
240 // Force animations to stop to give the next test a clean start
243 throw new Error( 'Unfinished animations: ' + timers
);
246 // Test should use fake XHR, wait for requests, or call abort()
247 $activeLen
= $.active
;
248 if ( $activeLen
!== undefined && $activeLen
!== 0 ) {
249 pending
= $.grep( ajaxRequests
, function ( ajax
) {
250 return ajax
.xhr
.state() === 'pending';
252 if ( pending
.length
!== $activeLen
) {
253 mw
.log
.warn( 'Pending requests does not match jQuery.active count' );
255 // Force requests to stop to give the next test a clean start
256 $.each( pending
, function ( i
, ajax
) {
257 mw
.log
.warn( 'Pending AJAX request #' + i
, ajax
.options
);
262 throw new Error( 'Pending AJAX requests: ' + pending
.length
+ ' (active: ' + $activeLen
+ ')' );
269 // $.when stops as soon as one fails, which makes sense in most
270 // practical scenarios, but not in a unit test where we really do
271 // need to wait until all of them are finished.
272 QUnit
.whenPromisesComplete = function () {
273 var altPromises
= [];
275 $.each( arguments
, function ( i
, arg
) {
276 var alt
= $.Deferred();
277 altPromises
.push( alt
);
279 // Whether this one fails or not, forwards it to
280 // the 'done' (resolve) callback of the alternative promise.
281 arg
.always( alt
.resolve
);
284 return $.when
.apply( $, altPromises
);
288 * Recursively convert a node to a plain object representing its structure.
289 * Only considers attributes and contents (elements and text nodes).
290 * Attribute values are compared strictly and not normalised.
293 * @return {Object|string} Plain JavaScript value representing the node.
295 function getDomStructure( node
) {
296 var $node
, children
, processedChildren
, i
, len
, el
;
298 if ( node
.nodeType
=== Node
.ELEMENT_NODE
) {
299 children
= $node
.contents();
300 processedChildren
= [];
301 for ( i
= 0, len
= children
.length
; i
< len
; i
++ ) {
303 if ( el
.nodeType
=== Node
.ELEMENT_NODE
|| el
.nodeType
=== Node
.TEXT_NODE
) {
304 processedChildren
.push( getDomStructure( el
) );
309 tagName
: node
.tagName
,
310 attributes
: $node
.getAttrs(),
311 contents
: processedChildren
314 // Should be text node
320 * Gets structure of node for this HTML.
322 * @param {string} html HTML markup for one or more nodes.
324 function getHtmlStructure( html
) {
325 var el
= $( '<div>' ).append( html
)[ 0 ];
326 return getDomStructure( el
);
330 * Add-on assertion helpers
332 // Define the add-ons
335 // Expect boolean true
336 assertTrue: function ( actual
, message
) {
337 QUnit
.push( actual
=== true, actual
, true, message
);
340 // Expect boolean false
341 assertFalse: function ( actual
, message
) {
342 QUnit
.push( actual
=== false, actual
, false, message
);
345 // Expect numerical value less than X
346 lt: function ( actual
, expected
, message
) {
347 QUnit
.push( actual
< expected
, actual
, 'less than ' + expected
, message
);
350 // Expect numerical value less than or equal to X
351 ltOrEq: function ( actual
, expected
, message
) {
352 QUnit
.push( actual
<= expected
, actual
, 'less than or equal to ' + expected
, message
);
355 // Expect numerical value greater than X
356 gt: function ( actual
, expected
, message
) {
357 QUnit
.push( actual
> expected
, actual
, 'greater than ' + expected
, message
);
360 // Expect numerical value greater than or equal to X
361 gtOrEq: function ( actual
, expected
, message
) {
362 QUnit
.push( actual
>= expected
, actual
, 'greater than or equal to ' + expected
, message
);
366 * Asserts that two HTML strings are structurally equivalent.
368 * @param {string} actualHtml Actual HTML markup.
369 * @param {string} expectedHtml Expected HTML markup
370 * @param {string} message Assertion message.
372 htmlEqual: function ( actualHtml
, expectedHtml
, message
) {
373 var actual
= getHtmlStructure( actualHtml
),
374 expected
= getHtmlStructure( expectedHtml
);
388 * Asserts that two HTML strings are not structurally equivalent.
390 * @param {string} actualHtml Actual HTML markup.
391 * @param {string} expectedHtml Expected HTML markup.
392 * @param {string} message Assertion message.
394 notHtmlEqual: function ( actualHtml
, expectedHtml
, message
) {
395 var actual
= getHtmlStructure( actualHtml
),
396 expected
= getHtmlStructure( expectedHtml
);
410 $.extend( QUnit
.assert
, addons
);
413 * Small test suite to confirm proper functionality of the utilities and
414 * initializations defined above in this file.
416 QUnit
.module( 'test.mediawiki.qunit.testrunner', QUnit
.newMwEnvironment( {
418 this.mwHtmlLive
= mw
.html
;
420 escape: function () {
425 teardown: function () {
426 mw
.html
= this.mwHtmlLive
;
436 QUnit
.test( 'Setup', function ( assert
) {
437 assert
.equal( mw
.html
.escape( 'foo' ), 'mocked', 'setup() callback was ran.' );
438 assert
.equal( mw
.config
.get( 'testVar' ), 'foo', 'config object applied' );
439 assert
.equal( mw
.messages
.get( 'testMsg' ), 'Foo.', 'messages object applied' );
441 mw
.config
.set( 'testVar', 'bar' );
442 mw
.messages
.set( 'testMsg', 'Bar.' );
445 QUnit
.test( 'Teardown', function ( assert
) {
446 assert
.equal( mw
.config
.get( 'testVar' ), 'foo', 'config object restored and re-applied after test()' );
447 assert
.equal( mw
.messages
.get( 'testMsg' ), 'Foo.', 'messages object restored and re-applied after test()' );
450 QUnit
.test( 'Loader status', function ( assert
) {
452 modules
= mw
.loader
.getModuleNames(),
456 for ( i
= 0, len
= modules
.length
; i
< len
; i
++ ) {
457 state
= mw
.loader
.getState( modules
[ i
] );
458 if ( state
=== 'error' ) {
459 error
.push( modules
[ i
] );
460 } else if ( state
=== 'missing' ) {
461 missing
.push( modules
[ i
] );
465 assert
.deepEqual( error
, [], 'Modules in error state' );
466 assert
.deepEqual( missing
, [], 'Modules in missing state' );
469 QUnit
.test( 'htmlEqual', function ( assert
) {
471 '<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>',
472 '<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>',
473 'Attribute order, spacing and quotation marks (equal)'
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 more 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 (not equal)'
483 '<label for="firstname" accesskey="f" class="important">First</label><input id="firstname" /><label for="lastname" accesskey="l" class="minor">Last</label><input id="lastname" />',
484 '<label for="firstname" accesskey="f" class="important">First</label><input id="firstname" /><label for="lastname" accesskey="l" class="minor">Last</label><input id="lastname" />',
485 'Multiple root nodes (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="important" >Last</label><input id="lastname" />',
491 'Multiple root nodes (not equal, last label node is different)'
495 'fo"o<br/>b>ar',
497 'Extra escaping is equal'
502 'Text escaping (not equal)'
506 'foo<a href="http://example.com">example</a>bar',
507 'foo<a href="http://example.com">example</a>bar',
508 'Outer text nodes are compared (equal)'
512 'foo<a href="http://example.com">example</a>bar',
513 'foo<a href="http://example.com">example</a>quux',
514 'Outer text nodes are compared (last text node different)'
519 QUnit
.module( 'test.mediawiki.qunit.testrunner-after', QUnit
.newMwEnvironment() );
521 QUnit
.test( 'Teardown', function ( assert
) {
522 assert
.equal( mw
.html
.escape( '<' ), '<', 'teardown() callback was ran.' );
523 assert
.equal( mw
.config
.get( 'testVar' ), null, 'config object restored to live in next module()' );
524 assert
.equal( mw
.messages
.get( 'testMsg' ), null, 'messages object restored to live in next module()' );
527 }( jQuery
, mediaWiki
, QUnit
) );