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