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