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