1 /*global CompletenessTest, sinon */
3 ( function ( $, mw
, QUnit
) {
6 var mwTestIgnore
, mwTester
,
12 * Add bogus to url to prevent IE crazy caching
14 * @param value {String} a relative path (eg. 'data/foo.js'
15 * or 'data/test.php?foo=bar').
16 * @return {String} Such as 'data/foo.js?131031765087663960'
18 QUnit
.fixurl = function ( value
) {
19 return value
+ (/\?/.test( value
) ? '&' : '?')
20 + String( new Date().getTime() )
21 + String( parseInt( Math
.random() * 100000, 10 ) );
28 // When a test() indicates asynchronicity with stop(),
29 // allow 10 seconds to pass before killing the test(),
30 // and assuming failure.
31 QUnit
.config
.testTimeout
= 10 * 1000;
33 // Add a checkbox to QUnit header to toggle MediaWiki ResourceLoader debug mode.
34 QUnit
.config
.urlConfig
.push( {
36 label
: 'Enable ResourceLoaderDebug',
37 tooltip
: 'Enable debug mode in ResourceLoader'
40 QUnit
.config
.requireExpects
= true;
43 * Load TestSwarm agent
45 // Only if the current url indicates that there is a TestSwarm instance watching us
46 // (TestSwarm appends swarmURL to the test suites url it loads in iframes).
47 // Otherwise this is just a simple view of Special:JavaScriptTest/qunit directly,
48 // no point in loading inject.js in that case. Also, make sure that this instance
49 // of MediaWiki has actually been configured with the required url to that inject.js
50 // script. By default it is false.
51 if ( QUnit
.urlParams
.swarmURL
&& mw
.config
.get( 'QUnitTestSwarmInjectJSPath' ) ) {
52 jQuery
.getScript( QUnit
.fixurl( mw
.config
.get( 'QUnitTestSwarmInjectJSPath' ) ) );
58 * Adds toggle checkbox to header
60 QUnit
.config
.urlConfig
.push( {
61 id
: 'completenesstest',
62 label
: 'Run CompletenessTest',
63 tooltip
: 'Run the completeness test'
69 * Glue code for nicer integration with QUnit setup/teardown
70 * Inspired by http://sinonjs.org/releases/sinon-qunit-1.0.0.js
72 * - Work properly with asynchronous QUnit by using module setup/teardown
73 * instead of synchronously wrapping QUnit.test.
75 sinon
.assert
.fail = function ( msg
) {
76 QUnit
.assert
.ok( false, msg
);
78 sinon
.assert
.pass = function ( msg
) {
79 QUnit
.assert
.ok( true, msg
);
84 properties
: ['spy', 'stub', 'mock', 'sandbox'],
85 // Don't fake timers by default
90 var orgModule
= QUnit
.module
;
92 QUnit
.module = function ( name
, localEnv
) {
93 localEnv
= localEnv
|| {};
96 var config
= sinon
.getConfig( sinon
.config
);
97 config
.injectInto
= this;
98 sinon
.sandbox
.create( config
);
100 if ( localEnv
.setup
) {
101 localEnv
.setup
.call( this );
104 teardown: function () {
105 this.sandbox
.verifyAndRestore();
107 if ( localEnv
.teardown
) {
108 localEnv
.teardown
.call( this );
115 // Initiate when enabled
116 if ( QUnit
.urlParams
.completenesstest
) {
118 // Return true to ignore
119 mwTestIgnore = function ( val
, tester
) {
121 // Don't record methods of the properties of constructors,
122 // to avoid getting into a loop (prototype.constructor.prototype..).
123 // Since we're therefor skipping any injection for
124 // "new mw.Foo()", manually set it to true here.
125 if ( val
instanceof mw
.Map
) {
126 tester
.methodCallTracker
.Map
= true;
129 if ( val
instanceof mw
.Title
) {
130 tester
.methodCallTracker
.Title
= true;
134 // Don't record methods of the properties of a jQuery object
135 if ( val
instanceof $ ) {
139 // Don't iterate over the module registry (the 'script' references would
140 // be listed as untested methods otherwise)
141 if ( val
=== mw
.loader
.moduleRegistry
) {
148 mwTester
= new CompletenessTest( mw
, mwTestIgnore
);
152 * Test environment recommended for all QUnit test modules
154 * Whether to log environment changes to the console
156 QUnit
.config
.urlConfig
.push( 'mwlogenv' );
159 * Reset mw.config and others to a fresh copy of the live config for each test(),
160 * and restore it back to the live one afterwards.
161 * @param localEnv {Object} [optional]
162 * @example (see test suite at the bottom of this file)
165 QUnit
.newMwEnvironment
= ( function () {
166 var warn
, log
, liveConfig
, liveMessages
;
168 liveConfig
= mw
.config
.values
;
169 liveMessages
= mw
.messages
.values
;
171 function suppressWarnings() {
173 mw
.log
.warn
= $.noop
;
176 function restoreWarnings() {
177 if ( warn
!== undefined ) {
183 function freshConfigCopy( custom
) {
185 // Tests should mock all factors that directly influence the tested code.
186 // For backwards compatibility though we set mw.config to a fresh copy of the live
187 // config. This way any modifications made to mw.config during the test will not
188 // affect other tests, nor the global scope outside the test runner.
189 // This is a shallow copy, since overriding an array or object value via "custom"
190 // should replace it. Setting a config property means you override it, not extend it.
191 // NOTE: It is important that we suppress warnings because extend() will also access
192 // deprecated properties and trigger deprecation warnings from mw.log#deprecate.
194 copy
= $.extend( {}, liveConfig
, custom
);
200 function freshMessagesCopy( custom
) {
201 return $.extend( /*deep=*/true, {}, liveMessages
, custom
);
204 log
= QUnit
.urlParams
.mwlogenv
? mw
.log : function () {};
206 return function ( localEnv
) {
207 localEnv
= $.extend( {
218 log( 'MwEnvironment> SETUP for "' + QUnit
.config
.current
.module
219 + ': ' + QUnit
.config
.current
.testName
+ '"' );
221 // Greetings, mock environment!
222 mw
.config
.values
= freshConfigCopy( localEnv
.config
);
223 mw
.messages
.values
= freshMessagesCopy( localEnv
.messages
);
224 this.suppressWarnings
= suppressWarnings
;
225 this.restoreWarnings
= restoreWarnings
;
227 localEnv
.setup
.call( this );
230 teardown: function () {
231 log( 'MwEnvironment> TEARDOWN for "' + QUnit
.config
.current
.module
232 + ': ' + QUnit
.config
.current
.testName
+ '"' );
234 localEnv
.teardown
.call( this );
236 // Farewell, mock environment!
237 mw
.config
.values
= liveConfig
;
238 mw
.messages
.values
= liveMessages
;
240 // As a convenience feature, automatically restore warnings if they're
241 // still suppressed by the end of the test.
244 // Check for incomplete animations/requests/etc and throw
245 // error if there are any.
246 if ( $.timers
&& $.timers
.length
!== 0 ) {
247 // Test may need to use fake timers, wait for animations or
249 throw new Error( 'Unfinished animations: ' + $.timers
.length
);
251 if ( $.active
!== undefined && $.active
!== 0 ) {
252 // Test may need to use fake XHR, wait for requests or
254 throw new Error( 'Unfinished AJAX requests: ' + $.active
);
261 // $.when stops as soon as one fails, which makes sense in most
262 // practical scenarios, but not in a unit test where we really do
263 // need to wait until all of them are finished.
264 QUnit
.whenPromisesComplete = function () {
265 var altPromises
= [];
267 $.each( arguments
, function ( i
, arg
) {
268 var alt
= $.Deferred();
269 altPromises
.push( alt
);
271 // Whether this one fails or not, forwards it to
272 // the 'done' (resolve) callback of the alternative promise.
273 arg
.always( alt
.resolve
);
276 return $.when
.apply( $, altPromises
);
280 * Recursively convert a node to a plain object representing its structure.
281 * Only considers attributes and contents (elements and text nodes).
282 * Attribute values are compared strictly and not normalised.
285 * @return {Object|string} Plain JavaScript value representing the node.
287 function getDomStructure( node
) {
288 var $node
, children
, processedChildren
, i
, len
, el
;
290 if ( node
.nodeType
=== ELEMENT_NODE
) {
291 children
= $node
.contents();
292 processedChildren
= [];
293 for ( i
= 0, len
= children
.length
; i
< len
; i
++ ) {
295 if ( el
.nodeType
=== ELEMENT_NODE
|| el
.nodeType
=== TEXT_NODE
) {
296 processedChildren
.push( getDomStructure( el
) );
301 tagName
: node
.tagName
,
302 attributes
: $node
.getAttrs(),
303 contents
: processedChildren
306 // Should be text node
312 * Gets structure of node for this HTML.
314 * @param {string} html HTML markup for one or more nodes.
316 function getHtmlStructure( html
) {
317 var el
= $( '<div>' ).append( html
)[0];
318 return getDomStructure( el
);
322 * Add-on assertion helpers
324 // Define the add-ons
327 // Expect boolean true
328 assertTrue: function ( actual
, message
) {
329 QUnit
.push( actual
=== true, actual
, true, message
);
332 // Expect boolean false
333 assertFalse: function ( actual
, message
) {
334 QUnit
.push( actual
=== false, actual
, false, message
);
337 // Expect numerical value less than X
338 lt: function ( actual
, expected
, message
) {
339 QUnit
.push( actual
< expected
, actual
, 'less than ' + expected
, message
);
342 // Expect numerical value less than or equal to X
343 ltOrEq: function ( actual
, expected
, message
) {
344 QUnit
.push( actual
<= expected
, actual
, 'less than or equal to ' + expected
, message
);
347 // Expect numerical value greater than X
348 gt: function ( actual
, expected
, message
) {
349 QUnit
.push( actual
> expected
, actual
, 'greater than ' + expected
, message
);
352 // Expect numerical value greater than or equal to X
353 gtOrEq: function ( actual
, expected
, message
) {
354 QUnit
.push( actual
>= expected
, actual
, 'greater than or equal to ' + expected
, message
);
358 * Asserts that two HTML strings are structurally equivalent.
360 * @param {string} actualHtml Actual HTML markup.
361 * @param {string} expectedHtml Expected HTML markup
362 * @param {string} message Assertion message.
364 htmlEqual: function ( actualHtml
, expectedHtml
, message
) {
365 var actual
= getHtmlStructure( actualHtml
),
366 expected
= getHtmlStructure( expectedHtml
);
380 * Asserts that two HTML strings are not structurally equivalent.
382 * @param {string} actualHtml Actual HTML markup.
383 * @param {string} expectedHtml Expected HTML markup.
384 * @param {string} message Assertion message.
386 notHtmlEqual: function ( actualHtml
, expectedHtml
, message
) {
387 var actual
= getHtmlStructure( actualHtml
),
388 expected
= getHtmlStructure( expectedHtml
);
402 $.extend( QUnit
.assert
, addons
);
405 * Small test suite to confirm proper functionality of the utilities and
406 * initializations defined above in this file.
408 QUnit
.module( 'test.mediawiki.qunit.testrunner', QUnit
.newMwEnvironment( {
410 this.mwHtmlLive
= mw
.html
;
412 escape: function () {
417 teardown: function () {
418 mw
.html
= this.mwHtmlLive
;
428 QUnit
.test( 'Setup', 3, function ( assert
) {
429 assert
.equal( mw
.html
.escape( 'foo' ), 'mocked', 'setup() callback was ran.' );
430 assert
.equal( mw
.config
.get( 'testVar' ), 'foo', 'config object applied' );
431 assert
.equal( mw
.messages
.get( 'testMsg' ), 'Foo.', 'messages object applied' );
433 mw
.config
.set( 'testVar', 'bar' );
434 mw
.messages
.set( 'testMsg', 'Bar.' );
437 QUnit
.test( 'Teardown', 2, function ( assert
) {
438 assert
.equal( mw
.config
.get( 'testVar' ), 'foo', 'config object restored and re-applied after test()' );
439 assert
.equal( mw
.messages
.get( 'testMsg' ), 'Foo.', 'messages object restored and re-applied after test()' );
442 QUnit
.test( 'Loader status', 2, function ( assert
) {
444 modules
= mw
.loader
.getModuleNames(),
448 for ( i
= 0, len
= modules
.length
; i
< len
; i
++ ) {
449 state
= mw
.loader
.getState( modules
[i
] );
450 if ( state
=== 'error' ) {
451 error
.push( modules
[i
] );
452 } else if ( state
=== 'missing' ) {
453 missing
.push( modules
[i
] );
457 assert
.deepEqual( error
, [], 'Modules in error state' );
458 assert
.deepEqual( missing
, [], 'Modules in missing state' );
461 QUnit
.test( 'htmlEqual', 8, function ( assert
) {
463 '<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>',
464 '<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>',
465 'Attribute order, spacing and quotation marks (equal)'
469 '<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>',
470 '<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>',
471 'Attribute order, spacing and quotation marks (not equal)'
475 '<label for="firstname" accesskey="f" class="important">First</label><input id="firstname" /><label for="lastname" accesskey="l" class="minor">Last</label><input id="lastname" />',
476 '<label for="firstname" accesskey="f" class="important">First</label><input id="firstname" /><label for="lastname" accesskey="l" class="minor">Last</label><input id="lastname" />',
477 'Multiple root nodes (equal)'
481 '<label for="firstname" accesskey="f" class="important">First</label><input id="firstname" /><label for="lastname" accesskey="l" class="minor">Last</label><input id="lastname" />',
482 '<label for="firstname" accesskey="f" class="important">First</label><input id="firstname" /><label for="lastname" accesskey="l" class="important" >Last</label><input id="lastname" />',
483 'Multiple root nodes (not equal, last label node is different)'
487 'fo"o<br/>b>ar',
489 'Extra escaping is equal'
494 'Text escaping (not equal)'
498 'foo<a href="http://example.com">example</a>bar',
499 'foo<a href="http://example.com">example</a>bar',
500 'Outer text nodes are compared (equal)'
504 'foo<a href="http://example.com">example</a>bar',
505 'foo<a href="http://example.com">example</a>quux',
506 'Outer text nodes are compared (last text node different)'
511 QUnit
.module( 'test.mediawiki.qunit.testrunner-after', QUnit
.newMwEnvironment() );
513 QUnit
.test( 'Teardown', 3, function ( assert
) {
514 assert
.equal( mw
.html
.escape( '<' ), '<', 'teardown() callback was ran.' );
515 assert
.equal( mw
.config
.get( 'testVar' ), null, 'config object restored to live in next module()' );
516 assert
.equal( mw
.messages
.get( 'testMsg' ), null, 'messages object restored to live in next module()' );
519 }( jQuery
, mediaWiki
, QUnit
) );