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