resourceloader: Avoid global window.mwTestFooJsCounter in unit tests
[lhc/web/wiklou.git] / tests / qunit / suites / resources / mediawiki / mediawiki.loader.test.js
1 ( function () {
2 QUnit.module( 'mediawiki.loader', QUnit.newMwEnvironment( {
3 setup: function ( assert ) {
4 // Expose for load.mock.php
5 mw.loader.testFail = function ( reason ) {
6 assert.ok( false, reason );
7 };
8
9 this.useStubClock = function () {
10 this.clock = this.sandbox.useFakeTimers();
11 this.tick = function ( forward ) {
12 return this.clock.tick( forward || 1 );
13 };
14 this.sandbox.stub( mw, 'requestIdleCallback', mw.requestIdleCallbackInternal );
15 };
16 },
17 teardown: function () {
18 mw.loader.maxQueryLength = 2000;
19 // Teardown for StringSet shim test
20 if ( this.nativeSet ) {
21 window.Set = this.nativeSet;
22 mw.redefineFallbacksForTest();
23 }
24 // Remove any remaining temporary statics
25 // exposed for cross-file mocks.
26 delete mw.loader.testCallback;
27 delete mw.loader.testFail;
28 delete mw.getScriptExampleScriptLoaded;
29 }
30 } ) );
31
32 mw.loader.addSource( {
33 testloader:
34 QUnit.fixurl( mw.config.get( 'wgScriptPath' ) + '/tests/qunit/data/load.mock.php' )
35 } );
36
37 /**
38 * The sync style load test, for @import. This is, in a way, also an open bug for
39 * ResourceLoader ("execute js after styles are loaded"), but browsers don't offer a
40 * way to get a callback from when a stylesheet is loaded (that is, including any
41 * `@import` rules inside). To work around this, we'll have a little time loop to check
42 * if the styles apply.
43 *
44 * Note: This test originally used new Image() and onerror to get a callback
45 * when the url is loaded, but that is fragile since it doesn't monitor the
46 * same request as the css @import, and Safari 4 has issues with
47 * onerror/onload not being fired at all in weird cases like this.
48 */
49 function assertStyleAsync( assert, $element, prop, val, fn ) {
50 var styleTestStart,
51 el = $element.get( 0 ),
52 styleTestTimeout = ( QUnit.config.testTimeout || 5000 ) - 200;
53
54 function isCssImportApplied() {
55 // Trigger reflow, repaint, redraw, whatever (cross-browser)
56 $element.css( 'height' );
57 // eslint-disable-next-line no-unused-expressions
58 el.innerHTML;
59 // eslint-disable-next-line no-self-assign
60 el.className = el.className;
61 // eslint-disable-next-line no-unused-expressions
62 document.documentElement.clientHeight;
63
64 return $element.css( prop ) === val;
65 }
66
67 function styleTestLoop() {
68 var styleTestSince = new Date().getTime() - styleTestStart;
69 // If it is passing or if we timed out, run the real test and stop the loop
70 if ( isCssImportApplied() || styleTestSince > styleTestTimeout ) {
71 assert.strictEqual( $element.css( prop ), val,
72 'style "' + prop + ': ' + val + '" from url is applied (after ' + styleTestSince + 'ms)'
73 );
74
75 if ( fn ) {
76 fn();
77 }
78
79 return;
80 }
81 // Otherwise, keep polling
82 setTimeout( styleTestLoop );
83 }
84
85 // Start the loop
86 styleTestStart = new Date().getTime();
87 styleTestLoop();
88 }
89
90 function urlStyleTest( selector, prop, val ) {
91 return QUnit.fixurl(
92 mw.config.get( 'wgScriptPath' ) +
93 '/tests/qunit/data/styleTest.css.php?' +
94 $.param( {
95 selector: selector,
96 prop: prop,
97 val: val
98 } )
99 );
100 }
101
102 QUnit.test( '.using( .., Function callback ) Promise', function ( assert ) {
103 var script = 0, callback = 0;
104 mw.loader.testCallback = function () {
105 script++;
106 };
107 mw.loader.implement( 'test.promise', [ QUnit.fixurl( mw.config.get( 'wgScriptPath' ) + '/tests/qunit/data/mwLoaderTestCallback.js' ) ] );
108
109 return mw.loader.using( 'test.promise', function () {
110 callback++;
111 } ).then( function () {
112 assert.strictEqual( script, 1, 'module script ran' );
113 assert.strictEqual( callback, 1, 'using() callback ran' );
114 } );
115 } );
116
117 QUnit.test( 'Prototype method as module name', function ( assert ) {
118 var call = 0;
119 mw.loader.testCallback = function () {
120 call++;
121 };
122 mw.loader.implement( 'hasOwnProperty', [ QUnit.fixurl( mw.config.get( 'wgScriptPath' ) + '/tests/qunit/data/mwLoaderTestCallback.js' ) ], {}, {} );
123
124 return mw.loader.using( 'hasOwnProperty', function () {
125 assert.strictEqual( call, 1, 'module script ran' );
126 } );
127 } );
128
129 // Covers mw.loader#sortDependencies (with native Set if available)
130 QUnit.test( '.using() - Error: Circular dependency [StringSet default]', function ( assert ) {
131 var done = assert.async();
132
133 mw.loader.register( [
134 [ 'test.set.circleA', '0', [ 'test.set.circleB' ] ],
135 [ 'test.set.circleB', '0', [ 'test.set.circleC' ] ],
136 [ 'test.set.circleC', '0', [ 'test.set.circleA' ] ]
137 ] );
138 mw.loader.using( 'test.set.circleC' ).then(
139 function done() {
140 assert.ok( false, 'Unexpected resolution, expected error.' );
141 },
142 function fail( e ) {
143 assert.ok( /Circular/.test( String( e ) ), 'Detect circular dependency' );
144 }
145 )
146 .always( done );
147 } );
148
149 // @covers mw.loader#sortDependencies (with fallback shim)
150 QUnit.test( '.using() - Error: Circular dependency [StringSet shim]', function ( assert ) {
151 var done = assert.async();
152
153 if ( !window.Set ) {
154 assert.expect( 0 );
155 done();
156 return;
157 }
158
159 this.nativeSet = window.Set;
160 window.Set = undefined;
161 mw.redefineFallbacksForTest();
162
163 mw.loader.register( [
164 [ 'test.shim.circleA', '0', [ 'test.shim.circleB' ] ],
165 [ 'test.shim.circleB', '0', [ 'test.shim.circleC' ] ],
166 [ 'test.shim.circleC', '0', [ 'test.shim.circleA' ] ]
167 ] );
168 mw.loader.using( 'test.shim.circleC' ).then(
169 function done() {
170 assert.ok( false, 'Unexpected resolution, expected error.' );
171 },
172 function fail( e ) {
173 assert.ok( /Circular/.test( String( e ) ), 'Detect circular dependency' );
174 }
175 )
176 .always( done );
177 } );
178
179 QUnit.test( '.load() - Error: Circular dependency', function ( assert ) {
180 var capture = [];
181 mw.loader.register( [
182 [ 'test.load.circleA', '0', [ 'test.load.circleB' ] ],
183 [ 'test.load.circleB', '0', [ 'test.load.circleC' ] ],
184 [ 'test.load.circleC', '0', [ 'test.load.circleA' ] ]
185 ] );
186 this.sandbox.stub( mw, 'track', function ( topic, data ) {
187 capture.push( {
188 topic: topic,
189 error: data.exception && data.exception.message,
190 source: data.source
191 } );
192 } );
193
194 mw.loader.load( 'test.load.circleC' );
195 assert.deepEqual(
196 [ {
197 topic: 'resourceloader.exception',
198 error: 'Circular reference detected: test.load.circleB -> test.load.circleC',
199 source: 'resolve'
200 } ],
201 capture,
202 'Detect circular dependency'
203 );
204 } );
205
206 QUnit.test( '.load() - Error: Circular dependency (direct)', function ( assert ) {
207 var capture = [];
208 mw.loader.register( [
209 [ 'test.load.circleDirect', '0', [ 'test.load.circleDirect' ] ]
210 ] );
211 this.sandbox.stub( mw, 'track', function ( topic, data ) {
212 capture.push( {
213 topic: topic,
214 error: data.exception && data.exception.message,
215 source: data.source
216 } );
217 } );
218
219 mw.loader.load( 'test.load.circleDirect' );
220 assert.deepEqual(
221 [ {
222 topic: 'resourceloader.exception',
223 error: 'Circular reference detected: test.load.circleDirect -> test.load.circleDirect',
224 source: 'resolve'
225 } ],
226 capture,
227 'Detect a direct self-dependency'
228 );
229 } );
230
231 QUnit.test( '.using() - Error: Unregistered', function ( assert ) {
232 var done = assert.async();
233
234 mw.loader.using( 'test.using.unreg' ).then(
235 function done() {
236 assert.ok( false, 'Unexpected resolution, expected error.' );
237 },
238 function fail( e ) {
239 assert.ok( /Unknown/.test( String( e ) ), 'Detect unknown dependency' );
240 }
241 ).always( done );
242 } );
243
244 QUnit.test( '.load() - Error: Unregistered', function ( assert ) {
245 var capture = [];
246 this.sandbox.stub( mw, 'track', function ( topic, data ) {
247 capture.push( {
248 topic: topic,
249 error: data.exception && data.exception.message,
250 source: data.source
251 } );
252 } );
253
254 mw.loader.load( 'test.load.unreg' );
255 assert.deepEqual(
256 [ {
257 topic: 'resourceloader.exception',
258 error: 'Unknown module: test.load.unreg',
259 source: 'resolve'
260 } ],
261 capture
262 );
263 } );
264
265 // Regression test for T36853
266 QUnit.test( '.load() - Error: Missing dependency', function ( assert ) {
267 var capture = [];
268 this.sandbox.stub( mw, 'track', function ( topic, data ) {
269 capture.push( {
270 topic: topic,
271 error: data.exception && data.exception.message,
272 source: data.source
273 } );
274 } );
275
276 mw.loader.register( [
277 [ 'test.load.missingdep1', '0', [ 'test.load.missingdep2' ] ],
278 [ 'test.load.missingdep', '0', [ 'test.load.missingdep1' ] ]
279 ] );
280 mw.loader.load( 'test.load.missingdep' );
281 assert.deepEqual(
282 [ {
283 topic: 'resourceloader.exception',
284 error: 'Unknown module: test.load.missingdep2',
285 source: 'resolve'
286 } ],
287 capture
288 );
289 } );
290
291 QUnit.test( '.implement( styles={ "css": [text, ..] } )', function ( assert ) {
292 var $element = $( '<div class="mw-test-implement-a"></div>' ).appendTo( '#qunit-fixture' );
293
294 assert.notEqual(
295 $element.css( 'float' ),
296 'right',
297 'style is clear'
298 );
299
300 mw.loader.implement(
301 'test.implement.a',
302 function () {
303 assert.strictEqual(
304 $element.css( 'float' ),
305 'right',
306 'style is applied'
307 );
308 },
309 {
310 all: '.mw-test-implement-a { float: right; }'
311 }
312 );
313
314 return mw.loader.using( 'test.implement.a' );
315 } );
316
317 QUnit.test( '.implement( styles={ "url": { <media>: [url, ..] } } )', function ( assert ) {
318 var $element1 = $( '<div class="mw-test-implement-b1"></div>' ).appendTo( '#qunit-fixture' ),
319 $element2 = $( '<div class="mw-test-implement-b2"></div>' ).appendTo( '#qunit-fixture' ),
320 $element3 = $( '<div class="mw-test-implement-b3"></div>' ).appendTo( '#qunit-fixture' ),
321 done = assert.async();
322
323 assert.notEqual(
324 $element1.css( 'text-align' ),
325 'center',
326 'style is clear'
327 );
328 assert.notEqual(
329 $element2.css( 'float' ),
330 'left',
331 'style is clear'
332 );
333 assert.notEqual(
334 $element3.css( 'text-align' ),
335 'right',
336 'style is clear'
337 );
338
339 mw.loader.implement(
340 'test.implement.b',
341 function () {
342 // Note: done() must only be called when the entire test is
343 // complete. So, make sure that we don't start until *both*
344 // assertStyleAsync calls have completed.
345 var pending = 2;
346 assertStyleAsync( assert, $element2, 'float', 'left', function () {
347 assert.notEqual( $element1.css( 'text-align' ), 'center', 'print style is not applied' );
348
349 pending--;
350 if ( pending === 0 ) {
351 done();
352 }
353 } );
354 assertStyleAsync( assert, $element3, 'float', 'right', function () {
355 assert.notEqual( $element1.css( 'text-align' ), 'center', 'print style is not applied' );
356
357 pending--;
358 if ( pending === 0 ) {
359 done();
360 }
361 } );
362 },
363 {
364 url: {
365 print: [ urlStyleTest( '.mw-test-implement-b1', 'text-align', 'center' ) ],
366 screen: [
367 // T42834: Make sure it actually works with more than 1 stylesheet reference
368 urlStyleTest( '.mw-test-implement-b2', 'float', 'left' ),
369 urlStyleTest( '.mw-test-implement-b3', 'float', 'right' )
370 ]
371 }
372 }
373 );
374
375 mw.loader.load( 'test.implement.b' );
376 } );
377
378 // Backwards compatibility
379 QUnit.test( '.implement( styles={ <media>: text } ) (back-compat)', function ( assert ) {
380 var $element = $( '<div class="mw-test-implement-c"></div>' ).appendTo( '#qunit-fixture' );
381
382 assert.notEqual(
383 $element.css( 'float' ),
384 'right',
385 'style is clear'
386 );
387
388 mw.loader.implement(
389 'test.implement.c',
390 function () {
391 assert.strictEqual(
392 $element.css( 'float' ),
393 'right',
394 'style is applied'
395 );
396 },
397 {
398 all: '.mw-test-implement-c { float: right; }'
399 }
400 );
401
402 return mw.loader.using( 'test.implement.c' );
403 } );
404
405 // Backwards compatibility
406 QUnit.test( '.implement( styles={ <media>: [url, ..] } ) (back-compat)', function ( assert ) {
407 var $element = $( '<div class="mw-test-implement-d"></div>' ).appendTo( '#qunit-fixture' ),
408 $element2 = $( '<div class="mw-test-implement-d2"></div>' ).appendTo( '#qunit-fixture' ),
409 done = assert.async();
410
411 assert.notEqual(
412 $element.css( 'float' ),
413 'right',
414 'style is clear'
415 );
416 assert.notEqual(
417 $element2.css( 'text-align' ),
418 'center',
419 'style is clear'
420 );
421
422 mw.loader.implement(
423 'test.implement.d',
424 function () {
425 assertStyleAsync( assert, $element, 'float', 'right', function () {
426 assert.notEqual( $element2.css( 'text-align' ), 'center', 'print style is not applied (T42500)' );
427 done();
428 } );
429 },
430 {
431 all: [ urlStyleTest( '.mw-test-implement-d', 'float', 'right' ) ],
432 print: [ urlStyleTest( '.mw-test-implement-d2', 'text-align', 'center' ) ]
433 }
434 );
435
436 mw.loader.load( 'test.implement.d' );
437 } );
438
439 QUnit.test( '.implement( messages before script )', function ( assert ) {
440 mw.loader.implement(
441 'test.implement.order',
442 function () {
443 assert.strictEqual( mw.loader.getState( 'test.implement.order' ), 'executing', 'state during script execution' );
444 assert.strictEqual( mw.msg( 'test-foobar' ), 'Hello Foobar, $1!', 'messages load before script execution' );
445 },
446 {},
447 {
448 'test-foobar': 'Hello Foobar, $1!'
449 }
450 );
451
452 return mw.loader.using( 'test.implement.order' ).then( function () {
453 assert.strictEqual( mw.loader.getState( 'test.implement.order' ), 'ready', 'final success state' );
454 } );
455 } );
456
457 // @import (T33676)
458 QUnit.test( '.implement( styles with @import )', function ( assert ) {
459 var $element,
460 done = assert.async();
461
462 mw.loader.implement(
463 'test.implement.import',
464 function () {
465 $element = $( '<div class="mw-test-implement-import">Foo bar</div>' ).appendTo( '#qunit-fixture' );
466
467 assertStyleAsync( assert, $element, 'float', 'right', function () {
468 assert.strictEqual( $element.css( 'text-align' ), 'center',
469 'CSS styles after the @import rule are working'
470 );
471
472 done();
473 } );
474 },
475 {
476 css: [
477 '@import url(\''
478 + urlStyleTest( '.mw-test-implement-import', 'float', 'right' )
479 + '\');\n'
480 + '.mw-test-implement-import { text-align: center; }'
481 ]
482 }
483 );
484
485 return mw.loader.using( 'test.implement.import' );
486 } );
487
488 QUnit.test( '.implement( dependency with styles )', function ( assert ) {
489 var $element = $( '<div class="mw-test-implement-e"></div>' ).appendTo( '#qunit-fixture' ),
490 $element2 = $( '<div class="mw-test-implement-e2"></div>' ).appendTo( '#qunit-fixture' );
491
492 assert.notEqual(
493 $element.css( 'float' ),
494 'right',
495 'style is clear'
496 );
497 assert.notEqual(
498 $element2.css( 'float' ),
499 'left',
500 'style is clear'
501 );
502
503 mw.loader.register( [
504 [ 'test.implement.e', '0', [ 'test.implement.e2' ] ],
505 [ 'test.implement.e2', '0' ]
506 ] );
507
508 mw.loader.implement(
509 'test.implement.e',
510 function () {
511 assert.strictEqual(
512 $element.css( 'float' ),
513 'right',
514 'Depending module\'s style is applied'
515 );
516 },
517 {
518 all: '.mw-test-implement-e { float: right; }'
519 }
520 );
521
522 mw.loader.implement(
523 'test.implement.e2',
524 function () {
525 assert.strictEqual(
526 $element2.css( 'float' ),
527 'left',
528 'Dependency\'s style is applied'
529 );
530 },
531 {
532 all: '.mw-test-implement-e2 { float: left; }'
533 }
534 );
535
536 return mw.loader.using( 'test.implement.e' );
537 } );
538
539 QUnit.test( '.implement( only scripts )', function ( assert ) {
540 mw.loader.implement( 'test.onlyscripts', function () {} );
541 return mw.loader.using( 'test.onlyscripts', function () {
542 assert.strictEqual( mw.loader.getState( 'test.onlyscripts' ), 'ready' );
543 } );
544 } );
545
546 QUnit.test( '.implement( only messages )', function ( assert ) {
547 assert.assertFalse( mw.messages.exists( 'T31107' ), 'Verify that the test message doesn\'t exist yet' );
548
549 mw.loader.implement( 'test.implement.msgs', [], {}, { T31107: 'loaded' } );
550
551 return mw.loader.using( 'test.implement.msgs', function () {
552 assert.ok( mw.messages.exists( 'T31107' ), 'T31107: messages-only module should implement ok' );
553 } );
554 } );
555
556 QUnit.test( '.implement( empty )', function ( assert ) {
557 mw.loader.implement( 'test.empty' );
558 return mw.loader.using( 'test.empty', function () {
559 assert.strictEqual( mw.loader.getState( 'test.empty' ), 'ready' );
560 } );
561 } );
562
563 QUnit.test( '.implement( package files )', function ( assert ) {
564 var done = assert.async(),
565 initJsRan = false,
566 counter = 41;
567 mw.loader.implement(
568 'test.implement.packageFiles',
569 {
570 main: 'resources/src/foo/init.js',
571 files: {
572 'resources/src/foo/data/hello.json': { hello: 'world' },
573 'resources/src/foo/foo.js': function ( require, module ) {
574 counter++;
575 module.exports = { answer: counter };
576 },
577 'resources/src/bar/bar.js': function ( require, module ) {
578 var core = require( './core.js' );
579 module.exports = { data: core.sayHello( 'Alice' ) };
580 },
581 'resources/src/bar/core.js': function ( require, module ) {
582 module.exports = { sayHello: function ( name ) {
583 return 'Hello ' + name;
584 } };
585 },
586 'resources/src/foo/init.js': function ( require ) {
587 initJsRan = true;
588 assert.deepEqual( require( './data/hello.json' ), { hello: 'world' }, 'require() with .json file' );
589 assert.deepEqual( require( './foo.js' ), { answer: 42 }, 'require() with .js file in same directory' );
590 assert.deepEqual( require( '../bar/bar.js' ), { data: 'Hello Alice' }, 'require() with ../ of a file that uses same-directory require()' );
591 assert.deepEqual( require( './foo.js' ), { answer: 42 }, 'require()ing the same script twice only runs it once' );
592 }
593 }
594 },
595 {},
596 {},
597 {}
598 );
599 mw.loader.using( 'test.implement.packageFiles' ).done( function () {
600 assert.ok( initJsRan, 'main JS file is executed' );
601 done();
602 } );
603 } );
604
605 QUnit.test( '.addSource()', function ( assert ) {
606 mw.loader.addSource( { testsource1: 'https://1.test/src' } );
607
608 assert.throws( function () {
609 mw.loader.addSource( { testsource1: 'https://1.test/src' } );
610 }, /already registered/, 'duplicate pair from addSource(Object)' );
611
612 assert.throws( function () {
613 mw.loader.addSource( { testsource1: 'https://1.test/src-diff' } );
614 }, /already registered/, 'duplicate ID from addSource(Object)' );
615 } );
616
617 // @covers mw.loader#batchRequest
618 // This is a regression test because in the past we called getCombinedVersion()
619 // for all requested modules, before url splitting took place.
620 // Discovered as part of T188076, but not directly related.
621 QUnit.test( 'Url composition (modules considered for version)', function ( assert ) {
622 mw.loader.register( [
623 // [module, version, dependencies, group, source]
624 [ 'testUrlInc', 'url', [], null, 'testloader' ],
625 [ 'testUrlIncDump', 'dump', [], null, 'testloader' ]
626 ] );
627
628 mw.loader.maxQueryLength = 10;
629
630 return mw.loader.using( [ 'testUrlIncDump', 'testUrlInc' ] ).then( function ( require ) {
631 assert.propEqual(
632 require( 'testUrlIncDump' ).query,
633 {
634 modules: 'testUrlIncDump',
635 // Expected: Wrapped hash just for this one module
636 // $hash = hash( 'fnv132', 'dump');
637 // base_convert( $hash, 16, 36 ); // "13e9zzn"
638 // Previously: Wrapped hash for both modules, despite being in separate requests
639 // $hash = hash( 'fnv132', 'urldump' );
640 // base_convert( $hash, 16, 36 ); // "18kz9ca"
641 version: '13e9zzn'
642 },
643 'Query parameters'
644 );
645
646 assert.strictEqual( mw.loader.getState( 'testUrlInc' ), 'ready', 'testUrlInc also loaded' );
647 } );
648 } );
649
650 // @covers mw.loader#batchRequest
651 // @covers mw.loader#buildModulesString
652 QUnit.test( 'Url composition (order of modules for version) – T188076', function ( assert ) {
653 mw.loader.register( [
654 // [module, version, dependencies, group, source]
655 [ 'testUrlOrder', 'url', [], null, 'testloader' ],
656 [ 'testUrlOrder.a', '1', [], null, 'testloader' ],
657 [ 'testUrlOrder.b', '2', [], null, 'testloader' ],
658 [ 'testUrlOrderDump', 'dump', [], null, 'testloader' ]
659 ] );
660
661 return mw.loader.using( [
662 'testUrlOrderDump',
663 'testUrlOrder.b',
664 'testUrlOrder.a',
665 'testUrlOrder'
666 ] ).then( function ( require ) {
667 assert.propEqual(
668 require( 'testUrlOrderDump' ).query,
669 {
670 modules: 'testUrlOrder,testUrlOrderDump|testUrlOrder.a,b',
671 // Expected: Combined in order after string packing
672 // $hash = hash( 'fnv132', 'urldump12' );
673 // base_convert( $hash, 16, 36 ); // "1knqzan"
674 // Previously: Combined in order of before string packing
675 // $hash = hash( 'fnv132', 'url12dump' );
676 // base_convert( $hash, 16, 36 ); // "11eo3in"
677 version: '1knqzan'
678 },
679 'Query parameters'
680 );
681 } );
682 } );
683
684 QUnit.test( 'Broken indirect dependency', function ( assert ) {
685 this.useStubClock();
686
687 // Don't actually emit an error event
688 this.sandbox.stub( mw, 'track' );
689
690 mw.loader.register( [
691 [ 'test.module1', '0' ],
692 [ 'test.module2', '0', [ 'test.module1' ] ],
693 [ 'test.module3', '0', [ 'test.module2' ] ]
694 ] );
695 mw.loader.implement( 'test.module1', function () {
696 throw new Error( 'expected' );
697 }, {}, {} );
698 this.tick();
699
700 assert.strictEqual( mw.loader.getState( 'test.module1' ), 'error', 'Expected "error" state for test.module1' );
701 assert.strictEqual( mw.loader.getState( 'test.module2' ), 'error', 'Expected "error" state for test.module2' );
702 assert.strictEqual( mw.loader.getState( 'test.module3' ), 'error', 'Expected "error" state for test.module3' );
703
704 assert.strictEqual( mw.track.callCount, 1 );
705 } );
706
707 QUnit.test( 'Out-of-order implementation', function ( assert ) {
708 this.useStubClock();
709
710 mw.loader.register( [
711 [ 'test.module4', '0' ],
712 [ 'test.module5', '0', [ 'test.module4' ] ],
713 [ 'test.module6', '0', [ 'test.module5' ] ]
714 ] );
715
716 mw.loader.implement( 'test.module4', function () {} );
717 this.tick();
718 assert.strictEqual( mw.loader.getState( 'test.module4' ), 'ready', 'Expected "ready" state for test.module4' );
719 assert.strictEqual( mw.loader.getState( 'test.module5' ), 'registered', 'Expected "registered" state for test.module5' );
720 assert.strictEqual( mw.loader.getState( 'test.module6' ), 'registered', 'Expected "registered" state for test.module6' );
721
722 mw.loader.implement( 'test.module6', function () {} );
723 this.tick();
724 assert.strictEqual( mw.loader.getState( 'test.module4' ), 'ready', 'Expected "ready" state for test.module4' );
725 assert.strictEqual( mw.loader.getState( 'test.module5' ), 'registered', 'Expected "registered" state for test.module5' );
726 assert.strictEqual( mw.loader.getState( 'test.module6' ), 'loaded', 'Expected "loaded" state for test.module6' );
727
728 mw.loader.implement( 'test.module5', function () {} );
729 this.tick();
730 assert.strictEqual( mw.loader.getState( 'test.module4' ), 'ready', 'Expected "ready" state for test.module4' );
731 assert.strictEqual( mw.loader.getState( 'test.module5' ), 'ready', 'Expected "ready" state for test.module5' );
732 assert.strictEqual( mw.loader.getState( 'test.module6' ), 'ready', 'Expected "ready" state for test.module6' );
733 } );
734
735 QUnit.test( 'Missing dependency', function ( assert ) {
736 this.useStubClock();
737
738 mw.loader.register( [
739 [ 'test.module7', '0' ],
740 [ 'test.module8', '0', [ 'test.module7' ] ],
741 [ 'test.module9', '0', [ 'test.module8' ] ]
742 ] );
743
744 mw.loader.implement( 'test.module8', function () {} );
745 this.tick();
746 assert.strictEqual( mw.loader.getState( 'test.module7' ), 'registered', 'Expected "registered" state for test.module7' );
747 assert.strictEqual( mw.loader.getState( 'test.module8' ), 'loaded', 'Expected "loaded" state for test.module8' );
748 assert.strictEqual( mw.loader.getState( 'test.module9' ), 'registered', 'Expected "registered" state for test.module9' );
749
750 mw.loader.state( { 'test.module7': 'missing' } );
751 this.tick();
752 assert.strictEqual( mw.loader.getState( 'test.module7' ), 'missing', 'Expected "missing" state for test.module7' );
753 assert.strictEqual( mw.loader.getState( 'test.module8' ), 'error', 'Expected "error" state for test.module8' );
754 assert.strictEqual( mw.loader.getState( 'test.module9' ), 'error', 'Expected "error" state for test.module9' );
755
756 mw.loader.implement( 'test.module9', function () {} );
757 this.tick();
758 assert.strictEqual( mw.loader.getState( 'test.module7' ), 'missing', 'Expected "missing" state for test.module7' );
759 assert.strictEqual( mw.loader.getState( 'test.module8' ), 'error', 'Expected "error" state for test.module8' );
760 assert.strictEqual( mw.loader.getState( 'test.module9' ), 'error', 'Expected "error" state for test.module9' );
761
762 // Restore clock for QUnit and $.Deferred internals
763 this.clock.restore();
764 return mw.loader.using( [ 'test.module7' ] ).then(
765 function () {
766 throw new Error( 'Success fired despite missing dependency' );
767 },
768 function ( e, dependencies ) {
769 assert.strictEqual( Array.isArray( dependencies ), true, 'Expected array of dependencies' );
770 assert.deepEqual(
771 dependencies,
772 [ 'jquery', 'mediawiki.base', 'test.module7' ],
773 'Error callback called with module test.module7'
774 );
775 }
776 ).then( function () {
777 return mw.loader.using( [ 'test.module9' ] );
778 } ).then(
779 function () {
780 throw new Error( 'Success fired despite missing dependency' );
781 },
782 function ( e, dependencies ) {
783 assert.strictEqual( Array.isArray( dependencies ), true, 'Expected array of dependencies' );
784 dependencies.sort();
785 assert.deepEqual(
786 dependencies,
787 [ 'jquery', 'mediawiki.base', 'test.module7', 'test.module8', 'test.module9' ],
788 'Error callback called with all three modules as dependencies'
789 );
790 }
791 );
792 } );
793
794 QUnit.test( 'Dependency handling', function ( assert ) {
795 mw.loader.register( [
796 // [module, version, dependencies, group, source]
797 [ 'testMissing', '1', [], null, 'testloader' ],
798 [ 'testUsesMissing', '1', [ 'testMissing' ], null, 'testloader' ],
799 [ 'testUsesNestedMissing', '1', [ 'testUsesMissing' ], null, 'testloader' ]
800 ] );
801
802 function verifyModuleStates() {
803 assert.strictEqual( mw.loader.getState( 'testMissing' ), 'missing', 'Module "testMissing" state' );
804 assert.strictEqual( mw.loader.getState( 'testUsesMissing' ), 'error', 'Module "testUsesMissing" state' );
805 assert.strictEqual( mw.loader.getState( 'testUsesNestedMissing' ), 'error', 'Module "testUsesNestedMissing" state' );
806 }
807
808 return mw.loader.using( [ 'testUsesNestedMissing' ] ).then(
809 function () {
810 verifyModuleStates();
811 throw new Error( 'Error handler should be invoked.' );
812 },
813 function ( e, modules ) {
814 // When the server sets state of 'testMissing' to 'missing'
815 // it should bubble up and trigger the error callback of the job for 'testUsesNestedMissing'.
816 assert.strictEqual( modules.indexOf( 'testMissing' ) !== -1, true, 'Triggered by testMissing.' );
817
818 verifyModuleStates();
819 }
820 );
821 } );
822
823 QUnit.test( 'Skip-function handling', function ( assert ) {
824 mw.loader.register( [
825 // [module, version, dependencies, group, source, skip]
826 [ 'testSkipped', '1', [], null, 'testloader', 'return true;' ],
827 [ 'testNotSkipped', '1', [], null, 'testloader', 'return false;' ],
828 [ 'testUsesSkippable', '1', [ 'testSkipped', 'testNotSkipped' ], null, 'testloader' ]
829 ] );
830
831 return mw.loader.using( [ 'testUsesSkippable' ] ).then(
832 function () {
833 assert.strictEqual( mw.loader.getState( 'testSkipped' ), 'ready', 'Skipped module' );
834 assert.strictEqual( mw.loader.getState( 'testNotSkipped' ), 'ready', 'Regular module' );
835 assert.strictEqual( mw.loader.getState( 'testUsesSkippable' ), 'ready', 'Regular module with skippable dependency' );
836 },
837 function ( e, badmodules ) {
838 // Should not fail and QUnit would already catch this,
839 // but add a handler anyway to report details from 'badmodules
840 assert.deepEqual( badmodules, [], 'Bad modules' );
841 }
842 );
843 } );
844
845 // This bug was actually already fixed in 1.18 and later when discovered in 1.17.
846 QUnit.test( '.load( "//protocol-relative" ) - T32825', function ( assert ) {
847 var target,
848 done = assert.async();
849
850 // URL to the callback script
851 target = QUnit.fixurl(
852 mw.config.get( 'wgServer' ) + mw.config.get( 'wgScriptPath' ) + '/tests/qunit/data/mwLoaderTestCallback.js'
853 );
854 // Ensure a protocol-relative URL for this test
855 target = target.replace( /https?:/, '' );
856 assert.strictEqual( target.slice( 0, 2 ), '//', 'URL is protocol-relative' );
857
858 mw.loader.testCallback = function () {
859 // Ensure once, delete now
860 delete mw.loader.testCallback;
861 assert.ok( true, 'callback' );
862 done();
863 };
864
865 // Go!
866 mw.loader.load( target );
867 } );
868
869 QUnit.test( '.load( "/absolute-path" )', function ( assert ) {
870 var target,
871 done = assert.async();
872
873 // URL to the callback script
874 target = QUnit.fixurl( mw.config.get( 'wgScriptPath' ) + '/tests/qunit/data/mwLoaderTestCallback.js' );
875 assert.strictEqual( target.slice( 0, 1 ), '/', 'URL is relative to document root' );
876
877 mw.loader.testCallback = function () {
878 // Ensure once, delete now
879 delete mw.loader.testCallback;
880 assert.ok( true, 'callback' );
881 done();
882 };
883
884 // Go!
885 mw.loader.load( target );
886 } );
887
888 QUnit.test( 'Empty string module name - T28804', function ( assert ) {
889 var done = false;
890
891 assert.strictEqual( mw.loader.getState( '' ), null, 'State (unregistered)' );
892
893 mw.loader.register( '', 'v1' );
894 assert.strictEqual( mw.loader.getState( '' ), 'registered', 'State (registered)' );
895 assert.strictEqual( mw.loader.getVersion( '' ), 'v1', 'Version' );
896
897 mw.loader.implement( '', function () {
898 done = true;
899 } );
900
901 return mw.loader.using( '', function () {
902 assert.strictEqual( done, true, 'script ran' );
903 assert.strictEqual( mw.loader.getState( '' ), 'ready', 'State (ready)' );
904 } );
905 } );
906
907 QUnit.test( 'Executing race - T112232', function ( assert ) {
908 var done = false;
909
910 // The red herring schedules its CSS buffer first. In T112232, a bug in the
911 // state machine would cause the job for testRaceLoadMe to run with an earlier job.
912 mw.loader.implement(
913 'testRaceRedHerring',
914 function () {},
915 { css: [ '.mw-testRaceRedHerring {}' ] }
916 );
917 mw.loader.implement(
918 'testRaceLoadMe',
919 function () {
920 done = true;
921 },
922 { css: [ '.mw-testRaceLoadMe { float: left; }' ] }
923 );
924
925 mw.loader.load( [ 'testRaceRedHerring', 'testRaceLoadMe' ] );
926 return mw.loader.using( 'testRaceLoadMe', function () {
927 assert.strictEqual( done, true, 'script ran' );
928 assert.strictEqual( mw.loader.getState( 'testRaceLoadMe' ), 'ready', 'state' );
929 } );
930 } );
931
932 QUnit.test( 'Stale response caching - T117587', function ( assert ) {
933 var count = 0;
934 // Enable store and stub timeout/idle scheduling
935 this.sandbox.stub( mw.loader.store, 'enabled', true );
936 this.sandbox.stub( window, 'setTimeout', function ( fn ) {
937 fn();
938 } );
939 this.sandbox.stub( mw, 'requestIdleCallback', function ( fn ) {
940 fn();
941 } );
942
943 mw.loader.register( 'test.stale', 'v2' );
944 assert.strictEqual( mw.loader.store.get( 'test.stale' ), false, 'Not in store' );
945
946 mw.loader.implement( 'test.stale@v1', function () {
947 count++;
948 } );
949
950 return mw.loader.using( 'test.stale' )
951 .then( function () {
952 assert.strictEqual( count, 1 );
953 // After implementing, registry contains version as implemented by the response.
954 assert.strictEqual( mw.loader.getVersion( 'test.stale' ), 'v1', 'Override version' );
955 assert.strictEqual( mw.loader.getState( 'test.stale' ), 'ready' );
956 assert.strictEqual( typeof mw.loader.store.get( 'test.stale' ), 'string', 'In store' );
957 } )
958 .then( function () {
959 // Reset run time, but keep mw.loader.store
960 mw.loader.moduleRegistry[ 'test.stale' ].script = undefined;
961 mw.loader.moduleRegistry[ 'test.stale' ].state = 'registered';
962 mw.loader.moduleRegistry[ 'test.stale' ].version = 'v2';
963
964 // Module was stored correctly as v1
965 // On future navigations, it will be ignored until evicted
966 assert.strictEqual( mw.loader.store.get( 'test.stale' ), false, 'Not in store' );
967 } );
968 } );
969
970 QUnit.test( 'Stale response caching - backcompat', function ( assert ) {
971 var script = 0;
972 // Enable store and stub timeout/idle scheduling
973 this.sandbox.stub( mw.loader.store, 'enabled', true );
974 this.sandbox.stub( window, 'setTimeout', function ( fn ) {
975 fn();
976 } );
977 this.sandbox.stub( mw, 'requestIdleCallback', function ( fn ) {
978 fn();
979 } );
980
981 mw.loader.register( 'test.stalebc', 'v2' );
982 assert.strictEqual( mw.loader.store.get( 'test.stalebc' ), false, 'Not in store' );
983
984 mw.loader.implement( 'test.stalebc', function () {
985 script++;
986 } );
987
988 return mw.loader.using( 'test.stalebc' )
989 .then( function () {
990 assert.strictEqual( script, 1, 'module script ran' );
991 assert.strictEqual( mw.loader.getState( 'test.stalebc' ), 'ready' );
992 assert.strictEqual( typeof mw.loader.store.get( 'test.stalebc' ), 'string', 'In store' );
993 } )
994 .then( function () {
995 // Reset run time, but keep mw.loader.store
996 mw.loader.moduleRegistry[ 'test.stalebc' ].script = undefined;
997 mw.loader.moduleRegistry[ 'test.stalebc' ].state = 'registered';
998 mw.loader.moduleRegistry[ 'test.stalebc' ].version = 'v2';
999
1000 // Legacy behaviour is storing under the expected version,
1001 // which woudl lead to whitewashing and stale values (T117587).
1002 assert.ok( mw.loader.store.get( 'test.stalebc' ), 'In store' );
1003 } );
1004 } );
1005
1006 QUnit.test( 'require()', function ( assert ) {
1007 mw.loader.register( [
1008 [ 'test.require1', '0' ],
1009 [ 'test.require2', '0' ],
1010 [ 'test.require3', '0' ],
1011 [ 'test.require4', '0', [ 'test.require3' ] ]
1012 ] );
1013 mw.loader.implement( 'test.require1', function () {} );
1014 mw.loader.implement( 'test.require2', function ( $, jQuery, require, module ) {
1015 module.exports = 1;
1016 } );
1017 mw.loader.implement( 'test.require3', function ( $, jQuery, require, module ) {
1018 module.exports = function () {
1019 return 'hello world';
1020 };
1021 } );
1022 mw.loader.implement( 'test.require4', function ( $, jQuery, require, module ) {
1023 var other = require( 'test.require3' );
1024 module.exports = {
1025 pizza: function () {
1026 return other();
1027 }
1028 };
1029 } );
1030 return mw.loader.using( [ 'test.require1', 'test.require2', 'test.require3', 'test.require4' ] ).then( function ( require ) {
1031 var module1, module2, module3, module4;
1032
1033 module1 = require( 'test.require1' );
1034 module2 = require( 'test.require2' );
1035 module3 = require( 'test.require3' );
1036 module4 = require( 'test.require4' );
1037
1038 assert.strictEqual( typeof module1, 'object', 'export of module with no export' );
1039 assert.strictEqual( module2, 1, 'export a number' );
1040 assert.strictEqual( module3(), 'hello world', 'export a function' );
1041 assert.strictEqual( typeof module4.pizza, 'function', 'export an object' );
1042 assert.strictEqual( module4.pizza(), 'hello world', 'module can require other modules' );
1043
1044 assert.throws( function () {
1045 require( '_badmodule' );
1046 }, /is not loaded/, 'Requesting non-existent modules throws error.' );
1047 } );
1048 } );
1049
1050 QUnit.test( 'require() in debug mode', function ( assert ) {
1051 var path = mw.config.get( 'wgScriptPath' );
1052 mw.loader.register( [
1053 [ 'test.require.define', '0' ],
1054 [ 'test.require.callback', '0', [ 'test.require.define' ] ]
1055 ] );
1056 mw.loader.implement( 'test.require.callback', [ QUnit.fixurl( path + '/tests/qunit/data/requireCallMwLoaderTestCallback.js' ) ] );
1057 mw.loader.implement( 'test.require.define', [ QUnit.fixurl( path + '/tests/qunit/data/defineCallMwLoaderTestCallback.js' ) ] );
1058
1059 return mw.loader.using( 'test.require.callback' ).then( function ( require ) {
1060 var cb = require( 'test.require.callback' );
1061 assert.strictEqual( cb.immediate, 'Defined.', 'module.exports and require work in debug mode' );
1062 // Must use try-catch because cb.later() will throw if require is undefined,
1063 // which doesn't work well inside Deferred.then() when using jQuery 1.x with QUnit
1064 try {
1065 assert.strictEqual( cb.later(), 'Defined.', 'require works asynchrously in debug mode' );
1066 } catch ( e ) {
1067 assert.strictEqual( String( e ), null, 'require works asynchrously in debug mode' );
1068 }
1069 } );
1070 } );
1071
1072 QUnit.test( 'Implicit dependencies', function ( assert ) {
1073 var user = 0,
1074 site = 0,
1075 siteFromUser = 0;
1076
1077 mw.loader.implement(
1078 'site',
1079 function () {
1080 site++;
1081 }
1082 );
1083 mw.loader.implement(
1084 'user',
1085 function () {
1086 user++;
1087 siteFromUser = site;
1088 }
1089 );
1090
1091 return mw.loader.using( 'user', function () {
1092 assert.strictEqual( site, 1, 'site module' );
1093 assert.strictEqual( user, 1, 'user module' );
1094 assert.strictEqual( siteFromUser, 1, 'site ran before user' );
1095 } ).always( function () {
1096 // Reset
1097 mw.loader.moduleRegistry.site.state = 'registered';
1098 mw.loader.moduleRegistry.user.state = 'registered';
1099 } );
1100 } );
1101
1102 QUnit.test( '.getScript() - success', function ( assert ) {
1103 var scriptUrl = QUnit.fixurl(
1104 mw.config.get( 'wgScriptPath' ) + '/tests/qunit/data/mediawiki.loader.getScript.example.js'
1105 );
1106
1107 return mw.loader.getScript( scriptUrl ).then(
1108 function () {
1109 assert.strictEqual( mw.getScriptExampleScriptLoaded, true, 'Data attached to a global object is available' );
1110 }
1111 );
1112 } );
1113
1114 QUnit.test( '.getScript() - failure', function ( assert ) {
1115 assert.rejects(
1116 mw.loader.getScript( 'https://example.test/not-found' ),
1117 /Failed to load script/,
1118 'Descriptive error message'
1119 );
1120 } );
1121
1122 }() );