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 {string} value 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.
168 * @param {Object} [localEnv]
169 * @example (see test suite at the bottom of this file)
172 QUnit.newMwEnvironment = ( function () {
173 var warn, error, liveConfig, liveMessages,
176 liveConfig = mw.config.values;
177 liveMessages = mw.messages.values;
179 function suppressWarnings() {
181 error = mw.log.error;
182 mw.log.warn = mw.log.error = $.noop;
185 function restoreWarnings() {
186 // Guard against calls not balanced with suppressWarnings()
187 if ( warn !== undefined ) {
189 mw.log.error = error;
190 warn = error = undefined;
194 function freshConfigCopy( custom ) {
196 // Tests should mock all factors that directly influence the tested code.
197 // For backwards compatibility though we set mw.config to a fresh copy of the live
198 // config. This way any modifications made to mw.config during the test will not
199 // affect other tests, nor the global scope outside the test runner.
200 // This is a shallow copy, since overriding an array or object value via "custom"
201 // should replace it. Setting a config property means you override it, not extend it.
202 // NOTE: It is important that we suppress warnings because extend() will also access
203 // deprecated properties and trigger deprecation warnings from mw.log#deprecate.
205 copy = $.extend( {}, liveConfig, custom );
211 function freshMessagesCopy( custom ) {
212 return $.extend( /*deep=*/true, {}, liveMessages, custom );
216 * @param {jQuery.Event} event
217 * @param {jqXHR} jqXHR
218 * @param {Object} ajaxOptions
220 function trackAjax( event, jqXHR, ajaxOptions ) {
221 ajaxRequests.push( { xhr: jqXHR, options: ajaxOptions } );
224 return function ( localEnv ) {
225 localEnv = $.extend( {
237 // Greetings, mock environment!
238 mw.config.values = freshConfigCopy( localEnv.config );
239 mw.messages.values = freshMessagesCopy( localEnv.messages );
240 this.suppressWarnings = suppressWarnings;
241 this.restoreWarnings = restoreWarnings;
243 // Start tracking ajax requests
244 $( document ).on( 'ajaxSend', trackAjax );
246 localEnv.setup.call( this );
249 teardown: function () {
250 var timers, pending, $activeLen;
252 localEnv.teardown.call( this );
254 // Stop tracking ajax requests
255 $( document ).off( 'ajaxSend', trackAjax );
257 // Farewell, mock environment!
258 mw.config.values = liveConfig;
259 mw.messages.values = liveMessages;
261 // As a convenience feature, automatically restore warnings if they're
262 // still suppressed by the end of the test.
265 // Tests should use fake timers or wait for animations to complete
266 // Check for incomplete animations/requests/etc and throw if there are any.
267 if ( $.timers && $.timers.length !== 0 ) {
268 timers = $.timers.length;
269 $.each( $.timers, function ( i, timer ) {
270 var node = timer.elem;
271 mw.log.warn( 'Unfinished animation #' + i + ' in ' + timer.queue + ' queue on ' +
272 mw.html.element( node.nodeName.toLowerCase(), $( node ).getAttrs() )
275 // Force animations to stop to give the next test a clean start
278 throw new Error( 'Unfinished animations: ' + timers );
281 // Test should use fake XHR, wait for requests, or call abort()
282 $activeLen = $.active;
283 if ( $activeLen !== undefined && $activeLen !== 0 ) {
284 pending = $.grep( ajaxRequests, function ( ajax ) {
285 return ajax.xhr.state() === 'pending';
287 if ( pending.length !== $activeLen ) {
288 mw.log.warn( 'Pending requests does not match jQuery.active count' );
290 // Force requests to stop to give the next test a clean start
291 $.each( pending, function ( i, ajax ) {
292 mw.log.warn( 'Pending AJAX request #' + i, ajax.options );
297 throw new Error( 'Pending AJAX requests: ' + pending.length + ' (active: ' + $activeLen + ')' );
304 // $.when stops as soon as one fails, which makes sense in most
305 // practical scenarios, but not in a unit test where we really do
306 // need to wait until all of them are finished.
307 QUnit.whenPromisesComplete = function () {
308 var altPromises = [];
310 $.each( arguments, function ( i, arg ) {
311 var alt = $.Deferred();
312 altPromises.push( alt );
314 // Whether this one fails or not, forwards it to
315 // the 'done' (resolve) callback of the alternative promise.
316 arg.always( alt.resolve );
319 return $.when.apply( $, altPromises );
323 * Recursively convert a node to a plain object representing its structure.
324 * Only considers attributes and contents (elements and text nodes).
325 * Attribute values are compared strictly and not normalised.
328 * @return {Object|string} Plain JavaScript value representing the node.
330 function getDomStructure( node ) {
331 var $node, children, processedChildren, i, len, el;
333 if ( node.nodeType === Node.ELEMENT_NODE ) {
334 children = $node.contents();
335 processedChildren = [];
336 for ( i = 0, len = children.length; i < len; i++ ) {
338 if ( el.nodeType === Node.ELEMENT_NODE || el.nodeType === Node.TEXT_NODE ) {
339 processedChildren.push( getDomStructure( el ) );
344 tagName: node.tagName,
345 attributes: $node.getAttrs(),
346 contents: processedChildren
349 // Should be text node
355 * Gets structure of node for this HTML.
357 * @param {string} html HTML markup for one or more nodes.
359 function getHtmlStructure( html ) {
360 var el = $( '<div>' ).append( html )[ 0 ];
361 return getDomStructure( el );
365 * Add-on assertion helpers
367 // Define the add-ons
370 // Expect boolean true
371 assertTrue: function ( actual, message ) {
372 QUnit.push( actual === true, actual, true, message );
375 // Expect boolean false
376 assertFalse: function ( actual, message ) {
377 QUnit.push( actual === false, actual, false, message );
380 // Expect numerical value less than X
381 lt: function ( actual, expected, message ) {
382 QUnit.push( actual < expected, actual, 'less than ' + expected, message );
385 // Expect numerical value less than or equal to X
386 ltOrEq: function ( actual, expected, message ) {
387 QUnit.push( actual <= expected, actual, 'less than or equal to ' + expected, message );
390 // Expect numerical value greater than X
391 gt: function ( actual, expected, message ) {
392 QUnit.push( actual > expected, actual, 'greater than ' + expected, message );
395 // Expect numerical value greater than or equal to X
396 gtOrEq: function ( actual, expected, message ) {
397 QUnit.push( actual >= expected, actual, 'greater than or equal to ' + expected, message );
401 * Asserts that two HTML strings are structurally equivalent.
403 * @param {string} actualHtml Actual HTML markup.
404 * @param {string} expectedHtml Expected HTML markup
405 * @param {string} message Assertion message.
407 htmlEqual: function ( actualHtml, expectedHtml, message ) {
408 var actual = getHtmlStructure( actualHtml ),
409 expected = getHtmlStructure( expectedHtml );
423 * Asserts that two HTML strings are not structurally equivalent.
425 * @param {string} actualHtml Actual HTML markup.
426 * @param {string} expectedHtml Expected HTML markup.
427 * @param {string} message Assertion message.
429 notHtmlEqual: function ( actualHtml, expectedHtml, message ) {
430 var actual = getHtmlStructure( actualHtml ),
431 expected = getHtmlStructure( expectedHtml );
445 $.extend( QUnit.assert, addons );
448 * Small test suite to confirm proper functionality of the utilities and
449 * initializations defined above in this file.
451 QUnit.module( 'test.mediawiki.qunit.testrunner', QUnit.newMwEnvironment( {
453 this.mwHtmlLive = mw.html;
455 escape: function () {
460 teardown: function () {
461 mw.html = this.mwHtmlLive;
471 QUnit.test( 'Setup', 3, function ( assert ) {
472 assert.equal( mw.html.escape( 'foo' ), 'mocked', 'setup() callback was ran.' );
473 assert.equal( mw.config.get( 'testVar' ), 'foo', 'config object applied' );
474 assert.equal( mw.messages.get( 'testMsg' ), 'Foo.', 'messages object applied' );
476 mw.config.set( 'testVar', 'bar' );
477 mw.messages.set( 'testMsg', 'Bar.' );
480 QUnit.test( 'Teardown', 2, function ( assert ) {
481 assert.equal( mw.config.get( 'testVar' ), 'foo', 'config object restored and re-applied after test()' );
482 assert.equal( mw.messages.get( 'testMsg' ), 'Foo.', 'messages object restored and re-applied after test()' );
485 QUnit.test( 'Loader status', 2, function ( assert ) {
487 modules = mw.loader.getModuleNames(),
491 for ( i = 0, len = modules.length; i < len; i++ ) {
492 state = mw.loader.getState( modules[ i ] );
493 if ( state === 'error' ) {
494 error.push( modules[ i ] );
495 } else if ( state === 'missing' ) {
496 missing.push( modules[ i ] );
500 assert.deepEqual( error, [], 'Modules in error state' );
501 assert.deepEqual( missing, [], 'Modules in missing state' );
504 QUnit.test( 'htmlEqual', 8, function ( assert ) {
506 '<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>',
507 '<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>',
508 'Attribute order, spacing and quotation marks (equal)'
512 '<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>',
513 '<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>',
514 'Attribute order, spacing and quotation marks (not equal)'
518 '<label for="firstname" accesskey="f" class="important">First</label><input id="firstname" /><label for="lastname" accesskey="l" class="minor">Last</label><input id="lastname" />',
519 '<label for="firstname" accesskey="f" class="important">First</label><input id="firstname" /><label for="lastname" accesskey="l" class="minor">Last</label><input id="lastname" />',
520 'Multiple root nodes (equal)'
524 '<label for="firstname" accesskey="f" class="important">First</label><input id="firstname" /><label for="lastname" accesskey="l" class="minor">Last</label><input id="lastname" />',
525 '<label for="firstname" accesskey="f" class="important">First</label><input id="firstname" /><label for="lastname" accesskey="l" class="important" >Last</label><input id="lastname" />',
526 'Multiple root nodes (not equal, last label node is different)'
530 'fo"o<br/>b>ar',
532 'Extra escaping is equal'
537 'Text escaping (not equal)'
541 'foo<a href="http://example.com">example</a>bar',
542 'foo<a href="http://example.com">example</a>bar',
543 'Outer text nodes are compared (equal)'
547 'foo<a href="http://example.com">example</a>bar',
548 'foo<a href="http://example.com">example</a>quux',
549 'Outer text nodes are compared (last text node different)'
554 QUnit.module( 'test.mediawiki.qunit.testrunner-after', QUnit.newMwEnvironment() );
556 QUnit.test( 'Teardown', 3, function ( assert ) {
557 assert.equal( mw.html.escape( '<' ), '<', 'teardown() callback was ran.' );
558 assert.equal( mw.config.get( 'testVar' ), null, 'config object restored to live in next module()' );
559 assert.equal( mw.messages.get( 'testMsg' ), null, 'messages object restored to live in next module()' );
562 }( jQuery, mediaWiki, QUnit ) );