78771decd0d84501584f54a20a306b92331bd9fd
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 value {String} 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.
167 * @param localEnv {Object} [optional]
168 * @example (see test suite at the bottom of this file)
171 QUnit
.newMwEnvironment
= ( function () {
172 var warn
, error
, liveConfig
, liveMessages
,
175 liveConfig
= mw
.config
.values
;
176 liveMessages
= mw
.messages
.values
;
178 function suppressWarnings() {
180 error
= mw
.log
.error
;
181 mw
.log
.warn
= mw
.log
.error
= $.noop
;
184 function restoreWarnings() {
185 // Guard against calls not balanced with suppressWarnings()
186 if ( warn
!== undefined ) {
188 mw
.log
.error
= error
;
189 warn
= error
= undefined;
193 function freshConfigCopy( custom
) {
195 // Tests should mock all factors that directly influence the tested code.
196 // For backwards compatibility though we set mw.config to a fresh copy of the live
197 // config. This way any modifications made to mw.config during the test will not
198 // affect other tests, nor the global scope outside the test runner.
199 // This is a shallow copy, since overriding an array or object value via "custom"
200 // should replace it. Setting a config property means you override it, not extend it.
201 // NOTE: It is important that we suppress warnings because extend() will also access
202 // deprecated properties and trigger deprecation warnings from mw.log#deprecate.
204 copy
= $.extend( {}, liveConfig
, custom
);
210 function freshMessagesCopy( custom
) {
211 return $.extend( /*deep=*/true, {}, liveMessages
, custom
);
215 * @param {jQuery.Event} event
216 * @param {jqXHR} jqXHR
217 * @param {Object} ajaxOptions
219 function trackAjax( event
, jqXHR
, ajaxOptions
) {
220 ajaxRequests
.push( { xhr
: jqXHR
, options
: ajaxOptions
} );
223 return function ( localEnv
) {
224 localEnv
= $.extend( {
236 // Greetings, mock environment!
237 mw
.config
.values
= freshConfigCopy( localEnv
.config
);
238 mw
.messages
.values
= freshMessagesCopy( localEnv
.messages
);
239 this.suppressWarnings
= suppressWarnings
;
240 this.restoreWarnings
= restoreWarnings
;
242 // Start tracking ajax requests
243 $( document
).on( 'ajaxSend', trackAjax
);
245 localEnv
.setup
.call( this );
248 teardown: function () {
249 var timers
, pending
, $activeLen
;
251 localEnv
.teardown
.call( this );
253 // Stop tracking ajax requests
254 $( document
).off( 'ajaxSend', trackAjax
);
256 // Farewell, mock environment!
257 mw
.config
.values
= liveConfig
;
258 mw
.messages
.values
= liveMessages
;
260 // As a convenience feature, automatically restore warnings if they're
261 // still suppressed by the end of the test.
264 // Tests should use fake timers or wait for animations to complete
265 // Check for incomplete animations/requests/etc and throw if there are any.
266 if ( $.timers
&& $.timers
.length
!== 0 ) {
267 timers
= $.timers
.length
;
268 $.each( $.timers
, function ( i
, timer
) {
269 var node
= timer
.elem
;
270 mw
.log
.warn( 'Unfinished animation #' + i
+ ' in ' + timer
.queue
+ ' queue on ' +
271 mw
.html
.element( node
.nodeName
.toLowerCase(), $(node
).getAttrs() )
274 // Force animations to stop to give the next test a clean start
277 throw new Error( 'Unfinished animations: ' + timers
);
280 // Test should use fake XHR, wait for requests, or call abort()
281 $activeLen
= $.active
;
282 if ( $activeLen
!== undefined && $activeLen
!== 0 ) {
283 pending
= $.grep( ajaxRequests
, function ( ajax
) {
284 return ajax
.xhr
.state() === 'pending';
286 if ( pending
.length
!== $activeLen
) {
287 mw
.log
.warn( 'Pending requests does not match jQuery.active count' );
289 // Force requests to stop to give the next test a clean start
290 $.each( pending
, function ( i
, ajax
) {
291 mw
.log
.warn( 'Pending AJAX request #' + i
, ajax
.options
);
296 throw new Error( 'Pending AJAX requests: ' + pending
.length
+ ' (active: ' + $activeLen
+ ')' );
303 // $.when stops as soon as one fails, which makes sense in most
304 // practical scenarios, but not in a unit test where we really do
305 // need to wait until all of them are finished.
306 QUnit
.whenPromisesComplete = function () {
307 var altPromises
= [];
309 $.each( arguments
, function ( i
, arg
) {
310 var alt
= $.Deferred();
311 altPromises
.push( alt
);
313 // Whether this one fails or not, forwards it to
314 // the 'done' (resolve) callback of the alternative promise.
315 arg
.always( alt
.resolve
);
318 return $.when
.apply( $, altPromises
);
322 * Recursively convert a node to a plain object representing its structure.
323 * Only considers attributes and contents (elements and text nodes).
324 * Attribute values are compared strictly and not normalised.
327 * @return {Object|string} Plain JavaScript value representing the node.
329 function getDomStructure( node
) {
330 var $node
, children
, processedChildren
, i
, len
, el
;
332 if ( node
.nodeType
=== Node
.ELEMENT_NODE
) {
333 children
= $node
.contents();
334 processedChildren
= [];
335 for ( i
= 0, len
= children
.length
; i
< len
; i
++ ) {
337 if ( el
.nodeType
=== Node
.ELEMENT_NODE
|| el
.nodeType
=== Node
.TEXT_NODE
) {
338 processedChildren
.push( getDomStructure( el
) );
343 tagName
: node
.tagName
,
344 attributes
: $node
.getAttrs(),
345 contents
: processedChildren
348 // Should be text node
354 * Gets structure of node for this HTML.
356 * @param {string} html HTML markup for one or more nodes.
358 function getHtmlStructure( html
) {
359 var el
= $( '<div>' ).append( html
)[0];
360 return getDomStructure( el
);
364 * Add-on assertion helpers
366 // Define the add-ons
369 // Expect boolean true
370 assertTrue: function ( actual
, message
) {
371 QUnit
.push( actual
=== true, actual
, true, message
);
374 // Expect boolean false
375 assertFalse: function ( actual
, message
) {
376 QUnit
.push( actual
=== false, actual
, false, message
);
379 // Expect numerical value less than X
380 lt: function ( actual
, expected
, message
) {
381 QUnit
.push( actual
< expected
, actual
, 'less than ' + expected
, message
);
384 // Expect numerical value less than or equal to X
385 ltOrEq: function ( actual
, expected
, message
) {
386 QUnit
.push( actual
<= expected
, actual
, 'less than or equal to ' + expected
, message
);
389 // Expect numerical value greater than X
390 gt: function ( actual
, expected
, message
) {
391 QUnit
.push( actual
> expected
, actual
, 'greater than ' + expected
, message
);
394 // Expect numerical value greater than or equal to X
395 gtOrEq: function ( actual
, expected
, message
) {
396 QUnit
.push( actual
>= expected
, actual
, 'greater than or equal to ' + expected
, message
);
400 * Asserts that two HTML strings are structurally equivalent.
402 * @param {string} actualHtml Actual HTML markup.
403 * @param {string} expectedHtml Expected HTML markup
404 * @param {string} message Assertion message.
406 htmlEqual: function ( actualHtml
, expectedHtml
, message
) {
407 var actual
= getHtmlStructure( actualHtml
),
408 expected
= getHtmlStructure( expectedHtml
);
422 * Asserts that two HTML strings are not structurally equivalent.
424 * @param {string} actualHtml Actual HTML markup.
425 * @param {string} expectedHtml Expected HTML markup.
426 * @param {string} message Assertion message.
428 notHtmlEqual: function ( actualHtml
, expectedHtml
, message
) {
429 var actual
= getHtmlStructure( actualHtml
),
430 expected
= getHtmlStructure( expectedHtml
);
444 $.extend( QUnit
.assert
, addons
);
447 * Small test suite to confirm proper functionality of the utilities and
448 * initializations defined above in this file.
450 QUnit
.module( 'test.mediawiki.qunit.testrunner', QUnit
.newMwEnvironment( {
452 this.mwHtmlLive
= mw
.html
;
454 escape: function () {
459 teardown: function () {
460 mw
.html
= this.mwHtmlLive
;
470 QUnit
.test( 'Setup', 3, function ( assert
) {
471 assert
.equal( mw
.html
.escape( 'foo' ), 'mocked', 'setup() callback was ran.' );
472 assert
.equal( mw
.config
.get( 'testVar' ), 'foo', 'config object applied' );
473 assert
.equal( mw
.messages
.get( 'testMsg' ), 'Foo.', 'messages object applied' );
475 mw
.config
.set( 'testVar', 'bar' );
476 mw
.messages
.set( 'testMsg', 'Bar.' );
479 QUnit
.test( 'Teardown', 2, function ( assert
) {
480 assert
.equal( mw
.config
.get( 'testVar' ), 'foo', 'config object restored and re-applied after test()' );
481 assert
.equal( mw
.messages
.get( 'testMsg' ), 'Foo.', 'messages object restored and re-applied after test()' );
484 QUnit
.test( 'Loader status', 2, function ( assert
) {
486 modules
= mw
.loader
.getModuleNames(),
490 for ( i
= 0, len
= modules
.length
; i
< len
; i
++ ) {
491 state
= mw
.loader
.getState( modules
[i
] );
492 if ( state
=== 'error' ) {
493 error
.push( modules
[i
] );
494 } else if ( state
=== 'missing' ) {
495 missing
.push( modules
[i
] );
499 assert
.deepEqual( error
, [], 'Modules in error state' );
500 assert
.deepEqual( missing
, [], 'Modules in missing state' );
503 QUnit
.test( 'htmlEqual', 8, function ( assert
) {
505 '<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>',
506 '<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>',
507 'Attribute order, spacing and quotation marks (equal)'
511 '<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>',
512 '<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>',
513 'Attribute order, spacing and quotation marks (not equal)'
517 '<label for="firstname" accesskey="f" class="important">First</label><input id="firstname" /><label for="lastname" accesskey="l" class="minor">Last</label><input id="lastname" />',
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 'Multiple root nodes (equal)'
523 '<label for="firstname" accesskey="f" class="important">First</label><input id="firstname" /><label for="lastname" accesskey="l" class="minor">Last</label><input id="lastname" />',
524 '<label for="firstname" accesskey="f" class="important">First</label><input id="firstname" /><label for="lastname" accesskey="l" class="important" >Last</label><input id="lastname" />',
525 'Multiple root nodes (not equal, last label node is different)'
529 'fo"o<br/>b>ar',
531 'Extra escaping is equal'
536 'Text escaping (not equal)'
540 'foo<a href="http://example.com">example</a>bar',
541 'foo<a href="http://example.com">example</a>bar',
542 'Outer text nodes are compared (equal)'
546 'foo<a href="http://example.com">example</a>bar',
547 'foo<a href="http://example.com">example</a>quux',
548 'Outer text nodes are compared (last text node different)'
553 QUnit
.module( 'test.mediawiki.qunit.testrunner-after', QUnit
.newMwEnvironment() );
555 QUnit
.test( 'Teardown', 3, function ( assert
) {
556 assert
.equal( mw
.html
.escape( '<' ), '<', 'teardown() callback was ran.' );
557 assert
.equal( mw
.config
.get( 'testVar' ), null, 'config object restored to live in next module()' );
558 assert
.equal( mw
.messages
.get( 'testMsg' ), null, 'messages object restored to live in next module()' );
561 }( jQuery
, mediaWiki
, QUnit
) );