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