1 /*global CompletenessTest, sinon */
3 ( function ( $, mw
, QUnit
) {
6 var mwTestIgnore
, mwTester
, addons
;
9 * Add bogus to url to prevent IE crazy caching
11 * @param value {String} a relative path (eg. 'data/foo.js'
12 * or 'data/test.php?foo=bar').
13 * @return {String} Such as 'data/foo.js?131031765087663960'
15 QUnit
.fixurl = function ( value
) {
16 return value
+ (/\?/.test( value
) ? '&' : '?')
17 + String( new Date().getTime() )
18 + String( parseInt( Math
.random() * 100000, 10 ) );
25 // When a test() indicates asynchronicity with stop(),
26 // allow 30 seconds to pass before killing the test(),
27 // and assuming failure.
28 QUnit
.config
.testTimeout
= 30 * 1000;
30 QUnit
.config
.requireExpects
= true;
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 mwTester
= new CompletenessTest( mw
, mwTestIgnore
);
165 * Reset mw.config and others to a fresh copy of the live config for each test(),
166 * and restore it back to the live one afterwards.
167 * @param localEnv {Object} [optional]
168 * @example (see test suite at the bottom of this file)
171 QUnit
.newMwEnvironment
= ( function () {
172 var warn
, error
, liveConfig
, liveMessages
,
175 liveConfig
= mw
.config
.values
;
176 liveMessages
= mw
.messages
.values
;
178 function suppressWarnings() {
180 error
= mw
.log
.error
;
181 mw
.log
.warn
= mw
.log
.error
= $.noop
;
184 function restoreWarnings() {
185 // Guard against calls not balanced with suppressWarnings()
186 if ( warn
!== undefined ) {
188 mw
.log
.error
= error
;
189 warn
= error
= undefined;
193 function freshConfigCopy( custom
) {
195 // Tests should mock all factors that directly influence the tested code.
196 // For backwards compatibility though we set mw.config to a fresh copy of the live
197 // config. This way any modifications made to mw.config during the test will not
198 // affect other tests, nor the global scope outside the test runner.
199 // This is a shallow copy, since overriding an array or object value via "custom"
200 // should replace it. Setting a config property means you override it, not extend it.
201 // NOTE: It is important that we suppress warnings because extend() will also access
202 // deprecated properties and trigger deprecation warnings from mw.log#deprecate.
204 copy
= $.extend( {}, liveConfig
, custom
);
210 function freshMessagesCopy( custom
) {
211 return $.extend( /*deep=*/true, {}, liveMessages
, custom
);
215 * @param {jQuery.Event} event
216 * @param {jqXHR} jqXHR
217 * @param {Object} ajaxOptions
219 function trackAjax( event
, jqXHR
, ajaxOptions
) {
220 ajaxRequests
.push( { xhr
: jqXHR
, options
: ajaxOptions
} );
223 return function ( localEnv
) {
224 localEnv
= $.extend( {
236 // Greetings, mock environment!
237 mw
.config
.values
= freshConfigCopy( localEnv
.config
);
238 mw
.messages
.values
= freshMessagesCopy( localEnv
.messages
);
239 this.suppressWarnings
= suppressWarnings
;
240 this.restoreWarnings
= restoreWarnings
;
242 // Start tracking ajax requests
243 $( document
).on( 'ajaxSend', trackAjax
);
245 localEnv
.setup
.call( this );
248 teardown: function () {
251 localEnv
.teardown
.call( this );
253 // Stop tracking ajax requests
254 $( document
).off( 'ajaxSend', trackAjax
);
256 // Farewell, mock environment!
257 mw
.config
.values
= liveConfig
;
258 mw
.messages
.values
= liveMessages
;
260 // As a convenience feature, automatically restore warnings if they're
261 // still suppressed by the end of the test.
264 // Tests should use fake timers or wait for animations to complete
265 // Check for incomplete animations/requests/etc and throw if there are any.
266 if ( $.timers
&& $.timers
.length
!== 0 ) {
267 timers
= $.timers
.length
;
268 $.each( $.timers
, function ( i
, timer
) {
269 var node
= timer
.elem
;
270 mw
.log
.warn( 'Unfinished animation #' + i
+ ' in ' + timer
.queue
+ ' queue on ' +
271 mw
.html
.element( node
.nodeName
.toLowerCase(), $(node
).getAttrs() )
274 // Force animations to stop to give the next test a clean start
277 throw new Error( 'Unfinished animations: ' + timers
);
280 // Test should use fake XHR, wait for requests, or call abort()
281 if ( $.active
!== undefined && $.active
!== 0 ) {
282 active
= $.grep( ajaxRequests
, function ( ajax
) {
283 return ajax
.xhr
.state() === 'pending';
285 if ( active
.length
!== $.active
) {
286 mw
.log
.warn( 'Pending requests does not match jQuery.active count' );
288 // Force requests to stop to give the next test a clean start
289 $.each( active
, function ( i
, ajax
) {
290 mw
.log
.warn( 'Unfinished AJAX request #' + i
, ajax
.options
);
295 throw new Error( 'Unfinished AJAX requests: ' + active
.length
);
302 // $.when stops as soon as one fails, which makes sense in most
303 // practical scenarios, but not in a unit test where we really do
304 // need to wait until all of them are finished.
305 QUnit
.whenPromisesComplete = function () {
306 var altPromises
= [];
308 $.each( arguments
, function ( i
, arg
) {
309 var alt
= $.Deferred();
310 altPromises
.push( alt
);
312 // Whether this one fails or not, forwards it to
313 // the 'done' (resolve) callback of the alternative promise.
314 arg
.always( alt
.resolve
);
317 return $.when
.apply( $, altPromises
);
321 * Recursively convert a node to a plain object representing its structure.
322 * Only considers attributes and contents (elements and text nodes).
323 * Attribute values are compared strictly and not normalised.
326 * @return {Object|string} Plain JavaScript value representing the node.
328 function getDomStructure( node
) {
329 var $node
, children
, processedChildren
, i
, len
, el
;
331 if ( node
.nodeType
=== Node
.ELEMENT_NODE
) {
332 children
= $node
.contents();
333 processedChildren
= [];
334 for ( i
= 0, len
= children
.length
; i
< len
; i
++ ) {
336 if ( el
.nodeType
=== Node
.ELEMENT_NODE
|| el
.nodeType
=== Node
.TEXT_NODE
) {
337 processedChildren
.push( getDomStructure( el
) );
342 tagName
: node
.tagName
,
343 attributes
: $node
.getAttrs(),
344 contents
: processedChildren
347 // Should be text node
353 * Gets structure of node for this HTML.
355 * @param {string} html HTML markup for one or more nodes.
357 function getHtmlStructure( html
) {
358 var el
= $( '<div>' ).append( html
)[0];
359 return getDomStructure( el
);
363 * Add-on assertion helpers
365 // Define the add-ons
368 // Expect boolean true
369 assertTrue: function ( actual
, message
) {
370 QUnit
.push( actual
=== true, actual
, true, message
);
373 // Expect boolean false
374 assertFalse: function ( actual
, message
) {
375 QUnit
.push( actual
=== false, actual
, false, message
);
378 // Expect numerical value less than X
379 lt: function ( actual
, expected
, message
) {
380 QUnit
.push( actual
< expected
, actual
, 'less than ' + expected
, message
);
383 // Expect numerical value less than or equal to X
384 ltOrEq: function ( actual
, expected
, message
) {
385 QUnit
.push( actual
<= expected
, actual
, 'less than or equal to ' + expected
, message
);
388 // Expect numerical value greater than X
389 gt: function ( actual
, expected
, message
) {
390 QUnit
.push( actual
> expected
, actual
, 'greater than ' + expected
, message
);
393 // Expect numerical value greater than or equal to X
394 gtOrEq: function ( actual
, expected
, message
) {
395 QUnit
.push( actual
>= expected
, actual
, 'greater than or equal to ' + expected
, message
);
399 * Asserts that two HTML strings are structurally equivalent.
401 * @param {string} actualHtml Actual HTML markup.
402 * @param {string} expectedHtml Expected HTML markup
403 * @param {string} message Assertion message.
405 htmlEqual: function ( actualHtml
, expectedHtml
, message
) {
406 var actual
= getHtmlStructure( actualHtml
),
407 expected
= getHtmlStructure( expectedHtml
);
421 * Asserts that two HTML strings are not structurally equivalent.
423 * @param {string} actualHtml Actual HTML markup.
424 * @param {string} expectedHtml Expected HTML markup.
425 * @param {string} message Assertion message.
427 notHtmlEqual: function ( actualHtml
, expectedHtml
, message
) {
428 var actual
= getHtmlStructure( actualHtml
),
429 expected
= getHtmlStructure( expectedHtml
);
443 $.extend( QUnit
.assert
, addons
);
446 * Small test suite to confirm proper functionality of the utilities and
447 * initializations defined above in this file.
449 QUnit
.module( 'test.mediawiki.qunit.testrunner', QUnit
.newMwEnvironment( {
451 this.mwHtmlLive
= mw
.html
;
453 escape: function () {
458 teardown: function () {
459 mw
.html
= this.mwHtmlLive
;
469 QUnit
.test( 'Setup', 3, function ( assert
) {
470 assert
.equal( mw
.html
.escape( 'foo' ), 'mocked', 'setup() callback was ran.' );
471 assert
.equal( mw
.config
.get( 'testVar' ), 'foo', 'config object applied' );
472 assert
.equal( mw
.messages
.get( 'testMsg' ), 'Foo.', 'messages object applied' );
474 mw
.config
.set( 'testVar', 'bar' );
475 mw
.messages
.set( 'testMsg', 'Bar.' );
478 QUnit
.test( 'Teardown', 2, function ( assert
) {
479 assert
.equal( mw
.config
.get( 'testVar' ), 'foo', 'config object restored and re-applied after test()' );
480 assert
.equal( mw
.messages
.get( 'testMsg' ), 'Foo.', 'messages object restored and re-applied after test()' );
483 QUnit
.test( 'Loader status', 2, function ( assert
) {
485 modules
= mw
.loader
.getModuleNames(),
489 for ( i
= 0, len
= modules
.length
; i
< len
; i
++ ) {
490 state
= mw
.loader
.getState( modules
[i
] );
491 if ( state
=== 'error' ) {
492 error
.push( modules
[i
] );
493 } else if ( state
=== 'missing' ) {
494 missing
.push( modules
[i
] );
498 assert
.deepEqual( error
, [], 'Modules in error state' );
499 assert
.deepEqual( missing
, [], 'Modules in missing state' );
502 QUnit
.test( 'htmlEqual', 8, function ( assert
) {
504 '<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>',
505 '<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>',
506 'Attribute order, spacing and quotation marks (equal)'
510 '<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>',
511 '<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>',
512 'Attribute order, spacing and quotation marks (not equal)'
516 '<label for="firstname" accesskey="f" class="important">First</label><input id="firstname" /><label for="lastname" accesskey="l" class="minor">Last</label><input id="lastname" />',
517 '<label for="firstname" accesskey="f" class="important">First</label><input id="firstname" /><label for="lastname" accesskey="l" class="minor">Last</label><input id="lastname" />',
518 'Multiple root nodes (equal)'
522 '<label for="firstname" accesskey="f" class="important">First</label><input id="firstname" /><label for="lastname" accesskey="l" class="minor">Last</label><input id="lastname" />',
523 '<label for="firstname" accesskey="f" class="important">First</label><input id="firstname" /><label for="lastname" accesskey="l" class="important" >Last</label><input id="lastname" />',
524 'Multiple root nodes (not equal, last label node is different)'
528 'fo"o<br/>b>ar',
530 'Extra escaping is equal'
535 'Text escaping (not equal)'
539 'foo<a href="http://example.com">example</a>bar',
540 'foo<a href="http://example.com">example</a>bar',
541 'Outer text nodes are compared (equal)'
545 'foo<a href="http://example.com">example</a>bar',
546 'foo<a href="http://example.com">example</a>quux',
547 'Outer text nodes are compared (last text node different)'
552 QUnit
.module( 'test.mediawiki.qunit.testrunner-after', QUnit
.newMwEnvironment() );
554 QUnit
.test( 'Teardown', 3, function ( assert
) {
555 assert
.equal( mw
.html
.escape( '<' ), '<', 'teardown() callback was ran.' );
556 assert
.equal( mw
.config
.get( 'testVar' ), null, 'config object restored to live in next module()' );
557 assert
.equal( mw
.messages
.get( 'testMsg' ), null, 'messages object restored to live in next module()' );
560 }( jQuery
, mediaWiki
, QUnit
) );