qunit: Also clear $.timers when stopping unfinished animations
[lhc/web/wiklou.git] / tests / qunit / data / testrunner.js
1 /* global sinon */
2 ( function ( $, mw, QUnit ) {
3 'use strict';
4
5 var addons;
6
7 /**
8 * Add bogus to url to prevent IE crazy caching
9 *
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'
13 */
14 QUnit.fixurl = function ( value ) {
15 return value + ( /\?/.test( value ) ? '&' : '?' )
16 + String( new Date().getTime() )
17 + String( parseInt( Math.random() * 100000, 10 ) );
18 };
19
20 /**
21 * Configuration
22 */
23
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;
27
28 // Reduce default animation duration from 400ms to 0ms for unit tests
29 // eslint-disable-next-line no-underscore-dangle
30 $.fx.speeds._default = 0;
31
32 // Add a checkbox to QUnit header to toggle MediaWiki ResourceLoader debug mode.
33 QUnit.config.urlConfig.push( {
34 id: 'debug',
35 label: 'Enable ResourceLoaderDebug',
36 tooltip: 'Enable debug mode in ResourceLoader',
37 value: 'true'
38 } );
39
40 /**
41 * SinonJS
42 *
43 * Glue code for nicer integration with QUnit setup/teardown
44 * Inspired by http://sinonjs.org/releases/sinon-qunit-1.0.0.js
45 * Fixes:
46 * - Work properly with asynchronous QUnit by using module setup/teardown
47 * instead of synchronously wrapping QUnit.test.
48 */
49 sinon.assert.fail = function ( msg ) {
50 QUnit.assert.ok( false, msg );
51 };
52 sinon.assert.pass = function ( msg ) {
53 QUnit.assert.ok( true, msg );
54 };
55 sinon.config = {
56 injectIntoThis: true,
57 injectInto: null,
58 properties: [ 'spy', 'stub', 'mock', 'sandbox' ],
59 // Don't fake timers by default
60 useFakeTimers: false,
61 useFakeServer: false
62 };
63 ( function () {
64 var orgModule = QUnit.module;
65
66 QUnit.module = function ( name, localEnv ) {
67 localEnv = localEnv || {};
68 orgModule( name, {
69 setup: function () {
70 var config = sinon.getConfig( sinon.config );
71 config.injectInto = this;
72 sinon.sandbox.create( config );
73
74 if ( localEnv.setup ) {
75 localEnv.setup.call( this );
76 }
77 },
78 teardown: function () {
79 if ( localEnv.teardown ) {
80 localEnv.teardown.call( this );
81 }
82
83 this.sandbox.verifyAndRestore();
84 }
85 } );
86 };
87 }() );
88
89 // Extend QUnit.module to provide a fixture element.
90 ( function () {
91 var orgModule = QUnit.module;
92
93 QUnit.module = function ( name, localEnv ) {
94 var fixture;
95 localEnv = localEnv || {};
96 orgModule( name, {
97 setup: function () {
98 fixture = document.createElement( 'div' );
99 fixture.id = 'qunit-fixture';
100 document.body.appendChild( fixture );
101
102 if ( localEnv.setup ) {
103 localEnv.setup.call( this );
104 }
105 },
106 teardown: function () {
107 if ( localEnv.teardown ) {
108 localEnv.teardown.call( this );
109 }
110
111 fixture.parentNode.removeChild( fixture );
112 }
113 } );
114 };
115 }() );
116
117 /**
118 * Reset mw.config and others to a fresh copy of the live config for each test(),
119 * and restore it back to the live one afterwards.
120 *
121 * @param {Object} [localEnv]
122 * @example (see test suite at the bottom of this file)
123 * </code>
124 */
125 QUnit.newMwEnvironment = ( function () {
126 var warn, error, liveConfig, liveMessages,
127 MwMap = mw.config.constructor, // internal use only
128 ajaxRequests = [];
129
130 liveConfig = mw.config;
131 liveMessages = mw.messages;
132
133 function suppressWarnings() {
134 if ( warn === undefined ) {
135 warn = mw.log.warn;
136 error = mw.log.error;
137 mw.log.warn = mw.log.error = $.noop;
138 }
139 }
140
141 function restoreWarnings() {
142 // Guard against calls not balanced with suppressWarnings()
143 if ( warn !== undefined ) {
144 mw.log.warn = warn;
145 mw.log.error = error;
146 warn = error = undefined;
147 }
148 }
149
150 function freshConfigCopy( custom ) {
151 var copy;
152 // Tests should mock all factors that directly influence the tested code.
153 // For backwards compatibility though we set mw.config to a fresh copy of the live
154 // config. This way any modifications made to mw.config during the test will not
155 // affect other tests, nor the global scope outside the test runner.
156 // This is a shallow copy, since overriding an array or object value via "custom"
157 // should replace it. Setting a config property means you override it, not extend it.
158 // NOTE: It is important that we suppress warnings because extend() will also access
159 // deprecated properties and trigger deprecation warnings from mw.log#deprecate.
160 suppressWarnings();
161 copy = $.extend( {}, liveConfig.get(), custom );
162 restoreWarnings();
163
164 return copy;
165 }
166
167 function freshMessagesCopy( custom ) {
168 return $.extend( /* deep */true, {}, liveMessages.get(), custom );
169 }
170
171 /**
172 * @param {jQuery.Event} event
173 * @param {jqXHR} jqXHR
174 * @param {Object} ajaxOptions
175 */
176 function trackAjax( event, jqXHR, ajaxOptions ) {
177 ajaxRequests.push( { xhr: jqXHR, options: ajaxOptions } );
178 }
179
180 return function ( localEnv ) {
181 localEnv = $.extend( {
182 // QUnit
183 setup: $.noop,
184 teardown: $.noop,
185 // MediaWiki
186 config: {},
187 messages: {}
188 }, localEnv );
189
190 return {
191 setup: function () {
192
193 // Greetings, mock environment!
194 mw.config = new MwMap();
195 mw.config.set( freshConfigCopy( localEnv.config ) );
196 mw.messages = new MwMap();
197 mw.messages.set( freshMessagesCopy( localEnv.messages ) );
198 // Update reference to mw.messages
199 mw.jqueryMsg.setParserDefaults( {
200 messages: mw.messages
201 } );
202
203 this.suppressWarnings = suppressWarnings;
204 this.restoreWarnings = restoreWarnings;
205
206 // Start tracking ajax requests
207 $( document ).on( 'ajaxSend', trackAjax );
208
209 localEnv.setup.call( this );
210 },
211
212 teardown: function () {
213 var timers, pending, $activeLen;
214
215 localEnv.teardown.call( this );
216
217 // Stop tracking ajax requests
218 $( document ).off( 'ajaxSend', trackAjax );
219
220 // As a convenience feature, automatically restore warnings if they're
221 // still suppressed by the end of the test.
222 restoreWarnings();
223
224 // Farewell, mock environment!
225 mw.config = liveConfig;
226 mw.messages = liveMessages;
227 // Restore reference to mw.messages
228 mw.jqueryMsg.setParserDefaults( {
229 messages: liveMessages
230 } );
231
232 // Tests should use fake timers or wait for animations to complete
233 // Check for incomplete animations/requests/etc and throw if there are any.
234 if ( $.timers && $.timers.length !== 0 ) {
235 timers = $.timers.length;
236 $.each( $.timers, function ( i, timer ) {
237 var node = timer.elem;
238 mw.log.warn( 'Unfinished animation #' + i + ' in ' + timer.queue + ' queue on ' +
239 mw.html.element( node.nodeName.toLowerCase(), $( node ).getAttrs() )
240 );
241 } );
242 // Force animations to stop to give the next test a clean start
243 $.timers = [];
244 $.fx.stop();
245
246 throw new Error( 'Unfinished animations: ' + timers );
247 }
248
249 // Test should use fake XHR, wait for requests, or call abort()
250 $activeLen = $.active;
251 if ( $activeLen !== undefined && $activeLen !== 0 ) {
252 pending = $.grep( ajaxRequests, function ( ajax ) {
253 return ajax.xhr.state() === 'pending';
254 } );
255 if ( pending.length !== $activeLen ) {
256 mw.log.warn( 'Pending requests does not match jQuery.active count' );
257 }
258 // Force requests to stop to give the next test a clean start
259 $.each( ajaxRequests, function ( i, ajax ) {
260 mw.log.warn(
261 'AJAX request #' + i + ' (state: ' + ajax.xhr.state() + ')',
262 ajax.options
263 );
264 ajax.xhr.abort();
265 } );
266 ajaxRequests = [];
267
268 throw new Error( 'Pending AJAX requests: ' + pending.length + ' (active: ' + $activeLen + ')' );
269 }
270 }
271 };
272 };
273 }() );
274
275 // $.when stops as soon as one fails, which makes sense in most
276 // practical scenarios, but not in a unit test where we really do
277 // need to wait until all of them are finished.
278 QUnit.whenPromisesComplete = function () {
279 var altPromises = [];
280
281 $.each( arguments, function ( i, arg ) {
282 var alt = $.Deferred();
283 altPromises.push( alt );
284
285 // Whether this one fails or not, forwards it to
286 // the 'done' (resolve) callback of the alternative promise.
287 arg.always( alt.resolve );
288 } );
289
290 return $.when.apply( $, altPromises );
291 };
292
293 /**
294 * Recursively convert a node to a plain object representing its structure.
295 * Only considers attributes and contents (elements and text nodes).
296 * Attribute values are compared strictly and not normalised.
297 *
298 * @param {Node} node
299 * @return {Object|string} Plain JavaScript value representing the node.
300 */
301 function getDomStructure( node ) {
302 var $node, children, processedChildren, i, len, el;
303 $node = $( node );
304 if ( node.nodeType === Node.ELEMENT_NODE ) {
305 children = $node.contents();
306 processedChildren = [];
307 for ( i = 0, len = children.length; i < len; i++ ) {
308 el = children[ i ];
309 if ( el.nodeType === Node.ELEMENT_NODE || el.nodeType === Node.TEXT_NODE ) {
310 processedChildren.push( getDomStructure( el ) );
311 }
312 }
313
314 return {
315 tagName: node.tagName,
316 attributes: $node.getAttrs(),
317 contents: processedChildren
318 };
319 } else {
320 // Should be text node
321 return $node.text();
322 }
323 }
324
325 /**
326 * Gets structure of node for this HTML.
327 *
328 * @param {string} html HTML markup for one or more nodes.
329 */
330 function getHtmlStructure( html ) {
331 var el = $( '<div>' ).append( html )[ 0 ];
332 return getDomStructure( el );
333 }
334
335 /**
336 * Add-on assertion helpers
337 */
338 // Define the add-ons
339 addons = {
340
341 // Expect boolean true
342 assertTrue: function ( actual, message ) {
343 QUnit.push( actual === true, actual, true, message );
344 },
345
346 // Expect boolean false
347 assertFalse: function ( actual, message ) {
348 QUnit.push( actual === false, actual, false, message );
349 },
350
351 // Expect numerical value less than X
352 lt: function ( actual, expected, message ) {
353 QUnit.push( actual < expected, actual, 'less than ' + expected, message );
354 },
355
356 // Expect numerical value less than or equal to X
357 ltOrEq: function ( actual, expected, message ) {
358 QUnit.push( actual <= expected, actual, 'less than or equal to ' + expected, message );
359 },
360
361 // Expect numerical value greater than X
362 gt: function ( actual, expected, message ) {
363 QUnit.push( actual > expected, actual, 'greater than ' + expected, message );
364 },
365
366 // Expect numerical value greater than or equal to X
367 gtOrEq: function ( actual, expected, message ) {
368 QUnit.push( actual >= expected, actual, 'greater than or equal to ' + expected, message );
369 },
370
371 /**
372 * Asserts that two HTML strings are structurally equivalent.
373 *
374 * @param {string} actualHtml Actual HTML markup.
375 * @param {string} expectedHtml Expected HTML markup
376 * @param {string} message Assertion message.
377 */
378 htmlEqual: function ( actualHtml, expectedHtml, message ) {
379 var actual = getHtmlStructure( actualHtml ),
380 expected = getHtmlStructure( expectedHtml );
381
382 QUnit.push(
383 QUnit.equiv(
384 actual,
385 expected
386 ),
387 actual,
388 expected,
389 message
390 );
391 },
392
393 /**
394 * Asserts that two HTML strings are not structurally equivalent.
395 *
396 * @param {string} actualHtml Actual HTML markup.
397 * @param {string} expectedHtml Expected HTML markup.
398 * @param {string} message Assertion message.
399 */
400 notHtmlEqual: function ( actualHtml, expectedHtml, message ) {
401 var actual = getHtmlStructure( actualHtml ),
402 expected = getHtmlStructure( expectedHtml );
403
404 QUnit.push(
405 !QUnit.equiv(
406 actual,
407 expected
408 ),
409 actual,
410 expected,
411 message
412 );
413 }
414 };
415
416 $.extend( QUnit.assert, addons );
417
418 /**
419 * Small test suite to confirm proper functionality of the utilities and
420 * initializations defined above in this file.
421 */
422 QUnit.module( 'test.mediawiki.qunit.testrunner', QUnit.newMwEnvironment( {
423 setup: function () {
424 this.mwHtmlLive = mw.html;
425 mw.html = {
426 escape: function () {
427 return 'mocked';
428 }
429 };
430 },
431 teardown: function () {
432 mw.html = this.mwHtmlLive;
433 },
434 config: {
435 testVar: 'foo'
436 },
437 messages: {
438 testMsg: 'Foo.'
439 }
440 } ) );
441
442 QUnit.test( 'Setup', function ( assert ) {
443 assert.equal( mw.html.escape( 'foo' ), 'mocked', 'setup() callback was ran.' );
444 assert.equal( mw.config.get( 'testVar' ), 'foo', 'config object applied' );
445 assert.equal( mw.messages.get( 'testMsg' ), 'Foo.', 'messages object applied' );
446
447 mw.config.set( 'testVar', 'bar' );
448 mw.messages.set( 'testMsg', 'Bar.' );
449 } );
450
451 QUnit.test( 'Teardown', function ( assert ) {
452 assert.equal( mw.config.get( 'testVar' ), 'foo', 'config object restored and re-applied after test()' );
453 assert.equal( mw.messages.get( 'testMsg' ), 'Foo.', 'messages object restored and re-applied after test()' );
454 } );
455
456 QUnit.test( 'Loader status', function ( assert ) {
457 var i, len, state,
458 modules = mw.loader.getModuleNames(),
459 error = [],
460 missing = [];
461
462 for ( i = 0, len = modules.length; i < len; i++ ) {
463 state = mw.loader.getState( modules[ i ] );
464 if ( state === 'error' ) {
465 error.push( modules[ i ] );
466 } else if ( state === 'missing' ) {
467 missing.push( modules[ i ] );
468 }
469 }
470
471 assert.deepEqual( error, [], 'Modules in error state' );
472 assert.deepEqual( missing, [], 'Modules in missing state' );
473 } );
474
475 QUnit.test( 'htmlEqual', function ( assert ) {
476 assert.htmlEqual(
477 '<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>',
478 '<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>',
479 'Attribute order, spacing and quotation marks (equal)'
480 );
481
482 assert.notHtmlEqual(
483 '<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>',
484 '<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>',
485 'Attribute order, spacing and quotation marks (not equal)'
486 );
487
488 assert.htmlEqual(
489 '<label for="firstname" accesskey="f" class="important">First</label><input id="firstname" /><label for="lastname" accesskey="l" class="minor">Last</label><input id="lastname" />',
490 '<label for="firstname" accesskey="f" class="important">First</label><input id="firstname" /><label for="lastname" accesskey="l" class="minor">Last</label><input id="lastname" />',
491 'Multiple root nodes (equal)'
492 );
493
494 assert.notHtmlEqual(
495 '<label for="firstname" accesskey="f" class="important">First</label><input id="firstname" /><label for="lastname" accesskey="l" class="minor">Last</label><input id="lastname" />',
496 '<label for="firstname" accesskey="f" class="important">First</label><input id="firstname" /><label for="lastname" accesskey="l" class="important" >Last</label><input id="lastname" />',
497 'Multiple root nodes (not equal, last label node is different)'
498 );
499
500 assert.htmlEqual(
501 'fo&quot;o<br/>b&gt;ar',
502 'fo"o<br/>b>ar',
503 'Extra escaping is equal'
504 );
505 assert.notHtmlEqual(
506 'foo&lt;br/&gt;bar',
507 'foo<br/>bar',
508 'Text escaping (not equal)'
509 );
510
511 assert.htmlEqual(
512 'foo<a href="http://example.com">example</a>bar',
513 'foo<a href="http://example.com">example</a>bar',
514 'Outer text nodes are compared (equal)'
515 );
516
517 assert.notHtmlEqual(
518 'foo<a href="http://example.com">example</a>bar',
519 'foo<a href="http://example.com">example</a>quux',
520 'Outer text nodes are compared (last text node different)'
521 );
522
523 } );
524
525 QUnit.module( 'test.mediawiki.qunit.testrunner-after', QUnit.newMwEnvironment() );
526
527 QUnit.test( 'Teardown', function ( assert ) {
528 assert.equal( mw.html.escape( '<' ), '&lt;', 'teardown() callback was ran.' );
529 assert.equal( mw.config.get( 'testVar' ), null, 'config object restored to live in next module()' );
530 assert.equal( mw.messages.get( 'testMsg' ), null, 'messages object restored to live in next module()' );
531 } );
532
533 }( jQuery, mediaWiki, QUnit ) );