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 // Reduce default animation duration from 400ms to 0ms for unit tests
29 $.fx.speeds._default = 0;
31 // Add a checkbox to QUnit header to toggle MediaWiki ResourceLoader debug mode.
32 QUnit.config.urlConfig.push( {
34 label: 'Enable ResourceLoaderDebug',
35 tooltip: 'Enable debug mode in ResourceLoader',
42 * Adds toggle checkbox to header
44 QUnit.config.urlConfig.push( {
45 id: 'completenesstest',
46 label: 'Run CompletenessTest',
47 tooltip: 'Run the completeness test'
53 * Glue code for nicer integration with QUnit setup/teardown
54 * Inspired by http://sinonjs.org/releases/sinon-qunit-1.0.0.js
56 * - Work properly with asynchronous QUnit by using module setup/teardown
57 * instead of synchronously wrapping QUnit.test.
59 sinon.assert.fail = function ( msg ) {
60 QUnit.assert.ok( false, msg );
62 sinon.assert.pass = function ( msg ) {
63 QUnit.assert.ok( true, msg );
68 properties: [ 'spy', 'stub', 'mock', 'sandbox' ],
69 // Don't fake timers by default
74 var orgModule = QUnit.module;
76 QUnit.module = function ( name, localEnv ) {
77 localEnv = localEnv || {};
80 var config = sinon.getConfig( sinon.config );
81 config.injectInto = this;
82 sinon.sandbox.create( config );
84 if ( localEnv.setup ) {
85 localEnv.setup.call( this );
88 teardown: function () {
89 if ( localEnv.teardown ) {
90 localEnv.teardown.call( this );
93 this.sandbox.verifyAndRestore();
99 // Extend QUnit.module to provide a fixture element.
101 var orgModule = QUnit.module;
103 QUnit.module = function ( name, localEnv ) {
105 localEnv = localEnv || {};
108 fixture = document.createElement( 'div' );
109 fixture.id = 'qunit-fixture';
110 document.body.appendChild( fixture );
112 if ( localEnv.setup ) {
113 localEnv.setup.call( this );
116 teardown: function () {
117 if ( localEnv.teardown ) {
118 localEnv.teardown.call( this );
121 fixture.parentNode.removeChild( fixture );
127 // Initiate when enabled
128 if ( QUnit.urlParams.completenesstest ) {
130 // Return true to ignore
131 mwTestIgnore = function ( val, tester ) {
133 // Don't record methods of the properties of constructors,
134 // to avoid getting into a loop (prototype.constructor.prototype..).
135 // Since we're therefor skipping any injection for
136 // "new mw.Foo()", manually set it to true here.
137 if ( val instanceof mw.Map ) {
138 tester.methodCallTracker.Map = true;
141 if ( val instanceof mw.Title ) {
142 tester.methodCallTracker.Title = true;
146 // Don't record methods of the properties of a jQuery object
147 if ( val instanceof $ ) {
151 // Don't iterate over the module registry (the 'script' references would
152 // be listed as untested methods otherwise)
153 if ( val === mw.loader.moduleRegistry ) {
160 mwTester = new CompletenessTest( mw, mwTestIgnore );
164 * Reset mw.config and others to a fresh copy of the live config for each test(),
165 * and restore it back to the live one afterwards.
167 * @param {Object} [localEnv]
168 * @example (see test suite at the bottom of this file)
171 QUnit.newMwEnvironment = ( function () {
172 var warn, error, liveConfig, liveMessages,
173 MwMap = mw.config.constructor, // internal use only
176 liveConfig = mw.config;
177 liveMessages = mw.messages;
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.get(), custom );
211 function freshMessagesCopy( custom ) {
212 return $.extend( /*deep=*/true, {}, liveMessages.get(), 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 = new MwMap();
239 mw.config.set( freshConfigCopy( localEnv.config ) );
240 mw.messages = new MwMap();
241 mw.messages.set( freshMessagesCopy( localEnv.messages ) );
242 // Update reference to mw.messages
243 mw.jqueryMsg.setParserDefaults( {
244 messages: mw.messages
247 this.suppressWarnings = suppressWarnings;
248 this.restoreWarnings = restoreWarnings;
250 // Start tracking ajax requests
251 $( document ).on( 'ajaxSend', trackAjax );
253 localEnv.setup.call( this );
256 teardown: function () {
257 var timers, pending, $activeLen;
259 localEnv.teardown.call( this );
261 // Stop tracking ajax requests
262 $( document ).off( 'ajaxSend', trackAjax );
264 // Farewell, mock environment!
265 mw.config = liveConfig;
266 mw.messages = liveMessages;
267 // Restore reference to mw.messages
268 mw.jqueryMsg.setParserDefaults( {
269 messages: liveMessages
272 // As a convenience feature, automatically restore warnings if they're
273 // still suppressed by the end of the test.
276 // Tests should use fake timers or wait for animations to complete
277 // Check for incomplete animations/requests/etc and throw if there are any.
278 if ( $.timers && $.timers.length !== 0 ) {
279 timers = $.timers.length;
280 $.each( $.timers, function ( i, timer ) {
281 var node = timer.elem;
282 mw.log.warn( 'Unfinished animation #' + i + ' in ' + timer.queue + ' queue on ' +
283 mw.html.element( node.nodeName.toLowerCase(), $( node ).getAttrs() )
286 // Force animations to stop to give the next test a clean start
289 throw new Error( 'Unfinished animations: ' + timers );
292 // Test should use fake XHR, wait for requests, or call abort()
293 $activeLen = $.active;
294 if ( $activeLen !== undefined && $activeLen !== 0 ) {
295 pending = $.grep( ajaxRequests, function ( ajax ) {
296 return ajax.xhr.state() === 'pending';
298 if ( pending.length !== $activeLen ) {
299 mw.log.warn( 'Pending requests does not match jQuery.active count' );
301 // Force requests to stop to give the next test a clean start
302 $.each( pending, function ( i, ajax ) {
303 mw.log.warn( 'Pending AJAX request #' + i, ajax.options );
308 throw new Error( 'Pending AJAX requests: ' + pending.length + ' (active: ' + $activeLen + ')' );
315 // $.when stops as soon as one fails, which makes sense in most
316 // practical scenarios, but not in a unit test where we really do
317 // need to wait until all of them are finished.
318 QUnit.whenPromisesComplete = function () {
319 var altPromises = [];
321 $.each( arguments, function ( i, arg ) {
322 var alt = $.Deferred();
323 altPromises.push( alt );
325 // Whether this one fails or not, forwards it to
326 // the 'done' (resolve) callback of the alternative promise.
327 arg.always( alt.resolve );
330 return $.when.apply( $, altPromises );
334 * Recursively convert a node to a plain object representing its structure.
335 * Only considers attributes and contents (elements and text nodes).
336 * Attribute values are compared strictly and not normalised.
339 * @return {Object|string} Plain JavaScript value representing the node.
341 function getDomStructure( node ) {
342 var $node, children, processedChildren, i, len, el;
344 if ( node.nodeType === Node.ELEMENT_NODE ) {
345 children = $node.contents();
346 processedChildren = [];
347 for ( i = 0, len = children.length; i < len; i++ ) {
349 if ( el.nodeType === Node.ELEMENT_NODE || el.nodeType === Node.TEXT_NODE ) {
350 processedChildren.push( getDomStructure( el ) );
355 tagName: node.tagName,
356 attributes: $node.getAttrs(),
357 contents: processedChildren
360 // Should be text node
366 * Gets structure of node for this HTML.
368 * @param {string} html HTML markup for one or more nodes.
370 function getHtmlStructure( html ) {
371 var el = $( '<div>' ).append( html )[ 0 ];
372 return getDomStructure( el );
376 * Add-on assertion helpers
378 // Define the add-ons
381 // Expect boolean true
382 assertTrue: function ( actual, message ) {
383 QUnit.push( actual === true, actual, true, message );
386 // Expect boolean false
387 assertFalse: function ( actual, message ) {
388 QUnit.push( actual === false, actual, false, message );
391 // Expect numerical value less than X
392 lt: function ( actual, expected, message ) {
393 QUnit.push( actual < expected, actual, 'less than ' + expected, message );
396 // Expect numerical value less than or equal to X
397 ltOrEq: function ( actual, expected, message ) {
398 QUnit.push( actual <= expected, actual, 'less than or equal to ' + expected, message );
401 // Expect numerical value greater than X
402 gt: function ( actual, expected, message ) {
403 QUnit.push( actual > expected, actual, 'greater than ' + expected, message );
406 // Expect numerical value greater than or equal to X
407 gtOrEq: function ( actual, expected, message ) {
408 QUnit.push( actual >= expected, actual, 'greater than or equal to ' + expected, message );
412 * Asserts that two HTML strings are structurally equivalent.
414 * @param {string} actualHtml Actual HTML markup.
415 * @param {string} expectedHtml Expected HTML markup
416 * @param {string} message Assertion message.
418 htmlEqual: function ( actualHtml, expectedHtml, message ) {
419 var actual = getHtmlStructure( actualHtml ),
420 expected = getHtmlStructure( expectedHtml );
434 * Asserts that two HTML strings are not structurally equivalent.
436 * @param {string} actualHtml Actual HTML markup.
437 * @param {string} expectedHtml Expected HTML markup.
438 * @param {string} message Assertion message.
440 notHtmlEqual: function ( actualHtml, expectedHtml, message ) {
441 var actual = getHtmlStructure( actualHtml ),
442 expected = getHtmlStructure( expectedHtml );
456 $.extend( QUnit.assert, addons );
459 * Small test suite to confirm proper functionality of the utilities and
460 * initializations defined above in this file.
462 QUnit.module( 'test.mediawiki.qunit.testrunner', QUnit.newMwEnvironment( {
464 this.mwHtmlLive = mw.html;
466 escape: function () {
471 teardown: function () {
472 mw.html = this.mwHtmlLive;
482 QUnit.test( 'Setup', 3, function ( assert ) {
483 assert.equal( mw.html.escape( 'foo' ), 'mocked', 'setup() callback was ran.' );
484 assert.equal( mw.config.get( 'testVar' ), 'foo', 'config object applied' );
485 assert.equal( mw.messages.get( 'testMsg' ), 'Foo.', 'messages object applied' );
487 mw.config.set( 'testVar', 'bar' );
488 mw.messages.set( 'testMsg', 'Bar.' );
491 QUnit.test( 'Teardown', 2, function ( assert ) {
492 assert.equal( mw.config.get( 'testVar' ), 'foo', 'config object restored and re-applied after test()' );
493 assert.equal( mw.messages.get( 'testMsg' ), 'Foo.', 'messages object restored and re-applied after test()' );
496 QUnit.test( 'Loader status', 2, function ( assert ) {
498 modules = mw.loader.getModuleNames(),
502 for ( i = 0, len = modules.length; i < len; i++ ) {
503 state = mw.loader.getState( modules[ i ] );
504 if ( state === 'error' ) {
505 error.push( modules[ i ] );
506 } else if ( state === 'missing' ) {
507 missing.push( modules[ i ] );
511 assert.deepEqual( error, [], 'Modules in error state' );
512 assert.deepEqual( missing, [], 'Modules in missing state' );
515 QUnit.test( 'htmlEqual', 8, function ( assert ) {
517 '<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>',
518 '<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>',
519 'Attribute order, spacing and quotation marks (equal)'
523 '<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>',
524 '<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>',
525 'Attribute order, spacing and quotation marks (not equal)'
529 '<label for="firstname" accesskey="f" class="important">First</label><input id="firstname" /><label for="lastname" accesskey="l" class="minor">Last</label><input id="lastname" />',
530 '<label for="firstname" accesskey="f" class="important">First</label><input id="firstname" /><label for="lastname" accesskey="l" class="minor">Last</label><input id="lastname" />',
531 'Multiple root nodes (equal)'
535 '<label for="firstname" accesskey="f" class="important">First</label><input id="firstname" /><label for="lastname" accesskey="l" class="minor">Last</label><input id="lastname" />',
536 '<label for="firstname" accesskey="f" class="important">First</label><input id="firstname" /><label for="lastname" accesskey="l" class="important" >Last</label><input id="lastname" />',
537 'Multiple root nodes (not equal, last label node is different)'
541 'fo"o<br/>b>ar',
543 'Extra escaping is equal'
548 'Text escaping (not equal)'
552 'foo<a href="http://example.com">example</a>bar',
553 'foo<a href="http://example.com">example</a>bar',
554 'Outer text nodes are compared (equal)'
558 'foo<a href="http://example.com">example</a>bar',
559 'foo<a href="http://example.com">example</a>quux',
560 'Outer text nodes are compared (last text node different)'
565 QUnit.module( 'test.mediawiki.qunit.testrunner-after', QUnit.newMwEnvironment() );
567 QUnit.test( 'Teardown', 3, function ( assert ) {
568 assert.equal( mw.html.escape( '<' ), '<', 'teardown() callback was ran.' );
569 assert.equal( mw.config.get( 'testVar' ), null, 'config object restored to live in next module()' );
570 assert.equal( mw.messages.get( 'testMsg' ), null, 'messages object restored to live in next module()' );
573 }( jQuery, mediaWiki, QUnit ) );