1 /*global CompletenessTest, sinon */
2 ( function ( $, mw
, QUnit
) {
5 var mwTestIgnore
, mwTester
, 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 // Add a checkbox to QUnit header to toggle MediaWiki ResourceLoader debug mode.
29 QUnit
.config
.urlConfig
.push( {
31 label
: 'Enable ResourceLoaderDebug',
32 tooltip
: 'Enable debug mode in ResourceLoader',
39 * Adds toggle checkbox to header
41 QUnit
.config
.urlConfig
.push( {
42 id
: 'completenesstest',
43 label
: 'Run CompletenessTest',
44 tooltip
: 'Run the completeness test'
50 * Glue code for nicer integration with QUnit setup/teardown
51 * Inspired by http://sinonjs.org/releases/sinon-qunit-1.0.0.js
53 * - Work properly with asynchronous QUnit by using module setup/teardown
54 * instead of synchronously wrapping QUnit.test.
56 sinon
.assert
.fail = function ( msg
) {
57 QUnit
.assert
.ok( false, msg
);
59 sinon
.assert
.pass = function ( msg
) {
60 QUnit
.assert
.ok( true, msg
);
65 properties
: [ 'spy', 'stub', 'mock', 'sandbox' ],
66 // Don't fake timers by default
71 var orgModule
= QUnit
.module
;
73 QUnit
.module = function ( name
, localEnv
) {
74 localEnv
= localEnv
|| {};
77 var config
= sinon
.getConfig( sinon
.config
);
78 config
.injectInto
= this;
79 sinon
.sandbox
.create( config
);
81 if ( localEnv
.setup
) {
82 localEnv
.setup
.call( this );
85 teardown: function () {
86 if ( localEnv
.teardown
) {
87 localEnv
.teardown
.call( this );
90 this.sandbox
.verifyAndRestore();
96 // Extend QUnit.module to provide a fixture element.
98 var orgModule
= QUnit
.module
;
100 QUnit
.module = function ( name
, localEnv
) {
102 localEnv
= localEnv
|| {};
105 fixture
= document
.createElement( 'div' );
106 fixture
.id
= 'qunit-fixture';
107 document
.body
.appendChild( fixture
);
109 if ( localEnv
.setup
) {
110 localEnv
.setup
.call( this );
113 teardown: function () {
114 if ( localEnv
.teardown
) {
115 localEnv
.teardown
.call( this );
118 fixture
.parentNode
.removeChild( fixture
);
124 // Initiate when enabled
125 if ( QUnit
.urlParams
.completenesstest
) {
127 // Return true to ignore
128 mwTestIgnore = function ( val
, tester
) {
130 // Don't record methods of the properties of constructors,
131 // to avoid getting into a loop (prototype.constructor.prototype..).
132 // Since we're therefor skipping any injection for
133 // "new mw.Foo()", manually set it to true here.
134 if ( val
instanceof mw
.Map
) {
135 tester
.methodCallTracker
.Map
= true;
138 if ( val
instanceof mw
.Title
) {
139 tester
.methodCallTracker
.Title
= true;
143 // Don't record methods of the properties of a jQuery object
144 if ( val
instanceof $ ) {
148 // Don't iterate over the module registry (the 'script' references would
149 // be listed as untested methods otherwise)
150 if ( val
=== mw
.loader
.moduleRegistry
) {
157 mwTester
= new CompletenessTest( mw
, mwTestIgnore
);
161 * Reset mw.config and others to a fresh copy of the live config for each test(),
162 * and restore it back to the live one afterwards.
164 * @param {Object} [localEnv]
165 * @example (see test suite at the bottom of this file)
168 QUnit
.newMwEnvironment
= ( function () {
169 var warn
, error
, liveConfig
, liveMessages
,
172 liveConfig
= mw
.config
.values
;
173 liveMessages
= mw
.messages
.values
;
175 function suppressWarnings() {
177 error
= mw
.log
.error
;
178 mw
.log
.warn
= mw
.log
.error
= $.noop
;
181 function restoreWarnings() {
182 // Guard against calls not balanced with suppressWarnings()
183 if ( warn
!== undefined ) {
185 mw
.log
.error
= error
;
186 warn
= error
= undefined;
190 function freshConfigCopy( custom
) {
192 // Tests should mock all factors that directly influence the tested code.
193 // For backwards compatibility though we set mw.config to a fresh copy of the live
194 // config. This way any modifications made to mw.config during the test will not
195 // affect other tests, nor the global scope outside the test runner.
196 // This is a shallow copy, since overriding an array or object value via "custom"
197 // should replace it. Setting a config property means you override it, not extend it.
198 // NOTE: It is important that we suppress warnings because extend() will also access
199 // deprecated properties and trigger deprecation warnings from mw.log#deprecate.
201 copy
= $.extend( {}, liveConfig
, custom
);
207 function freshMessagesCopy( custom
) {
208 return $.extend( /*deep=*/true, {}, liveMessages
, custom
);
212 * @param {jQuery.Event} event
213 * @param {jqXHR} jqXHR
214 * @param {Object} ajaxOptions
216 function trackAjax( event
, jqXHR
, ajaxOptions
) {
217 ajaxRequests
.push( { xhr
: jqXHR
, options
: ajaxOptions
} );
220 return function ( localEnv
) {
221 localEnv
= $.extend( {
233 // Greetings, mock environment!
234 mw
.config
.values
= freshConfigCopy( localEnv
.config
);
235 mw
.messages
.values
= freshMessagesCopy( localEnv
.messages
);
236 this.suppressWarnings
= suppressWarnings
;
237 this.restoreWarnings
= restoreWarnings
;
239 // Start tracking ajax requests
240 $( document
).on( 'ajaxSend', trackAjax
);
242 localEnv
.setup
.call( this );
245 teardown: function () {
246 var timers
, pending
, $activeLen
;
248 localEnv
.teardown
.call( this );
250 // Stop tracking ajax requests
251 $( document
).off( 'ajaxSend', trackAjax
);
253 // Farewell, mock environment!
254 mw
.config
.values
= liveConfig
;
255 mw
.messages
.values
= liveMessages
;
257 // As a convenience feature, automatically restore warnings if they're
258 // still suppressed by the end of the test.
261 // Tests should use fake timers or wait for animations to complete
262 // Check for incomplete animations/requests/etc and throw if there are any.
263 if ( $.timers
&& $.timers
.length
!== 0 ) {
264 timers
= $.timers
.length
;
265 $.each( $.timers
, function ( i
, timer
) {
266 var node
= timer
.elem
;
267 mw
.log
.warn( 'Unfinished animation #' + i
+ ' in ' + timer
.queue
+ ' queue on ' +
268 mw
.html
.element( node
.nodeName
.toLowerCase(), $( node
).getAttrs() )
271 // Force animations to stop to give the next test a clean start
274 throw new Error( 'Unfinished animations: ' + timers
);
277 // Test should use fake XHR, wait for requests, or call abort()
278 $activeLen
= $.active
;
279 if ( $activeLen
!== undefined && $activeLen
!== 0 ) {
280 pending
= $.grep( ajaxRequests
, function ( ajax
) {
281 return ajax
.xhr
.state() === 'pending';
283 if ( pending
.length
!== $activeLen
) {
284 mw
.log
.warn( 'Pending requests does not match jQuery.active count' );
286 // Force requests to stop to give the next test a clean start
287 $.each( pending
, function ( i
, ajax
) {
288 mw
.log
.warn( 'Pending AJAX request #' + i
, ajax
.options
);
293 throw new Error( 'Pending AJAX requests: ' + pending
.length
+ ' (active: ' + $activeLen
+ ')' );
300 // $.when stops as soon as one fails, which makes sense in most
301 // practical scenarios, but not in a unit test where we really do
302 // need to wait until all of them are finished.
303 QUnit
.whenPromisesComplete = function () {
304 var altPromises
= [];
306 $.each( arguments
, function ( i
, arg
) {
307 var alt
= $.Deferred();
308 altPromises
.push( alt
);
310 // Whether this one fails or not, forwards it to
311 // the 'done' (resolve) callback of the alternative promise.
312 arg
.always( alt
.resolve
);
315 return $.when
.apply( $, altPromises
);
319 * Recursively convert a node to a plain object representing its structure.
320 * Only considers attributes and contents (elements and text nodes).
321 * Attribute values are compared strictly and not normalised.
324 * @return {Object|string} Plain JavaScript value representing the node.
326 function getDomStructure( node
) {
327 var $node
, children
, processedChildren
, i
, len
, el
;
329 if ( node
.nodeType
=== Node
.ELEMENT_NODE
) {
330 children
= $node
.contents();
331 processedChildren
= [];
332 for ( i
= 0, len
= children
.length
; i
< len
; i
++ ) {
334 if ( el
.nodeType
=== Node
.ELEMENT_NODE
|| el
.nodeType
=== Node
.TEXT_NODE
) {
335 processedChildren
.push( getDomStructure( el
) );
340 tagName
: node
.tagName
,
341 attributes
: $node
.getAttrs(),
342 contents
: processedChildren
345 // Should be text node
351 * Gets structure of node for this HTML.
353 * @param {string} html HTML markup for one or more nodes.
355 function getHtmlStructure( html
) {
356 var el
= $( '<div>' ).append( html
)[ 0 ];
357 return getDomStructure( el
);
361 * Add-on assertion helpers
363 // Define the add-ons
366 // Expect boolean true
367 assertTrue: function ( actual
, message
) {
368 QUnit
.push( actual
=== true, actual
, true, message
);
371 // Expect boolean false
372 assertFalse: function ( actual
, message
) {
373 QUnit
.push( actual
=== false, actual
, false, message
);
376 // Expect numerical value less than X
377 lt: function ( actual
, expected
, message
) {
378 QUnit
.push( actual
< expected
, actual
, 'less than ' + expected
, message
);
381 // Expect numerical value less than or equal to X
382 ltOrEq: function ( actual
, expected
, message
) {
383 QUnit
.push( actual
<= expected
, actual
, 'less than or equal to ' + expected
, message
);
386 // Expect numerical value greater than X
387 gt: function ( actual
, expected
, message
) {
388 QUnit
.push( actual
> expected
, actual
, 'greater than ' + expected
, message
);
391 // Expect numerical value greater than or equal to X
392 gtOrEq: function ( actual
, expected
, message
) {
393 QUnit
.push( actual
>= expected
, actual
, 'greater than or equal to ' + expected
, message
);
397 * Asserts that two HTML strings are structurally equivalent.
399 * @param {string} actualHtml Actual HTML markup.
400 * @param {string} expectedHtml Expected HTML markup
401 * @param {string} message Assertion message.
403 htmlEqual: function ( actualHtml
, expectedHtml
, message
) {
404 var actual
= getHtmlStructure( actualHtml
),
405 expected
= getHtmlStructure( expectedHtml
);
419 * Asserts that two HTML strings are not structurally equivalent.
421 * @param {string} actualHtml Actual HTML markup.
422 * @param {string} expectedHtml Expected HTML markup.
423 * @param {string} message Assertion message.
425 notHtmlEqual: function ( actualHtml
, expectedHtml
, message
) {
426 var actual
= getHtmlStructure( actualHtml
),
427 expected
= getHtmlStructure( expectedHtml
);
441 $.extend( QUnit
.assert
, addons
);
444 * Small test suite to confirm proper functionality of the utilities and
445 * initializations defined above in this file.
447 QUnit
.module( 'test.mediawiki.qunit.testrunner', QUnit
.newMwEnvironment( {
449 this.mwHtmlLive
= mw
.html
;
451 escape: function () {
456 teardown: function () {
457 mw
.html
= this.mwHtmlLive
;
467 QUnit
.test( 'Setup', 3, function ( assert
) {
468 assert
.equal( mw
.html
.escape( 'foo' ), 'mocked', 'setup() callback was ran.' );
469 assert
.equal( mw
.config
.get( 'testVar' ), 'foo', 'config object applied' );
470 assert
.equal( mw
.messages
.get( 'testMsg' ), 'Foo.', 'messages object applied' );
472 mw
.config
.set( 'testVar', 'bar' );
473 mw
.messages
.set( 'testMsg', 'Bar.' );
476 QUnit
.test( 'Teardown', 2, function ( assert
) {
477 assert
.equal( mw
.config
.get( 'testVar' ), 'foo', 'config object restored and re-applied after test()' );
478 assert
.equal( mw
.messages
.get( 'testMsg' ), 'Foo.', 'messages object restored and re-applied after test()' );
481 QUnit
.test( 'Loader status', 2, function ( assert
) {
483 modules
= mw
.loader
.getModuleNames(),
487 for ( i
= 0, len
= modules
.length
; i
< len
; i
++ ) {
488 state
= mw
.loader
.getState( modules
[ i
] );
489 if ( state
=== 'error' ) {
490 error
.push( modules
[ i
] );
491 } else if ( state
=== 'missing' ) {
492 missing
.push( modules
[ i
] );
496 assert
.deepEqual( error
, [], 'Modules in error state' );
497 assert
.deepEqual( missing
, [], 'Modules in missing state' );
500 QUnit
.test( 'htmlEqual', 8, function ( assert
) {
502 '<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>',
503 '<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>',
504 'Attribute order, spacing and quotation marks (equal)'
508 '<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>',
509 '<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>',
510 'Attribute order, spacing and quotation marks (not equal)'
514 '<label for="firstname" accesskey="f" class="important">First</label><input id="firstname" /><label for="lastname" accesskey="l" class="minor">Last</label><input id="lastname" />',
515 '<label for="firstname" accesskey="f" class="important">First</label><input id="firstname" /><label for="lastname" accesskey="l" class="minor">Last</label><input id="lastname" />',
516 'Multiple root nodes (equal)'
520 '<label for="firstname" accesskey="f" class="important">First</label><input id="firstname" /><label for="lastname" accesskey="l" class="minor">Last</label><input id="lastname" />',
521 '<label for="firstname" accesskey="f" class="important">First</label><input id="firstname" /><label for="lastname" accesskey="l" class="important" >Last</label><input id="lastname" />',
522 'Multiple root nodes (not equal, last label node is different)'
526 'fo"o<br/>b>ar',
528 'Extra escaping is equal'
533 'Text escaping (not equal)'
537 'foo<a href="http://example.com">example</a>bar',
538 'foo<a href="http://example.com">example</a>bar',
539 'Outer text nodes are compared (equal)'
543 'foo<a href="http://example.com">example</a>bar',
544 'foo<a href="http://example.com">example</a>quux',
545 'Outer text nodes are compared (last text node different)'
550 QUnit
.module( 'test.mediawiki.qunit.testrunner-after', QUnit
.newMwEnvironment() );
552 QUnit
.test( 'Teardown', 3, function ( assert
) {
553 assert
.equal( mw
.html
.escape( '<' ), '<', 'teardown() callback was ran.' );
554 assert
.equal( mw
.config
.get( 'testVar' ), null, 'config object restored to live in next module()' );
555 assert
.equal( mw
.messages
.get( 'testMsg' ), null, 'messages object restored to live in next module()' );
558 }( jQuery
, mediaWiki
, QUnit
) );