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 30 seconds to pass before killing the test(),
30 // and assuming failure.
31 QUnit
.config
.testTimeout
= 30 * 1000;
33 QUnit
.config
.requireExpects
= true;
35 // Add a checkbox to QUnit header to toggle MediaWiki ResourceLoader debug mode.
36 QUnit
.config
.urlConfig
.push( {
38 label
: 'Enable ResourceLoaderDebug',
39 tooltip
: 'Enable debug mode in ResourceLoader'
45 * Adds toggle checkbox to header
47 QUnit
.config
.urlConfig
.push( {
48 id
: 'completenesstest',
49 label
: 'Run CompletenessTest',
50 tooltip
: 'Run the completeness test'
56 * Glue code for nicer integration with QUnit setup/teardown
57 * Inspired by http://sinonjs.org/releases/sinon-qunit-1.0.0.js
59 * - Work properly with asynchronous QUnit by using module setup/teardown
60 * instead of synchronously wrapping QUnit.test.
62 sinon
.assert
.fail = function ( msg
) {
63 QUnit
.assert
.ok( false, msg
);
65 sinon
.assert
.pass = function ( msg
) {
66 QUnit
.assert
.ok( true, msg
);
71 properties
: ['spy', 'stub', 'mock', 'sandbox'],
72 // Don't fake timers by default
77 var orgModule
= QUnit
.module
;
79 QUnit
.module = function ( name
, localEnv
) {
80 localEnv
= localEnv
|| {};
83 var config
= sinon
.getConfig( sinon
.config
);
84 config
.injectInto
= this;
85 sinon
.sandbox
.create( config
);
87 if ( localEnv
.setup
) {
88 localEnv
.setup
.call( this );
91 teardown: function () {
92 this.sandbox
.verifyAndRestore();
94 if ( localEnv
.teardown
) {
95 localEnv
.teardown
.call( this );
102 // Initiate when enabled
103 if ( QUnit
.urlParams
.completenesstest
) {
105 // Return true to ignore
106 mwTestIgnore = function ( val
, tester
) {
108 // Don't record methods of the properties of constructors,
109 // to avoid getting into a loop (prototype.constructor.prototype..).
110 // Since we're therefor skipping any injection for
111 // "new mw.Foo()", manually set it to true here.
112 if ( val
instanceof mw
.Map
) {
113 tester
.methodCallTracker
.Map
= true;
116 if ( val
instanceof mw
.Title
) {
117 tester
.methodCallTracker
.Title
= true;
121 // Don't record methods of the properties of a jQuery object
122 if ( val
instanceof $ ) {
126 // Don't iterate over the module registry (the 'script' references would
127 // be listed as untested methods otherwise)
128 if ( val
=== mw
.loader
.moduleRegistry
) {
135 mwTester
= new CompletenessTest( mw
, mwTestIgnore
);
139 * Test environment recommended for all QUnit test modules
141 * Whether to log environment changes to the console
143 QUnit
.config
.urlConfig
.push( 'mwlogenv' );
146 * Reset mw.config and others to a fresh copy of the live config for each test(),
147 * and restore it back to the live one afterwards.
148 * @param localEnv {Object} [optional]
149 * @example (see test suite at the bottom of this file)
152 QUnit
.newMwEnvironment
= ( function () {
153 var warn
, log
, liveConfig
, liveMessages
;
155 liveConfig
= mw
.config
.values
;
156 liveMessages
= mw
.messages
.values
;
158 function suppressWarnings() {
160 mw
.log
.warn
= $.noop
;
163 function restoreWarnings() {
164 if ( warn
!== undefined ) {
170 function freshConfigCopy( custom
) {
172 // Tests should mock all factors that directly influence the tested code.
173 // For backwards compatibility though we set mw.config to a fresh copy of the live
174 // config. This way any modifications made to mw.config during the test will not
175 // affect other tests, nor the global scope outside the test runner.
176 // This is a shallow copy, since overriding an array or object value via "custom"
177 // should replace it. Setting a config property means you override it, not extend it.
178 // NOTE: It is important that we suppress warnings because extend() will also access
179 // deprecated properties and trigger deprecation warnings from mw.log#deprecate.
181 copy
= $.extend( {}, liveConfig
, custom
);
187 function freshMessagesCopy( custom
) {
188 return $.extend( /*deep=*/true, {}, liveMessages
, custom
);
191 log
= QUnit
.urlParams
.mwlogenv
? mw
.log : function () {};
193 return function ( localEnv
) {
194 localEnv
= $.extend( {
205 log( 'MwEnvironment> SETUP for "' + QUnit
.config
.current
.module
206 + ': ' + QUnit
.config
.current
.testName
+ '"' );
208 // Greetings, mock environment!
209 mw
.config
.values
= freshConfigCopy( localEnv
.config
);
210 mw
.messages
.values
= freshMessagesCopy( localEnv
.messages
);
211 this.suppressWarnings
= suppressWarnings
;
212 this.restoreWarnings
= restoreWarnings
;
214 localEnv
.setup
.call( this );
217 teardown: function () {
219 log( 'MwEnvironment> TEARDOWN for "' + QUnit
.config
.current
.module
220 + ': ' + QUnit
.config
.current
.testName
+ '"' );
222 localEnv
.teardown
.call( this );
224 // Farewell, mock environment!
225 mw
.config
.values
= liveConfig
;
226 mw
.messages
.values
= liveMessages
;
228 // As a convenience feature, automatically restore warnings if they're
229 // still suppressed by the end of the test.
232 // Check for incomplete animations/requests/etc and throw
233 // error if there are any.
234 if ( $.timers
&& $.timers
.length
!== 0 ) {
235 timers
= $.timers
.length
;
236 // Tests shoulld use fake timers or wait for animations to complete
237 $.each( $.timers
, function ( i
, timer
) {
238 var node
= timer
.elem
;
239 mw
.log
.warn( 'Unfinished animation #' + i
+ ' in ' + timer
.queue
+ ' queue on ' +
240 mw
.html
.element( node
.nodeName
.toLowerCase(), $(node
).getAttrs() )
243 // Force animations to stop to give the next test a clean start
246 throw new Error( 'Unfinished animations: ' + timers
);
248 if ( $.active
!== undefined && $.active
!== 0 ) {
249 // Test may need to use fake XHR, wait for requests or
251 throw new Error( 'Unfinished AJAX requests: ' + $.active
);
258 // $.when stops as soon as one fails, which makes sense in most
259 // practical scenarios, but not in a unit test where we really do
260 // need to wait until all of them are finished.
261 QUnit
.whenPromisesComplete = function () {
262 var altPromises
= [];
264 $.each( arguments
, function ( i
, arg
) {
265 var alt
= $.Deferred();
266 altPromises
.push( alt
);
268 // Whether this one fails or not, forwards it to
269 // the 'done' (resolve) callback of the alternative promise.
270 arg
.always( alt
.resolve
);
273 return $.when
.apply( $, altPromises
);
277 * Recursively convert a node to a plain object representing its structure.
278 * Only considers attributes and contents (elements and text nodes).
279 * Attribute values are compared strictly and not normalised.
282 * @return {Object|string} Plain JavaScript value representing the node.
284 function getDomStructure( node
) {
285 var $node
, children
, processedChildren
, i
, len
, el
;
287 if ( node
.nodeType
=== ELEMENT_NODE
) {
288 children
= $node
.contents();
289 processedChildren
= [];
290 for ( i
= 0, len
= children
.length
; i
< len
; i
++ ) {
292 if ( el
.nodeType
=== ELEMENT_NODE
|| el
.nodeType
=== TEXT_NODE
) {
293 processedChildren
.push( getDomStructure( el
) );
298 tagName
: node
.tagName
,
299 attributes
: $node
.getAttrs(),
300 contents
: processedChildren
303 // Should be text node
309 * Gets structure of node for this HTML.
311 * @param {string} html HTML markup for one or more nodes.
313 function getHtmlStructure( html
) {
314 var el
= $( '<div>' ).append( html
)[0];
315 return getDomStructure( el
);
319 * Add-on assertion helpers
321 // Define the add-ons
324 // Expect boolean true
325 assertTrue: function ( actual
, message
) {
326 QUnit
.push( actual
=== true, actual
, true, message
);
329 // Expect boolean false
330 assertFalse: function ( actual
, message
) {
331 QUnit
.push( actual
=== false, actual
, false, message
);
334 // Expect numerical value less than X
335 lt: function ( actual
, expected
, message
) {
336 QUnit
.push( actual
< expected
, actual
, 'less than ' + expected
, message
);
339 // Expect numerical value less than or equal to X
340 ltOrEq: function ( actual
, expected
, message
) {
341 QUnit
.push( actual
<= expected
, actual
, 'less than or equal to ' + expected
, message
);
344 // Expect numerical value greater than X
345 gt: function ( actual
, expected
, message
) {
346 QUnit
.push( actual
> expected
, actual
, 'greater than ' + expected
, message
);
349 // Expect numerical value greater than or equal to X
350 gtOrEq: function ( actual
, expected
, message
) {
351 QUnit
.push( actual
>= expected
, actual
, 'greater than or equal to ' + expected
, message
);
355 * Asserts that two HTML strings are structurally equivalent.
357 * @param {string} actualHtml Actual HTML markup.
358 * @param {string} expectedHtml Expected HTML markup
359 * @param {string} message Assertion message.
361 htmlEqual: function ( actualHtml
, expectedHtml
, message
) {
362 var actual
= getHtmlStructure( actualHtml
),
363 expected
= getHtmlStructure( expectedHtml
);
377 * Asserts that two HTML strings are not structurally equivalent.
379 * @param {string} actualHtml Actual HTML markup.
380 * @param {string} expectedHtml Expected HTML markup.
381 * @param {string} message Assertion message.
383 notHtmlEqual: function ( actualHtml
, expectedHtml
, message
) {
384 var actual
= getHtmlStructure( actualHtml
),
385 expected
= getHtmlStructure( expectedHtml
);
399 $.extend( QUnit
.assert
, addons
);
402 * Small test suite to confirm proper functionality of the utilities and
403 * initializations defined above in this file.
405 QUnit
.module( 'test.mediawiki.qunit.testrunner', QUnit
.newMwEnvironment( {
407 this.mwHtmlLive
= mw
.html
;
409 escape: function () {
414 teardown: function () {
415 mw
.html
= this.mwHtmlLive
;
425 QUnit
.test( 'Setup', 3, function ( assert
) {
426 assert
.equal( mw
.html
.escape( 'foo' ), 'mocked', 'setup() callback was ran.' );
427 assert
.equal( mw
.config
.get( 'testVar' ), 'foo', 'config object applied' );
428 assert
.equal( mw
.messages
.get( 'testMsg' ), 'Foo.', 'messages object applied' );
430 mw
.config
.set( 'testVar', 'bar' );
431 mw
.messages
.set( 'testMsg', 'Bar.' );
434 QUnit
.test( 'Teardown', 2, function ( assert
) {
435 assert
.equal( mw
.config
.get( 'testVar' ), 'foo', 'config object restored and re-applied after test()' );
436 assert
.equal( mw
.messages
.get( 'testMsg' ), 'Foo.', 'messages object restored and re-applied after test()' );
439 QUnit
.test( 'Loader status', 2, function ( assert
) {
441 modules
= mw
.loader
.getModuleNames(),
445 for ( i
= 0, len
= modules
.length
; i
< len
; i
++ ) {
446 state
= mw
.loader
.getState( modules
[i
] );
447 if ( state
=== 'error' ) {
448 error
.push( modules
[i
] );
449 } else if ( state
=== 'missing' ) {
450 missing
.push( modules
[i
] );
454 assert
.deepEqual( error
, [], 'Modules in error state' );
455 assert
.deepEqual( missing
, [], 'Modules in missing state' );
458 QUnit
.test( 'htmlEqual', 8, function ( assert
) {
460 '<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>',
461 '<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>',
462 'Attribute order, spacing and quotation marks (equal)'
466 '<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>',
467 '<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>',
468 'Attribute order, spacing and quotation marks (not equal)'
472 '<label for="firstname" accesskey="f" class="important">First</label><input id="firstname" /><label for="lastname" accesskey="l" class="minor">Last</label><input id="lastname" />',
473 '<label for="firstname" accesskey="f" class="important">First</label><input id="firstname" /><label for="lastname" accesskey="l" class="minor">Last</label><input id="lastname" />',
474 'Multiple root nodes (equal)'
478 '<label for="firstname" accesskey="f" class="important">First</label><input id="firstname" /><label for="lastname" accesskey="l" class="minor">Last</label><input id="lastname" />',
479 '<label for="firstname" accesskey="f" class="important">First</label><input id="firstname" /><label for="lastname" accesskey="l" class="important" >Last</label><input id="lastname" />',
480 'Multiple root nodes (not equal, last label node is different)'
484 'fo"o<br/>b>ar',
486 'Extra escaping is equal'
491 'Text escaping (not equal)'
495 'foo<a href="http://example.com">example</a>bar',
496 'foo<a href="http://example.com">example</a>bar',
497 'Outer text nodes are compared (equal)'
501 'foo<a href="http://example.com">example</a>bar',
502 'foo<a href="http://example.com">example</a>quux',
503 'Outer text nodes are compared (last text node different)'
508 QUnit
.module( 'test.mediawiki.qunit.testrunner-after', QUnit
.newMwEnvironment() );
510 QUnit
.test( 'Teardown', 3, function ( assert
) {
511 assert
.equal( mw
.html
.escape( '<' ), '<', 'teardown() callback was ran.' );
512 assert
.equal( mw
.config
.get( 'testVar' ), null, 'config object restored to live in next module()' );
513 assert
.equal( mw
.messages
.get( 'testMsg' ), null, 'messages object restored to live in next module()' );
516 }( jQuery
, mediaWiki
, QUnit
) );