Merge "build: Upgrade eslint-utils dependency from 1.3.1 to 1.4.2 for security issues"
[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, 'track', 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, 'track', 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, 'track', function ( topic, data ) {
250 capture.push( {
251 topic: topic,
252 error: data.exception && data.exception.message,
253 source: data.source
254 } );
255 } );
256
257 mw.loader.load( 'test.load.unreg' );
258 assert.deepEqual(
259 [ {
260 topic: 'resourceloader.exception',
261 error: 'Unknown module: test.load.unreg',
262 source: 'resolve'
263 } ],
264 capture
265 );
266 } );
267
268 // Regression test for T36853
269 QUnit.test( '.load() - Error: Missing dependency', function ( assert ) {
270 var capture = [];
271 this.sandbox.stub( mw, 'track', function ( topic, data ) {
272 capture.push( {
273 topic: topic,
274 error: data.exception && data.exception.message,
275 source: data.source
276 } );
277 } );
278
279 mw.loader.register( [
280 [ 'test.load.missingdep1', '0', [ 'test.load.missingdep2' ] ],
281 [ 'test.load.missingdep', '0', [ 'test.load.missingdep1' ] ]
282 ] );
283 mw.loader.load( 'test.load.missingdep' );
284 assert.deepEqual(
285 [ {
286 topic: 'resourceloader.exception',
287 error: 'Unknown module: test.load.missingdep2',
288 source: 'resolve'
289 } ],
290 capture
291 );
292 } );
293
294 QUnit.test( '.implement( styles={ "css": [text, ..] } )', function ( assert ) {
295 var $element = $( '<div class="mw-test-implement-a"></div>' ).appendTo( '#qunit-fixture' );
296
297 assert.notEqual(
298 $element.css( 'float' ),
299 'right',
300 'style is clear'
301 );
302
303 mw.loader.implement(
304 'test.implement.a',
305 function () {
306 assert.strictEqual(
307 $element.css( 'float' ),
308 'right',
309 'style is applied'
310 );
311 },
312 {
313 all: '.mw-test-implement-a { float: right; }'
314 }
315 );
316
317 return mw.loader.using( 'test.implement.a' );
318 } );
319
320 QUnit.test( '.implement( styles={ "url": { <media>: [url, ..] } } )', function ( assert ) {
321 var $element1 = $( '<div class="mw-test-implement-b1"></div>' ).appendTo( '#qunit-fixture' ),
322 $element2 = $( '<div class="mw-test-implement-b2"></div>' ).appendTo( '#qunit-fixture' ),
323 $element3 = $( '<div class="mw-test-implement-b3"></div>' ).appendTo( '#qunit-fixture' ),
324 done = assert.async();
325
326 assert.notEqual(
327 $element1.css( 'text-align' ),
328 'center',
329 'style is clear'
330 );
331 assert.notEqual(
332 $element2.css( 'float' ),
333 'left',
334 'style is clear'
335 );
336 assert.notEqual(
337 $element3.css( 'text-align' ),
338 'right',
339 'style is clear'
340 );
341
342 mw.loader.implement(
343 'test.implement.b',
344 function () {
345 // Note: done() must only be called when the entire test is
346 // complete. So, make sure that we don't start until *both*
347 // assertStyleAsync calls have completed.
348 var pending = 2;
349 assertStyleAsync( assert, $element2, 'float', 'left', function () {
350 assert.notEqual( $element1.css( 'text-align' ), 'center', 'print style is not applied' );
351
352 pending--;
353 if ( pending === 0 ) {
354 done();
355 }
356 } );
357 assertStyleAsync( assert, $element3, 'float', 'right', function () {
358 assert.notEqual( $element1.css( 'text-align' ), 'center', 'print style is not applied' );
359
360 pending--;
361 if ( pending === 0 ) {
362 done();
363 }
364 } );
365 },
366 {
367 url: {
368 print: [ urlStyleTest( '.mw-test-implement-b1', 'text-align', 'center' ) ],
369 screen: [
370 // T42834: Make sure it actually works with more than 1 stylesheet reference
371 urlStyleTest( '.mw-test-implement-b2', 'float', 'left' ),
372 urlStyleTest( '.mw-test-implement-b3', 'float', 'right' )
373 ]
374 }
375 }
376 );
377
378 mw.loader.load( 'test.implement.b' );
379 } );
380
381 // Backwards compatibility
382 QUnit.test( '.implement( styles={ <media>: text } ) (back-compat)', function ( assert ) {
383 var $element = $( '<div class="mw-test-implement-c"></div>' ).appendTo( '#qunit-fixture' );
384
385 assert.notEqual(
386 $element.css( 'float' ),
387 'right',
388 'style is clear'
389 );
390
391 mw.loader.implement(
392 'test.implement.c',
393 function () {
394 assert.strictEqual(
395 $element.css( 'float' ),
396 'right',
397 'style is applied'
398 );
399 },
400 {
401 all: '.mw-test-implement-c { float: right; }'
402 }
403 );
404
405 return mw.loader.using( 'test.implement.c' );
406 } );
407
408 // Backwards compatibility
409 QUnit.test( '.implement( styles={ <media>: [url, ..] } ) (back-compat)', function ( assert ) {
410 var $element = $( '<div class="mw-test-implement-d"></div>' ).appendTo( '#qunit-fixture' ),
411 $element2 = $( '<div class="mw-test-implement-d2"></div>' ).appendTo( '#qunit-fixture' ),
412 done = assert.async();
413
414 assert.notEqual(
415 $element.css( 'float' ),
416 'right',
417 'style is clear'
418 );
419 assert.notEqual(
420 $element2.css( 'text-align' ),
421 'center',
422 'style is clear'
423 );
424
425 mw.loader.implement(
426 'test.implement.d',
427 function () {
428 assertStyleAsync( assert, $element, 'float', 'right', function () {
429 assert.notEqual( $element2.css( 'text-align' ), 'center', 'print style is not applied (T42500)' );
430 done();
431 } );
432 },
433 {
434 all: [ urlStyleTest( '.mw-test-implement-d', 'float', 'right' ) ],
435 print: [ urlStyleTest( '.mw-test-implement-d2', 'text-align', 'center' ) ]
436 }
437 );
438
439 mw.loader.load( 'test.implement.d' );
440 } );
441
442 QUnit.test( '.implement( messages before script )', function ( assert ) {
443 mw.loader.implement(
444 'test.implement.order',
445 function () {
446 assert.strictEqual( mw.loader.getState( 'test.implement.order' ), 'executing', 'state during script execution' );
447 assert.strictEqual( mw.msg( 'test-foobar' ), 'Hello Foobar, $1!', 'messages load before script execution' );
448 },
449 {},
450 {
451 'test-foobar': 'Hello Foobar, $1!'
452 }
453 );
454
455 return mw.loader.using( 'test.implement.order' ).then( function () {
456 assert.strictEqual( mw.loader.getState( 'test.implement.order' ), 'ready', 'final success state' );
457 } );
458 } );
459
460 // @import (T33676)
461 QUnit.test( '.implement( styles with @import )', function ( assert ) {
462 var $element,
463 done = assert.async();
464
465 mw.loader.implement(
466 'test.implement.import',
467 function () {
468 $element = $( '<div class="mw-test-implement-import">Foo bar</div>' ).appendTo( '#qunit-fixture' );
469
470 assertStyleAsync( assert, $element, 'float', 'right', function () {
471 assert.strictEqual( $element.css( 'text-align' ), 'center',
472 'CSS styles after the @import rule are working'
473 );
474
475 done();
476 } );
477 },
478 {
479 css: [
480 '@import url(\''
481 + urlStyleTest( '.mw-test-implement-import', 'float', 'right' )
482 + '\');\n'
483 + '.mw-test-implement-import { text-align: center; }'
484 ]
485 }
486 );
487
488 return mw.loader.using( 'test.implement.import' );
489 } );
490
491 QUnit.test( '.implement( dependency with styles )', function ( assert ) {
492 var $element = $( '<div class="mw-test-implement-e"></div>' ).appendTo( '#qunit-fixture' ),
493 $element2 = $( '<div class="mw-test-implement-e2"></div>' ).appendTo( '#qunit-fixture' );
494
495 assert.notEqual(
496 $element.css( 'float' ),
497 'right',
498 'style is clear'
499 );
500 assert.notEqual(
501 $element2.css( 'float' ),
502 'left',
503 'style is clear'
504 );
505
506 mw.loader.register( [
507 [ 'test.implement.e', '0', [ 'test.implement.e2' ] ],
508 [ 'test.implement.e2', '0' ]
509 ] );
510
511 mw.loader.implement(
512 'test.implement.e',
513 function () {
514 assert.strictEqual(
515 $element.css( 'float' ),
516 'right',
517 'Depending module\'s style is applied'
518 );
519 },
520 {
521 all: '.mw-test-implement-e { float: right; }'
522 }
523 );
524
525 mw.loader.implement(
526 'test.implement.e2',
527 function () {
528 assert.strictEqual(
529 $element2.css( 'float' ),
530 'left',
531 'Dependency\'s style is applied'
532 );
533 },
534 {
535 all: '.mw-test-implement-e2 { float: left; }'
536 }
537 );
538
539 return mw.loader.using( 'test.implement.e' );
540 } );
541
542 QUnit.test( '.implement( only scripts )', function ( assert ) {
543 mw.loader.implement( 'test.onlyscripts', function () {} );
544 return mw.loader.using( 'test.onlyscripts', function () {
545 assert.strictEqual( mw.loader.getState( 'test.onlyscripts' ), 'ready' );
546 } );
547 } );
548
549 QUnit.test( '.implement( only messages )', function ( assert ) {
550 assert.assertFalse( mw.messages.exists( 'T31107' ), 'Verify that the test message doesn\'t exist yet' );
551
552 mw.loader.implement( 'test.implement.msgs', [], {}, { T31107: 'loaded' } );
553
554 return mw.loader.using( 'test.implement.msgs', function () {
555 assert.ok( mw.messages.exists( 'T31107' ), 'T31107: messages-only module should implement ok' );
556 } );
557 } );
558
559 QUnit.test( '.implement( empty )', function ( assert ) {
560 mw.loader.implement( 'test.empty' );
561 return mw.loader.using( 'test.empty', function () {
562 assert.strictEqual( mw.loader.getState( 'test.empty' ), 'ready' );
563 } );
564 } );
565
566 QUnit.test( '.implement( package files )', function ( assert ) {
567 var done = assert.async(),
568 initJsRan = false,
569 counter = 41;
570 mw.loader.implement(
571 'test.implement.packageFiles',
572 {
573 main: 'resources/src/foo/init.js',
574 files: {
575 'resources/src/foo/data/hello.json': { hello: 'world' },
576 'resources/src/foo/foo.js': function ( require, module ) {
577 counter++;
578 module.exports = { answer: counter };
579 },
580 'resources/src/bar/bar.js': function ( require, module ) {
581 var core = require( './core.js' );
582 module.exports = { data: core.sayHello( 'Alice' ) };
583 },
584 'resources/src/bar/core.js': function ( require, module ) {
585 module.exports = { sayHello: function ( name ) {
586 return 'Hello ' + name;
587 } };
588 },
589 'resources/src/foo/init.js': function ( require ) {
590 initJsRan = true;
591 assert.deepEqual( require( './data/hello.json' ), { hello: 'world' }, 'require() with .json file' );
592 assert.deepEqual( require( './foo.js' ), { answer: 42 }, 'require() with .js file in same directory' );
593 assert.deepEqual( require( '../bar/bar.js' ), { data: 'Hello Alice' }, 'require() with ../ of a file that uses same-directory require()' );
594 assert.deepEqual( require( './foo.js' ), { answer: 42 }, 'require()ing the same script twice only runs it once' );
595 }
596 }
597 },
598 {},
599 {},
600 {}
601 );
602 mw.loader.using( 'test.implement.packageFiles' ).done( function () {
603 assert.ok( initJsRan, 'main JS file is executed' );
604 done();
605 } );
606 } );
607
608 QUnit.test( '.addSource()', function ( assert ) {
609 mw.loader.addSource( { testsource1: 'https://1.test/src' } );
610
611 assert.throws( function () {
612 mw.loader.addSource( { testsource1: 'https://1.test/src' } );
613 }, /already registered/, 'duplicate pair from addSource(Object)' );
614
615 assert.throws( function () {
616 mw.loader.addSource( { testsource1: 'https://1.test/src-diff' } );
617 }, /already registered/, 'duplicate ID from addSource(Object)' );
618 } );
619
620 // @covers mw.loader#batchRequest
621 // This is a regression test because in the past we called getCombinedVersion()
622 // for all requested modules, before url splitting took place.
623 // Discovered as part of T188076, but not directly related.
624 QUnit.test( 'Url composition (modules considered for version)', function ( assert ) {
625 mw.loader.register( [
626 // [module, version, dependencies, group, source]
627 [ 'testUrlInc', 'url', [], null, 'testloader' ],
628 [ 'testUrlIncDump', 'dump', [], null, 'testloader' ]
629 ] );
630
631 mw.loader.maxQueryLength = 10;
632
633 return mw.loader.using( [ 'testUrlIncDump', 'testUrlInc' ] ).then( function ( require ) {
634 assert.propEqual(
635 require( 'testUrlIncDump' ).query,
636 {
637 modules: 'testUrlIncDump',
638 // Expected: Wrapped hash just for this one module
639 // $hash = hash( 'fnv132', 'dump');
640 // base_convert( $hash, 16, 36 ); // "13e9zzn"
641 // Previously: Wrapped hash for both modules, despite being in separate requests
642 // $hash = hash( 'fnv132', 'urldump' );
643 // base_convert( $hash, 16, 36 ); // "18kz9ca"
644 version: '13e9zzn'
645 },
646 'Query parameters'
647 );
648
649 assert.strictEqual( mw.loader.getState( 'testUrlInc' ), 'ready', 'testUrlInc also loaded' );
650 } );
651 } );
652
653 // @covers mw.loader#batchRequest
654 // @covers mw.loader#buildModulesString
655 QUnit.test( 'Url composition (order of modules for version) – T188076', function ( assert ) {
656 mw.loader.register( [
657 // [module, version, dependencies, group, source]
658 [ 'testUrlOrder', 'url', [], null, 'testloader' ],
659 [ 'testUrlOrder.a', '1', [], null, 'testloader' ],
660 [ 'testUrlOrder.b', '2', [], null, 'testloader' ],
661 [ 'testUrlOrderDump', 'dump', [], null, 'testloader' ]
662 ] );
663
664 return mw.loader.using( [
665 'testUrlOrderDump',
666 'testUrlOrder.b',
667 'testUrlOrder.a',
668 'testUrlOrder'
669 ] ).then( function ( require ) {
670 assert.propEqual(
671 require( 'testUrlOrderDump' ).query,
672 {
673 modules: 'testUrlOrder,testUrlOrderDump|testUrlOrder.a,b',
674 // Expected: Combined in order after string packing
675 // $hash = hash( 'fnv132', 'urldump12' );
676 // base_convert( $hash, 16, 36 ); // "1knqzan"
677 // Previously: Combined in order of before string packing
678 // $hash = hash( 'fnv132', 'url12dump' );
679 // base_convert( $hash, 16, 36 ); // "11eo3in"
680 version: '1knqzan'
681 },
682 'Query parameters'
683 );
684 } );
685 } );
686
687 QUnit.test( 'Broken indirect dependency', function ( assert ) {
688 this.useStubClock();
689
690 // Don't actually emit an error event
691 this.sandbox.stub( mw, 'track' );
692
693 mw.loader.register( [
694 [ 'test.module1', '0' ],
695 [ 'test.module2', '0', [ 'test.module1' ] ],
696 [ 'test.module3', '0', [ 'test.module2' ] ]
697 ] );
698 mw.loader.implement( 'test.module1', function () {
699 throw new Error( 'expected' );
700 }, {}, {} );
701 this.tick();
702
703 assert.strictEqual( mw.loader.getState( 'test.module1' ), 'error', 'Expected "error" state for test.module1' );
704 assert.strictEqual( mw.loader.getState( 'test.module2' ), 'error', 'Expected "error" state for test.module2' );
705 assert.strictEqual( mw.loader.getState( 'test.module3' ), 'error', 'Expected "error" state for test.module3' );
706
707 assert.strictEqual( mw.track.callCount, 1 );
708 } );
709
710 QUnit.test( 'Out-of-order implementation', function ( assert ) {
711 this.useStubClock();
712
713 mw.loader.register( [
714 [ 'test.module4', '0' ],
715 [ 'test.module5', '0', [ 'test.module4' ] ],
716 [ 'test.module6', '0', [ 'test.module5' ] ]
717 ] );
718
719 mw.loader.implement( 'test.module4', function () {} );
720 this.tick();
721 assert.strictEqual( mw.loader.getState( 'test.module4' ), 'ready', 'Expected "ready" state for test.module4' );
722 assert.strictEqual( mw.loader.getState( 'test.module5' ), 'registered', 'Expected "registered" state for test.module5' );
723 assert.strictEqual( mw.loader.getState( 'test.module6' ), 'registered', 'Expected "registered" state for test.module6' );
724
725 mw.loader.implement( 'test.module6', function () {} );
726 this.tick();
727 assert.strictEqual( mw.loader.getState( 'test.module4' ), 'ready', 'Expected "ready" state for test.module4' );
728 assert.strictEqual( mw.loader.getState( 'test.module5' ), 'registered', 'Expected "registered" state for test.module5' );
729 assert.strictEqual( mw.loader.getState( 'test.module6' ), 'loaded', 'Expected "loaded" state for test.module6' );
730
731 mw.loader.implement( 'test.module5', function () {} );
732 this.tick();
733 assert.strictEqual( mw.loader.getState( 'test.module4' ), 'ready', 'Expected "ready" state for test.module4' );
734 assert.strictEqual( mw.loader.getState( 'test.module5' ), 'ready', 'Expected "ready" state for test.module5' );
735 assert.strictEqual( mw.loader.getState( 'test.module6' ), 'ready', 'Expected "ready" state for test.module6' );
736 } );
737
738 QUnit.test( 'Missing dependency', function ( assert ) {
739 this.useStubClock();
740
741 mw.loader.register( [
742 [ 'test.module7', '0' ],
743 [ 'test.module8', '0', [ 'test.module7' ] ],
744 [ 'test.module9', '0', [ 'test.module8' ] ]
745 ] );
746
747 mw.loader.implement( 'test.module8', function () {} );
748 this.tick();
749 assert.strictEqual( mw.loader.getState( 'test.module7' ), 'registered', 'Expected "registered" state for test.module7' );
750 assert.strictEqual( mw.loader.getState( 'test.module8' ), 'loaded', 'Expected "loaded" state for test.module8' );
751 assert.strictEqual( mw.loader.getState( 'test.module9' ), 'registered', 'Expected "registered" state for test.module9' );
752
753 mw.loader.state( { 'test.module7': 'missing' } );
754 this.tick();
755 assert.strictEqual( mw.loader.getState( 'test.module7' ), 'missing', 'Expected "missing" state for test.module7' );
756 assert.strictEqual( mw.loader.getState( 'test.module8' ), 'error', 'Expected "error" state for test.module8' );
757 assert.strictEqual( mw.loader.getState( 'test.module9' ), 'error', 'Expected "error" state for test.module9' );
758
759 mw.loader.implement( 'test.module9', function () {} );
760 this.tick();
761 assert.strictEqual( mw.loader.getState( 'test.module7' ), 'missing', 'Expected "missing" state for test.module7' );
762 assert.strictEqual( mw.loader.getState( 'test.module8' ), 'error', 'Expected "error" state for test.module8' );
763 assert.strictEqual( mw.loader.getState( 'test.module9' ), 'error', 'Expected "error" state for test.module9' );
764
765 // Restore clock for QUnit and $.Deferred internals
766 this.clock.restore();
767 return mw.loader.using( [ 'test.module7' ] ).then(
768 function () {
769 throw new Error( 'Success fired despite missing dependency' );
770 },
771 function ( e, dependencies ) {
772 assert.strictEqual( Array.isArray( dependencies ), true, 'Expected array of dependencies' );
773 assert.deepEqual(
774 dependencies,
775 [ 'jquery', 'mediawiki.base', 'test.module7' ],
776 'Error callback called with module test.module7'
777 );
778 }
779 ).then( function () {
780 return mw.loader.using( [ 'test.module9' ] );
781 } ).then(
782 function () {
783 throw new Error( 'Success fired despite missing dependency' );
784 },
785 function ( e, dependencies ) {
786 assert.strictEqual( Array.isArray( dependencies ), true, 'Expected array of dependencies' );
787 dependencies.sort();
788 assert.deepEqual(
789 dependencies,
790 [ 'jquery', 'mediawiki.base', 'test.module7', 'test.module8', 'test.module9' ],
791 'Error callback called with all three modules as dependencies'
792 );
793 }
794 );
795 } );
796
797 QUnit.test( 'Dependency handling', function ( assert ) {
798 mw.loader.register( [
799 // [module, version, dependencies, group, source]
800 [ 'testMissing', '1', [], null, 'testloader' ],
801 [ 'testUsesMissing', '1', [ 'testMissing' ], null, 'testloader' ],
802 [ 'testUsesNestedMissing', '1', [ 'testUsesMissing' ], null, 'testloader' ]
803 ] );
804
805 function verifyModuleStates() {
806 assert.strictEqual( mw.loader.getState( 'testMissing' ), 'missing', 'Module "testMissing" state' );
807 assert.strictEqual( mw.loader.getState( 'testUsesMissing' ), 'error', 'Module "testUsesMissing" state' );
808 assert.strictEqual( mw.loader.getState( 'testUsesNestedMissing' ), 'error', 'Module "testUsesNestedMissing" state' );
809 }
810
811 return mw.loader.using( [ 'testUsesNestedMissing' ] ).then(
812 function () {
813 verifyModuleStates();
814 throw new Error( 'Error handler should be invoked.' );
815 },
816 function ( e, modules ) {
817 // When the server sets state of 'testMissing' to 'missing'
818 // it should bubble up and trigger the error callback of the job for 'testUsesNestedMissing'.
819 assert.strictEqual( modules.indexOf( 'testMissing' ) !== -1, true, 'Triggered by testMissing.' );
820
821 verifyModuleStates();
822 }
823 );
824 } );
825
826 QUnit.test( 'Skip-function handling', function ( assert ) {
827 mw.loader.register( [
828 // [module, version, dependencies, group, source, skip]
829 [ 'testSkipped', '1', [], null, 'testloader', 'return true;' ],
830 [ 'testNotSkipped', '1', [], null, 'testloader', 'return false;' ],
831 [ 'testUsesSkippable', '1', [ 'testSkipped', 'testNotSkipped' ], null, 'testloader' ]
832 ] );
833
834 return mw.loader.using( [ 'testUsesSkippable' ] ).then(
835 function () {
836 assert.strictEqual( mw.loader.getState( 'testSkipped' ), 'ready', 'Skipped module' );
837 assert.strictEqual( mw.loader.getState( 'testNotSkipped' ), 'ready', 'Regular module' );
838 assert.strictEqual( mw.loader.getState( 'testUsesSkippable' ), 'ready', 'Regular module with skippable dependency' );
839 },
840 function ( e, badmodules ) {
841 // Should not fail and QUnit would already catch this,
842 // but add a handler anyway to report details from 'badmodules
843 assert.deepEqual( badmodules, [], 'Bad modules' );
844 }
845 );
846 } );
847
848 // This bug was actually already fixed in 1.18 and later when discovered in 1.17.
849 QUnit.test( '.load( "//protocol-relative" ) - T32825', function ( assert ) {
850 var target,
851 done = assert.async();
852
853 // URL to the callback script
854 target = QUnit.fixurl(
855 mw.config.get( 'wgServer' ) + mw.config.get( 'wgScriptPath' ) + '/tests/qunit/data/mwLoaderTestCallback.js'
856 );
857 // Ensure a protocol-relative URL for this test
858 target = target.replace( /https?:/, '' );
859 assert.strictEqual( target.slice( 0, 2 ), '//', 'URL is protocol-relative' );
860
861 mw.loader.testCallback = function () {
862 // Ensure once, delete now
863 delete mw.loader.testCallback;
864 assert.ok( true, 'callback' );
865 done();
866 };
867
868 // Go!
869 mw.loader.load( target );
870 } );
871
872 QUnit.test( '.load( "/absolute-path" )', function ( assert ) {
873 var target,
874 done = assert.async();
875
876 // URL to the callback script
877 target = QUnit.fixurl( mw.config.get( 'wgScriptPath' ) + '/tests/qunit/data/mwLoaderTestCallback.js' );
878 assert.strictEqual( target.slice( 0, 1 ), '/', 'URL is relative to document root' );
879
880 mw.loader.testCallback = function () {
881 // Ensure once, delete now
882 delete mw.loader.testCallback;
883 assert.ok( true, 'callback' );
884 done();
885 };
886
887 // Go!
888 mw.loader.load( target );
889 } );
890
891 QUnit.test( 'Empty string module name - T28804', function ( assert ) {
892 var done = false;
893
894 assert.strictEqual( mw.loader.getState( '' ), null, 'State (unregistered)' );
895
896 mw.loader.register( '', 'v1' );
897 assert.strictEqual( mw.loader.getState( '' ), 'registered', 'State (registered)' );
898 assert.strictEqual( mw.loader.getVersion( '' ), 'v1', 'Version' );
899
900 mw.loader.implement( '', function () {
901 done = true;
902 } );
903
904 return mw.loader.using( '', function () {
905 assert.strictEqual( done, true, 'script ran' );
906 assert.strictEqual( mw.loader.getState( '' ), 'ready', 'State (ready)' );
907 } );
908 } );
909
910 QUnit.test( 'Executing race - T112232', function ( assert ) {
911 var done = false;
912
913 // The red herring schedules its CSS buffer first. In T112232, a bug in the
914 // state machine would cause the job for testRaceLoadMe to run with an earlier job.
915 mw.loader.implement(
916 'testRaceRedHerring',
917 function () {},
918 { css: [ '.mw-testRaceRedHerring {}' ] }
919 );
920 mw.loader.implement(
921 'testRaceLoadMe',
922 function () {
923 done = true;
924 },
925 { css: [ '.mw-testRaceLoadMe { float: left; }' ] }
926 );
927
928 mw.loader.load( [ 'testRaceRedHerring', 'testRaceLoadMe' ] );
929 return mw.loader.using( 'testRaceLoadMe', function () {
930 assert.strictEqual( done, true, 'script ran' );
931 assert.strictEqual( mw.loader.getState( 'testRaceLoadMe' ), 'ready', 'state' );
932 } );
933 } );
934
935 QUnit.test( 'Stale response caching - T117587', function ( assert ) {
936 var count = 0;
937 // Enable store and stub timeout/idle scheduling
938 this.sandbox.stub( mw.loader.store, 'enabled', true );
939 this.sandbox.stub( window, 'setTimeout', function ( fn ) {
940 fn();
941 } );
942 this.sandbox.stub( mw, 'requestIdleCallback', function ( fn ) {
943 fn();
944 } );
945
946 mw.loader.register( 'test.stale', 'v2' );
947 assert.strictEqual( mw.loader.store.get( 'test.stale' ), false, 'Not in store' );
948
949 mw.loader.implement( 'test.stale@v1', function () {
950 count++;
951 } );
952
953 return mw.loader.using( 'test.stale' )
954 .then( function () {
955 assert.strictEqual( count, 1 );
956 // After implementing, registry contains version as implemented by the response.
957 assert.strictEqual( mw.loader.getVersion( 'test.stale' ), 'v1', 'Override version' );
958 assert.strictEqual( mw.loader.getState( 'test.stale' ), 'ready' );
959 assert.strictEqual( typeof mw.loader.store.get( 'test.stale' ), 'string', 'In store' );
960 } )
961 .then( function () {
962 // Reset run time, but keep mw.loader.store
963 mw.loader.moduleRegistry[ 'test.stale' ].script = undefined;
964 mw.loader.moduleRegistry[ 'test.stale' ].state = 'registered';
965 mw.loader.moduleRegistry[ 'test.stale' ].version = 'v2';
966
967 // Module was stored correctly as v1
968 // On future navigations, it will be ignored until evicted
969 assert.strictEqual( mw.loader.store.get( 'test.stale' ), false, 'Not in store' );
970 } );
971 } );
972
973 QUnit.test( 'Stale response caching - backcompat', function ( assert ) {
974 var script = 0;
975 // Enable store and stub timeout/idle scheduling
976 this.sandbox.stub( mw.loader.store, 'enabled', true );
977 this.sandbox.stub( window, 'setTimeout', function ( fn ) {
978 fn();
979 } );
980 this.sandbox.stub( mw, 'requestIdleCallback', function ( fn ) {
981 fn();
982 } );
983
984 mw.loader.register( 'test.stalebc', 'v2' );
985 assert.strictEqual( mw.loader.store.get( 'test.stalebc' ), false, 'Not in store' );
986
987 mw.loader.implement( 'test.stalebc', function () {
988 script++;
989 } );
990
991 return mw.loader.using( 'test.stalebc' )
992 .then( function () {
993 assert.strictEqual( script, 1, 'module script ran' );
994 assert.strictEqual( mw.loader.getState( 'test.stalebc' ), 'ready' );
995 assert.strictEqual( typeof mw.loader.store.get( 'test.stalebc' ), 'string', 'In store' );
996 } )
997 .then( function () {
998 // Reset run time, but keep mw.loader.store
999 mw.loader.moduleRegistry[ 'test.stalebc' ].script = undefined;
1000 mw.loader.moduleRegistry[ 'test.stalebc' ].state = 'registered';
1001 mw.loader.moduleRegistry[ 'test.stalebc' ].version = 'v2';
1002
1003 // Legacy behaviour is storing under the expected version,
1004 // which woudl lead to whitewashing and stale values (T117587).
1005 assert.ok( mw.loader.store.get( 'test.stalebc' ), 'In store' );
1006 } );
1007 } );
1008
1009 QUnit.test( 'No storing of group=private responses', function ( assert ) {
1010 var name = 'test.group.priv';
1011
1012 // Enable store and stub timeout/idle scheduling
1013 this.sandbox.stub( mw.loader.store, 'enabled', true );
1014 this.sandbox.stub( window, 'setTimeout', function ( fn ) {
1015 fn();
1016 } );
1017 this.sandbox.stub( mw, 'requestIdleCallback', function ( fn ) {
1018 fn();
1019 } );
1020
1021 // See ResourceLoaderStartUpModule::$groupIds
1022 mw.loader.register( name, 'x', [], 1 );
1023 assert.strictEqual( mw.loader.store.get( name ), false, 'Not in store' );
1024
1025 mw.loader.implement( name, function () {} );
1026 return mw.loader.using( name ).then( function () {
1027 assert.strictEqual( mw.loader.getState( name ), 'ready' );
1028 assert.strictEqual( mw.loader.store.get( name ), false, 'Still not in store' );
1029 } );
1030 } );
1031
1032 QUnit.test( 'No storing of group=user responses', function ( assert ) {
1033 var name = 'test.group.user';
1034
1035 // Enable store and stub timeout/idle scheduling
1036 this.sandbox.stub( mw.loader.store, 'enabled', true );
1037 this.sandbox.stub( window, 'setTimeout', function ( fn ) {
1038 fn();
1039 } );
1040 this.sandbox.stub( mw, 'requestIdleCallback', function ( fn ) {
1041 fn();
1042 } );
1043
1044 // See ResourceLoaderStartUpModule::$groupIds
1045 mw.loader.register( name, 'y', [], 0 );
1046 assert.strictEqual( mw.loader.store.get( name ), false, 'Not in store' );
1047
1048 mw.loader.implement( name, function () {} );
1049 return mw.loader.using( name ).then( function () {
1050 assert.strictEqual( mw.loader.getState( name ), 'ready' );
1051 assert.strictEqual( mw.loader.store.get( name ), false, 'Still not in store' );
1052 } );
1053 } );
1054
1055 QUnit.test( 'mw.loader.store.init - Invalid JSON', function ( assert ) {
1056 // Reset
1057 this.sandbox.stub( mw.loader.store, 'enabled', null );
1058 this.sandbox.stub( mw.loader.store, 'items', {} );
1059 this.resetStoreKey = true;
1060 localStorage.setItem( mw.loader.store.key, 'invalid' );
1061
1062 mw.loader.store.init();
1063 assert.strictEqual( mw.loader.store.enabled, true, 'Enabled' );
1064 assert.strictEqual(
1065 $.isEmptyObject( mw.loader.store.items ),
1066 true,
1067 'Items starts fresh'
1068 );
1069 } );
1070
1071 QUnit.test( 'mw.loader.store.init - Wrong JSON', function ( assert ) {
1072 // Reset
1073 this.sandbox.stub( mw.loader.store, 'enabled', null );
1074 this.sandbox.stub( mw.loader.store, 'items', {} );
1075 this.resetStoreKey = true;
1076 localStorage.setItem( mw.loader.store.key, JSON.stringify( { wrong: true } ) );
1077
1078 mw.loader.store.init();
1079 assert.strictEqual( mw.loader.store.enabled, true, 'Enabled' );
1080 assert.strictEqual(
1081 $.isEmptyObject( mw.loader.store.items ),
1082 true,
1083 'Items starts fresh'
1084 );
1085 } );
1086
1087 QUnit.test( 'mw.loader.store.init - Expired JSON', function ( assert ) {
1088 // Reset
1089 this.sandbox.stub( mw.loader.store, 'enabled', null );
1090 this.sandbox.stub( mw.loader.store, 'items', {} );
1091 this.resetStoreKey = true;
1092 localStorage.setItem( mw.loader.store.key, JSON.stringify( {
1093 items: { use: 'not me' },
1094 vary: mw.loader.store.vary,
1095 asOf: 130161 // 2011-04-01 12:00
1096 } ) );
1097
1098 mw.loader.store.init();
1099 assert.strictEqual( mw.loader.store.enabled, true, 'Enabled' );
1100 assert.strictEqual(
1101 $.isEmptyObject( mw.loader.store.items ),
1102 true,
1103 'Items starts fresh'
1104 );
1105 } );
1106
1107 QUnit.test( 'mw.loader.store.init - Good JSON', function ( assert ) {
1108 // Reset
1109 this.sandbox.stub( mw.loader.store, 'enabled', null );
1110 this.sandbox.stub( mw.loader.store, 'items', {} );
1111 this.resetStoreKey = true;
1112 localStorage.setItem( mw.loader.store.key, JSON.stringify( {
1113 items: { use: 'me' },
1114 vary: mw.loader.store.vary,
1115 asOf: Math.ceil( Date.now() / 1e7 ) - 5 // ~ 13 hours ago
1116 } ) );
1117
1118 mw.loader.store.init();
1119 assert.strictEqual( mw.loader.store.enabled, true, 'Enabled' );
1120 assert.deepEqual(
1121 mw.loader.store.items,
1122 { use: 'me' },
1123 'Stored items are loaded'
1124 );
1125 } );
1126
1127 QUnit.test( 'require()', function ( assert ) {
1128 mw.loader.register( [
1129 [ 'test.require1', '0' ],
1130 [ 'test.require2', '0' ],
1131 [ 'test.require3', '0' ],
1132 [ 'test.require4', '0', [ 'test.require3' ] ]
1133 ] );
1134 mw.loader.implement( 'test.require1', function () {} );
1135 mw.loader.implement( 'test.require2', function ( $, jQuery, require, module ) {
1136 module.exports = 1;
1137 } );
1138 mw.loader.implement( 'test.require3', function ( $, jQuery, require, module ) {
1139 module.exports = function () {
1140 return 'hello world';
1141 };
1142 } );
1143 mw.loader.implement( 'test.require4', function ( $, jQuery, require, module ) {
1144 var other = require( 'test.require3' );
1145 module.exports = {
1146 pizza: function () {
1147 return other();
1148 }
1149 };
1150 } );
1151 return mw.loader.using( [ 'test.require1', 'test.require2', 'test.require3', 'test.require4' ] ).then( function ( require ) {
1152 var module1, module2, module3, module4;
1153
1154 module1 = require( 'test.require1' );
1155 module2 = require( 'test.require2' );
1156 module3 = require( 'test.require3' );
1157 module4 = require( 'test.require4' );
1158
1159 assert.strictEqual( typeof module1, 'object', 'export of module with no export' );
1160 assert.strictEqual( module2, 1, 'export a number' );
1161 assert.strictEqual( module3(), 'hello world', 'export a function' );
1162 assert.strictEqual( typeof module4.pizza, 'function', 'export an object' );
1163 assert.strictEqual( module4.pizza(), 'hello world', 'module can require other modules' );
1164
1165 assert.throws( function () {
1166 require( '_badmodule' );
1167 }, /is not loaded/, 'Requesting non-existent modules throws error.' );
1168 } );
1169 } );
1170
1171 QUnit.test( 'require() in debug mode', function ( assert ) {
1172 var path = mw.config.get( 'wgScriptPath' );
1173 mw.loader.register( [
1174 [ 'test.require.define', '0' ],
1175 [ 'test.require.callback', '0', [ 'test.require.define' ] ]
1176 ] );
1177 mw.loader.implement( 'test.require.callback', [ QUnit.fixurl( path + '/tests/qunit/data/requireCallMwLoaderTestCallback.js' ) ] );
1178 mw.loader.implement( 'test.require.define', [ QUnit.fixurl( path + '/tests/qunit/data/defineCallMwLoaderTestCallback.js' ) ] );
1179
1180 return mw.loader.using( 'test.require.callback' ).then( function ( require ) {
1181 var cb = require( 'test.require.callback' );
1182 assert.strictEqual( cb.immediate, 'Defined.', 'module.exports and require work in debug mode' );
1183 // Must use try-catch because cb.later() will throw if require is undefined,
1184 // which doesn't work well inside Deferred.then() when using jQuery 1.x with QUnit
1185 try {
1186 assert.strictEqual( cb.later(), 'Defined.', 'require works asynchrously in debug mode' );
1187 } catch ( e ) {
1188 assert.strictEqual( String( e ), null, 'require works asynchrously in debug mode' );
1189 }
1190 } );
1191 } );
1192
1193 QUnit.test( 'Implicit dependencies', function ( assert ) {
1194 var user = 0,
1195 site = 0,
1196 siteFromUser = 0;
1197
1198 mw.loader.implement(
1199 'site',
1200 function () {
1201 site++;
1202 }
1203 );
1204 mw.loader.implement(
1205 'user',
1206 function () {
1207 user++;
1208 siteFromUser = site;
1209 }
1210 );
1211
1212 return mw.loader.using( 'user', function () {
1213 assert.strictEqual( site, 1, 'site module' );
1214 assert.strictEqual( user, 1, 'user module' );
1215 assert.strictEqual( siteFromUser, 1, 'site ran before user' );
1216 } ).always( function () {
1217 // Reset
1218 mw.loader.moduleRegistry.site.state = 'registered';
1219 mw.loader.moduleRegistry.user.state = 'registered';
1220 } );
1221 } );
1222
1223 QUnit.test( '.getScript() - success', function ( assert ) {
1224 var scriptUrl = QUnit.fixurl(
1225 mw.config.get( 'wgScriptPath' ) + '/tests/qunit/data/mediawiki.loader.getScript.example.js'
1226 );
1227
1228 return mw.loader.getScript( scriptUrl ).then(
1229 function () {
1230 assert.strictEqual( mw.getScriptExampleScriptLoaded, true, 'Data attached to a global object is available' );
1231 }
1232 );
1233 } );
1234
1235 QUnit.test( '.getScript() - failure', function ( assert ) {
1236 assert.rejects(
1237 mw.loader.getScript( 'https://example.test/not-found' ),
1238 /Failed to load script/,
1239 'Descriptive error message'
1240 );
1241 } );
1242
1243 }() );