1 /* global CompletenessTest, sinon */
2 ( function ( $, mw
, QUnit
) {
5 var mwTestIgnore
, addons
;
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 * Adds toggle checkbox to header
45 QUnit
.config
.urlConfig
.push( {
46 id
: 'completenesstest',
47 label
: 'Run CompletenessTest',
48 tooltip
: 'Run the completeness test'
54 * Glue code for nicer integration with QUnit setup/teardown
55 * Inspired by http://sinonjs.org/releases/sinon-qunit-1.0.0.js
57 * - Work properly with asynchronous QUnit by using module setup/teardown
58 * instead of synchronously wrapping QUnit.test.
60 sinon
.assert
.fail = function ( msg
) {
61 QUnit
.assert
.ok( false, msg
);
63 sinon
.assert
.pass = function ( msg
) {
64 QUnit
.assert
.ok( true, msg
);
69 properties
: [ 'spy', 'stub', 'mock', 'sandbox' ],
70 // Don't fake timers by default
75 var orgModule
= QUnit
.module
;
77 QUnit
.module = function ( name
, 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
) {
106 localEnv
= localEnv
|| {};
109 fixture
= document
.createElement( 'div' );
110 fixture
.id
= 'qunit-fixture';
111 document
.body
.appendChild( fixture
);
113 if ( localEnv
.setup
) {
114 localEnv
.setup
.call( this );
117 teardown: function () {
118 if ( localEnv
.teardown
) {
119 localEnv
.teardown
.call( this );
122 fixture
.parentNode
.removeChild( fixture
);
128 // Initiate when enabled
129 if ( QUnit
.urlParams
.completenesstest
) {
131 // Return true to ignore
132 mwTestIgnore = function ( val
, tester
) {
134 // Don't record methods of the properties of constructors,
135 // to avoid getting into a loop (prototype.constructor.prototype..).
136 // Since we're therefor skipping any injection for
137 // "new mw.Foo()", manually set it to true here.
138 if ( val
instanceof mw
.Map
) {
139 tester
.methodCallTracker
.Map
= true;
142 if ( val
instanceof mw
.Title
) {
143 tester
.methodCallTracker
.Title
= true;
147 // Don't record methods of the properties of a jQuery object
148 if ( val
instanceof $ ) {
152 // Don't iterate over the module registry (the 'script' references would
153 // be listed as untested methods otherwise)
154 if ( val
=== mw
.loader
.moduleRegistry
) {
161 // eslint-disable-next-line no-new
162 new CompletenessTest( mw
, mwTestIgnore
);
166 * Reset mw.config and others to a fresh copy of the live config for each test(),
167 * and restore it back to the live one afterwards.
169 * @param {Object} [localEnv]
170 * @example (see test suite at the bottom of this file)
173 QUnit
.newMwEnvironment
= ( function () {
174 var warn
, error
, liveConfig
, liveMessages
,
175 MwMap
= mw
.config
.constructor, // internal use only
178 liveConfig
= mw
.config
;
179 liveMessages
= mw
.messages
;
181 function suppressWarnings() {
183 error
= mw
.log
.error
;
184 mw
.log
.warn
= mw
.log
.error
= $.noop
;
187 function restoreWarnings() {
188 // Guard against calls not balanced with suppressWarnings()
189 if ( warn
!== undefined ) {
191 mw
.log
.error
= error
;
192 warn
= error
= undefined;
196 function freshConfigCopy( custom
) {
198 // Tests should mock all factors that directly influence the tested code.
199 // For backwards compatibility though we set mw.config to a fresh copy of the live
200 // config. This way any modifications made to mw.config during the test will not
201 // affect other tests, nor the global scope outside the test runner.
202 // This is a shallow copy, since overriding an array or object value via "custom"
203 // should replace it. Setting a config property means you override it, not extend it.
204 // NOTE: It is important that we suppress warnings because extend() will also access
205 // deprecated properties and trigger deprecation warnings from mw.log#deprecate.
207 copy
= $.extend( {}, liveConfig
.get(), custom
);
213 function freshMessagesCopy( custom
) {
214 return $.extend( /* deep */true, {}, liveMessages
.get(), custom
);
218 * @param {jQuery.Event} event
219 * @param {jqXHR} jqXHR
220 * @param {Object} ajaxOptions
222 function trackAjax( event
, jqXHR
, ajaxOptions
) {
223 ajaxRequests
.push( { xhr
: jqXHR
, options
: ajaxOptions
} );
226 return function ( localEnv
) {
227 localEnv
= $.extend( {
239 // Greetings, mock environment!
240 mw
.config
= new MwMap();
241 mw
.config
.set( freshConfigCopy( localEnv
.config
) );
242 mw
.messages
= new MwMap();
243 mw
.messages
.set( freshMessagesCopy( localEnv
.messages
) );
244 // Update reference to mw.messages
245 mw
.jqueryMsg
.setParserDefaults( {
246 messages
: mw
.messages
249 this.suppressWarnings
= suppressWarnings
;
250 this.restoreWarnings
= restoreWarnings
;
252 // Start tracking ajax requests
253 $( document
).on( 'ajaxSend', trackAjax
);
255 localEnv
.setup
.call( this );
258 teardown: function () {
259 var timers
, pending
, $activeLen
;
261 localEnv
.teardown
.call( this );
263 // Stop tracking ajax requests
264 $( document
).off( 'ajaxSend', trackAjax
);
266 // Farewell, mock environment!
267 mw
.config
= liveConfig
;
268 mw
.messages
= liveMessages
;
269 // Restore reference to mw.messages
270 mw
.jqueryMsg
.setParserDefaults( {
271 messages
: liveMessages
274 // As a convenience feature, automatically restore warnings if they're
275 // still suppressed by the end of the test.
278 // Tests should use fake timers or wait for animations to complete
279 // Check for incomplete animations/requests/etc and throw if there are any.
280 if ( $.timers
&& $.timers
.length
!== 0 ) {
281 timers
= $.timers
.length
;
282 $.each( $.timers
, function ( i
, timer
) {
283 var node
= timer
.elem
;
284 mw
.log
.warn( 'Unfinished animation #' + i
+ ' in ' + timer
.queue
+ ' queue on ' +
285 mw
.html
.element( node
.nodeName
.toLowerCase(), $( node
).getAttrs() )
288 // Force animations to stop to give the next test a clean start
291 throw new Error( 'Unfinished animations: ' + timers
);
294 // Test should use fake XHR, wait for requests, or call abort()
295 $activeLen
= $.active
;
296 if ( $activeLen
!== undefined && $activeLen
!== 0 ) {
297 pending
= $.grep( ajaxRequests
, function ( ajax
) {
298 return ajax
.xhr
.state() === 'pending';
300 if ( pending
.length
!== $activeLen
) {
301 mw
.log
.warn( 'Pending requests does not match jQuery.active count' );
303 // Force requests to stop to give the next test a clean start
304 $.each( pending
, function ( i
, ajax
) {
305 mw
.log
.warn( 'Pending AJAX request #' + i
, ajax
.options
);
310 throw new Error( 'Pending AJAX requests: ' + pending
.length
+ ' (active: ' + $activeLen
+ ')' );
317 // $.when stops as soon as one fails, which makes sense in most
318 // practical scenarios, but not in a unit test where we really do
319 // need to wait until all of them are finished.
320 QUnit
.whenPromisesComplete = function () {
321 var altPromises
= [];
323 $.each( arguments
, function ( i
, arg
) {
324 var alt
= $.Deferred();
325 altPromises
.push( alt
);
327 // Whether this one fails or not, forwards it to
328 // the 'done' (resolve) callback of the alternative promise.
329 arg
.always( alt
.resolve
);
332 return $.when
.apply( $, altPromises
);
336 * Recursively convert a node to a plain object representing its structure.
337 * Only considers attributes and contents (elements and text nodes).
338 * Attribute values are compared strictly and not normalised.
341 * @return {Object|string} Plain JavaScript value representing the node.
343 function getDomStructure( node
) {
344 var $node
, children
, processedChildren
, i
, len
, el
;
346 if ( node
.nodeType
=== Node
.ELEMENT_NODE
) {
347 children
= $node
.contents();
348 processedChildren
= [];
349 for ( i
= 0, len
= children
.length
; i
< len
; i
++ ) {
351 if ( el
.nodeType
=== Node
.ELEMENT_NODE
|| el
.nodeType
=== Node
.TEXT_NODE
) {
352 processedChildren
.push( getDomStructure( el
) );
357 tagName
: node
.tagName
,
358 attributes
: $node
.getAttrs(),
359 contents
: processedChildren
362 // Should be text node
368 * Gets structure of node for this HTML.
370 * @param {string} html HTML markup for one or more nodes.
372 function getHtmlStructure( html
) {
373 var el
= $( '<div>' ).append( html
)[ 0 ];
374 return getDomStructure( el
);
378 * Add-on assertion helpers
380 // Define the add-ons
383 // Expect boolean true
384 assertTrue: function ( actual
, message
) {
385 QUnit
.push( actual
=== true, actual
, true, message
);
388 // Expect boolean false
389 assertFalse: function ( actual
, message
) {
390 QUnit
.push( actual
=== false, actual
, false, message
);
393 // Expect numerical value less than X
394 lt: function ( actual
, expected
, message
) {
395 QUnit
.push( actual
< expected
, actual
, 'less than ' + expected
, message
);
398 // Expect numerical value less than or equal to X
399 ltOrEq: function ( actual
, expected
, message
) {
400 QUnit
.push( actual
<= expected
, actual
, 'less than or equal to ' + expected
, message
);
403 // Expect numerical value greater than X
404 gt: function ( actual
, expected
, message
) {
405 QUnit
.push( actual
> expected
, actual
, 'greater than ' + expected
, message
);
408 // Expect numerical value greater than or equal to X
409 gtOrEq: function ( actual
, expected
, message
) {
410 QUnit
.push( actual
>= expected
, actual
, 'greater than or equal to ' + expected
, message
);
414 * Asserts that two HTML strings are structurally equivalent.
416 * @param {string} actualHtml Actual HTML markup.
417 * @param {string} expectedHtml Expected HTML markup
418 * @param {string} message Assertion message.
420 htmlEqual: function ( actualHtml
, expectedHtml
, message
) {
421 var actual
= getHtmlStructure( actualHtml
),
422 expected
= getHtmlStructure( expectedHtml
);
436 * Asserts that two HTML strings are not structurally equivalent.
438 * @param {string} actualHtml Actual HTML markup.
439 * @param {string} expectedHtml Expected HTML markup.
440 * @param {string} message Assertion message.
442 notHtmlEqual: function ( actualHtml
, expectedHtml
, message
) {
443 var actual
= getHtmlStructure( actualHtml
),
444 expected
= getHtmlStructure( expectedHtml
);
458 $.extend( QUnit
.assert
, addons
);
461 * Small test suite to confirm proper functionality of the utilities and
462 * initializations defined above in this file.
464 QUnit
.module( 'test.mediawiki.qunit.testrunner', QUnit
.newMwEnvironment( {
466 this.mwHtmlLive
= mw
.html
;
468 escape: function () {
473 teardown: function () {
474 mw
.html
= this.mwHtmlLive
;
484 QUnit
.test( 'Setup', function ( assert
) {
485 assert
.equal( mw
.html
.escape( 'foo' ), 'mocked', 'setup() callback was ran.' );
486 assert
.equal( mw
.config
.get( 'testVar' ), 'foo', 'config object applied' );
487 assert
.equal( mw
.messages
.get( 'testMsg' ), 'Foo.', 'messages object applied' );
489 mw
.config
.set( 'testVar', 'bar' );
490 mw
.messages
.set( 'testMsg', 'Bar.' );
493 QUnit
.test( 'Teardown', function ( assert
) {
494 assert
.equal( mw
.config
.get( 'testVar' ), 'foo', 'config object restored and re-applied after test()' );
495 assert
.equal( mw
.messages
.get( 'testMsg' ), 'Foo.', 'messages object restored and re-applied after test()' );
498 QUnit
.test( 'Loader status', function ( assert
) {
500 modules
= mw
.loader
.getModuleNames(),
504 for ( i
= 0, len
= modules
.length
; i
< len
; i
++ ) {
505 state
= mw
.loader
.getState( modules
[ i
] );
506 if ( state
=== 'error' ) {
507 error
.push( modules
[ i
] );
508 } else if ( state
=== 'missing' ) {
509 missing
.push( modules
[ i
] );
513 assert
.deepEqual( error
, [], 'Modules in error state' );
514 assert
.deepEqual( missing
, [], 'Modules in missing state' );
517 QUnit
.test( 'htmlEqual', function ( assert
) {
519 '<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>',
520 '<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>',
521 'Attribute order, spacing and quotation marks (equal)'
525 '<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>',
526 '<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>',
527 'Attribute order, spacing and quotation marks (not equal)'
531 '<label for="firstname" accesskey="f" class="important">First</label><input id="firstname" /><label for="lastname" accesskey="l" class="minor">Last</label><input id="lastname" />',
532 '<label for="firstname" accesskey="f" class="important">First</label><input id="firstname" /><label for="lastname" accesskey="l" class="minor">Last</label><input id="lastname" />',
533 'Multiple root nodes (equal)'
537 '<label for="firstname" accesskey="f" class="important">First</label><input id="firstname" /><label for="lastname" accesskey="l" class="minor">Last</label><input id="lastname" />',
538 '<label for="firstname" accesskey="f" class="important">First</label><input id="firstname" /><label for="lastname" accesskey="l" class="important" >Last</label><input id="lastname" />',
539 'Multiple root nodes (not equal, last label node is different)'
543 'fo"o<br/>b>ar',
545 'Extra escaping is equal'
550 'Text escaping (not equal)'
554 'foo<a href="http://example.com">example</a>bar',
555 'foo<a href="http://example.com">example</a>bar',
556 'Outer text nodes are compared (equal)'
560 'foo<a href="http://example.com">example</a>bar',
561 'foo<a href="http://example.com">example</a>quux',
562 'Outer text nodes are compared (last text node different)'
567 QUnit
.module( 'test.mediawiki.qunit.testrunner-after', QUnit
.newMwEnvironment() );
569 QUnit
.test( 'Teardown', function ( assert
) {
570 assert
.equal( mw
.html
.escape( '<' ), '<', 'teardown() callback was ran.' );
571 assert
.equal( mw
.config
.get( 'testVar' ), null, 'config object restored to live in next module()' );
572 assert
.equal( mw
.messages
.get( 'testMsg' ), null, 'messages object restored to live in next module()' );
575 }( jQuery
, mediaWiki
, QUnit
) );