Merge "resources: Strip '$' and 'mw' from file closures"
[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( '.addSource()', function ( assert ) {
562 mw.loader.addSource( { testsource1: 'https://1.test/src' } );
563
564 assert.throws( function () {
565 mw.loader.addSource( { testsource1: 'https://1.test/src' } );
566 }, /already registered/, 'duplicate pair from addSource(Object)' );
567
568 assert.throws( function () {
569 mw.loader.addSource( { testsource1: 'https://1.test/src-diff' } );
570 }, /already registered/, 'duplicate ID from addSource(Object)' );
571 } );
572
573 // @covers mw.loader#batchRequest
574 // This is a regression test because in the past we called getCombinedVersion()
575 // for all requested modules, before url splitting took place.
576 // Discovered as part of T188076, but not directly related.
577 QUnit.test( 'Url composition (modules considered for version)', function ( assert ) {
578 mw.loader.register( [
579 // [module, version, dependencies, group, source]
580 [ 'testUrlInc', 'url', [], null, 'testloader' ],
581 [ 'testUrlIncDump', 'dump', [], null, 'testloader' ]
582 ] );
583
584 mw.config.set( 'wgResourceLoaderMaxQueryLength', 10 );
585
586 return mw.loader.using( [ 'testUrlIncDump', 'testUrlInc' ] ).then( function ( require ) {
587 assert.propEqual(
588 require( 'testUrlIncDump' ).query,
589 {
590 modules: 'testUrlIncDump',
591 // Expected: Wrapped hash just for this one module
592 // $hash = hash( 'fnv132', 'dump');
593 // base_convert( $hash, 16, 36 ); // "13e9zzn"
594 // Previously: Wrapped hash for both modules, despite being in separate requests
595 // $hash = hash( 'fnv132', 'urldump' );
596 // base_convert( $hash, 16, 36 ); // "18kz9ca"
597 version: '13e9zzn'
598 },
599 'Query parameters'
600 );
601
602 assert.strictEqual( mw.loader.getState( 'testUrlInc' ), 'ready', 'testUrlInc also loaded' );
603 } );
604 } );
605
606 // @covers mw.loader#batchRequest
607 // @covers mw.loader#buildModulesString
608 QUnit.test( 'Url composition (order of modules for version) – T188076', function ( assert ) {
609 mw.loader.register( [
610 // [module, version, dependencies, group, source]
611 [ 'testUrlOrder', 'url', [], null, 'testloader' ],
612 [ 'testUrlOrder.a', '1', [], null, 'testloader' ],
613 [ 'testUrlOrder.b', '2', [], null, 'testloader' ],
614 [ 'testUrlOrderDump', 'dump', [], null, 'testloader' ]
615 ] );
616
617 return mw.loader.using( [
618 'testUrlOrderDump',
619 'testUrlOrder.b',
620 'testUrlOrder.a',
621 'testUrlOrder'
622 ] ).then( function ( require ) {
623 assert.propEqual(
624 require( 'testUrlOrderDump' ).query,
625 {
626 modules: 'testUrlOrder,testUrlOrderDump|testUrlOrder.a,b',
627 // Expected: Combined in order after string packing
628 // $hash = hash( 'fnv132', 'urldump12' );
629 // base_convert( $hash, 16, 36 ); // "1knqzan"
630 // Previously: Combined in order of before string packing
631 // $hash = hash( 'fnv132', 'url12dump' );
632 // base_convert( $hash, 16, 36 ); // "11eo3in"
633 version: '1knqzan'
634 },
635 'Query parameters'
636 );
637 } );
638 } );
639
640 QUnit.test( 'Broken indirect dependency', function ( assert ) {
641 this.useStubClock();
642
643 // Don't actually emit an error event
644 this.sandbox.stub( mw, 'track' );
645
646 mw.loader.register( [
647 [ 'test.module1', '0' ],
648 [ 'test.module2', '0', [ 'test.module1' ] ],
649 [ 'test.module3', '0', [ 'test.module2' ] ]
650 ] );
651 mw.loader.implement( 'test.module1', function () {
652 throw new Error( 'expected' );
653 }, {}, {} );
654 this.tick();
655
656 assert.strictEqual( mw.loader.getState( 'test.module1' ), 'error', 'Expected "error" state for test.module1' );
657 assert.strictEqual( mw.loader.getState( 'test.module2' ), 'error', 'Expected "error" state for test.module2' );
658 assert.strictEqual( mw.loader.getState( 'test.module3' ), 'error', 'Expected "error" state for test.module3' );
659
660 assert.strictEqual( mw.track.callCount, 1 );
661 } );
662
663 QUnit.test( 'Out-of-order implementation', function ( assert ) {
664 this.useStubClock();
665
666 mw.loader.register( [
667 [ 'test.module4', '0' ],
668 [ 'test.module5', '0', [ 'test.module4' ] ],
669 [ 'test.module6', '0', [ 'test.module5' ] ]
670 ] );
671
672 mw.loader.implement( 'test.module4', function () {} );
673 this.tick();
674 assert.strictEqual( mw.loader.getState( 'test.module4' ), 'ready', 'Expected "ready" state for test.module4' );
675 assert.strictEqual( mw.loader.getState( 'test.module5' ), 'registered', 'Expected "registered" state for test.module5' );
676 assert.strictEqual( mw.loader.getState( 'test.module6' ), 'registered', 'Expected "registered" state for test.module6' );
677
678 mw.loader.implement( 'test.module6', function () {} );
679 this.tick();
680 assert.strictEqual( mw.loader.getState( 'test.module4' ), 'ready', 'Expected "ready" state for test.module4' );
681 assert.strictEqual( mw.loader.getState( 'test.module5' ), 'registered', 'Expected "registered" state for test.module5' );
682 assert.strictEqual( mw.loader.getState( 'test.module6' ), 'loaded', 'Expected "loaded" state for test.module6' );
683
684 mw.loader.implement( 'test.module5', function () {} );
685 this.tick();
686 assert.strictEqual( mw.loader.getState( 'test.module4' ), 'ready', 'Expected "ready" state for test.module4' );
687 assert.strictEqual( mw.loader.getState( 'test.module5' ), 'ready', 'Expected "ready" state for test.module5' );
688 assert.strictEqual( mw.loader.getState( 'test.module6' ), 'ready', 'Expected "ready" state for test.module6' );
689 } );
690
691 QUnit.test( 'Missing dependency', function ( assert ) {
692 this.useStubClock();
693
694 mw.loader.register( [
695 [ 'test.module7', '0' ],
696 [ 'test.module8', '0', [ 'test.module7' ] ],
697 [ 'test.module9', '0', [ 'test.module8' ] ]
698 ] );
699
700 mw.loader.implement( 'test.module8', function () {} );
701 this.tick();
702 assert.strictEqual( mw.loader.getState( 'test.module7' ), 'registered', 'Expected "registered" state for test.module7' );
703 assert.strictEqual( mw.loader.getState( 'test.module8' ), 'loaded', 'Expected "loaded" state for test.module8' );
704 assert.strictEqual( mw.loader.getState( 'test.module9' ), 'registered', 'Expected "registered" state for test.module9' );
705
706 mw.loader.state( { 'test.module7': 'missing' } );
707 this.tick();
708 assert.strictEqual( mw.loader.getState( 'test.module7' ), 'missing', 'Expected "missing" state for test.module7' );
709 assert.strictEqual( mw.loader.getState( 'test.module8' ), 'error', 'Expected "error" state for test.module8' );
710 assert.strictEqual( mw.loader.getState( 'test.module9' ), 'error', 'Expected "error" state for test.module9' );
711
712 mw.loader.implement( 'test.module9', function () {} );
713 this.tick();
714 assert.strictEqual( mw.loader.getState( 'test.module7' ), 'missing', 'Expected "missing" state for test.module7' );
715 assert.strictEqual( mw.loader.getState( 'test.module8' ), 'error', 'Expected "error" state for test.module8' );
716 assert.strictEqual( mw.loader.getState( 'test.module9' ), 'error', 'Expected "error" state for test.module9' );
717
718 // Restore clock for QUnit and $.Deferred internals
719 this.clock.restore();
720 return mw.loader.using( [ 'test.module7' ] ).then(
721 function () {
722 throw new Error( 'Success fired despite missing dependency' );
723 },
724 function ( e, dependencies ) {
725 assert.strictEqual( Array.isArray( dependencies ), true, 'Expected array of dependencies' );
726 assert.deepEqual(
727 dependencies,
728 [ 'jquery', 'mediawiki.base', 'test.module7' ],
729 'Error callback called with module test.module7'
730 );
731 }
732 ).then( function () {
733 return mw.loader.using( [ 'test.module9' ] );
734 } ).then(
735 function () {
736 throw new Error( 'Success fired despite missing dependency' );
737 },
738 function ( e, dependencies ) {
739 assert.strictEqual( Array.isArray( dependencies ), true, 'Expected array of dependencies' );
740 dependencies.sort();
741 assert.deepEqual(
742 dependencies,
743 [ 'jquery', 'mediawiki.base', 'test.module7', 'test.module8', 'test.module9' ],
744 'Error callback called with all three modules as dependencies'
745 );
746 }
747 );
748 } );
749
750 QUnit.test( 'Dependency handling', function ( assert ) {
751 mw.loader.register( [
752 // [module, version, dependencies, group, source]
753 [ 'testMissing', '1', [], null, 'testloader' ],
754 [ 'testUsesMissing', '1', [ 'testMissing' ], null, 'testloader' ],
755 [ 'testUsesNestedMissing', '1', [ 'testUsesMissing' ], null, 'testloader' ]
756 ] );
757
758 function verifyModuleStates() {
759 assert.strictEqual( mw.loader.getState( 'testMissing' ), 'missing', 'Module "testMissing" state' );
760 assert.strictEqual( mw.loader.getState( 'testUsesMissing' ), 'error', 'Module "testUsesMissing" state' );
761 assert.strictEqual( mw.loader.getState( 'testUsesNestedMissing' ), 'error', 'Module "testUsesNestedMissing" state' );
762 }
763
764 return mw.loader.using( [ 'testUsesNestedMissing' ] ).then(
765 function () {
766 verifyModuleStates();
767 throw new Error( 'Error handler should be invoked.' );
768 },
769 function ( e, modules ) {
770 // When the server sets state of 'testMissing' to 'missing'
771 // it should bubble up and trigger the error callback of the job for 'testUsesNestedMissing'.
772 assert.strictEqual( modules.indexOf( 'testMissing' ) !== -1, true, 'Triggered by testMissing.' );
773
774 verifyModuleStates();
775 }
776 );
777 } );
778
779 QUnit.test( 'Skip-function handling', function ( assert ) {
780 mw.loader.register( [
781 // [module, version, dependencies, group, source, skip]
782 [ 'testSkipped', '1', [], null, 'testloader', 'return true;' ],
783 [ 'testNotSkipped', '1', [], null, 'testloader', 'return false;' ],
784 [ 'testUsesSkippable', '1', [ 'testSkipped', 'testNotSkipped' ], null, 'testloader' ]
785 ] );
786
787 return mw.loader.using( [ 'testUsesSkippable' ] ).then(
788 function () {
789 assert.strictEqual( mw.loader.getState( 'testSkipped' ), 'ready', 'Skipped module' );
790 assert.strictEqual( mw.loader.getState( 'testNotSkipped' ), 'ready', 'Regular module' );
791 assert.strictEqual( mw.loader.getState( 'testUsesSkippable' ), 'ready', 'Regular module with skippable dependency' );
792 },
793 function ( e, badmodules ) {
794 // Should not fail and QUnit would already catch this,
795 // but add a handler anyway to report details from 'badmodules
796 assert.deepEqual( badmodules, [], 'Bad modules' );
797 }
798 );
799 } );
800
801 // This bug was actually already fixed in 1.18 and later when discovered in 1.17.
802 QUnit.test( '.load( "//protocol-relative" ) - T32825', function ( assert ) {
803 var target,
804 done = assert.async();
805
806 // URL to the callback script
807 target = QUnit.fixurl(
808 mw.config.get( 'wgServer' ) + mw.config.get( 'wgScriptPath' ) + '/tests/qunit/data/mwLoaderTestCallback.js'
809 );
810 // Ensure a protocol-relative URL for this test
811 target = target.replace( /https?:/, '' );
812 assert.strictEqual( target.slice( 0, 2 ), '//', 'URL is protocol-relative' );
813
814 mw.loader.testCallback = function () {
815 // Ensure once, delete now
816 delete mw.loader.testCallback;
817 assert.ok( true, 'callback' );
818 done();
819 };
820
821 // Go!
822 mw.loader.load( target );
823 } );
824
825 QUnit.test( '.load( "/absolute-path" )', function ( assert ) {
826 var target,
827 done = assert.async();
828
829 // URL to the callback script
830 target = QUnit.fixurl( mw.config.get( 'wgScriptPath' ) + '/tests/qunit/data/mwLoaderTestCallback.js' );
831 assert.strictEqual( target.slice( 0, 1 ), '/', 'URL is relative to document root' );
832
833 mw.loader.testCallback = function () {
834 // Ensure once, delete now
835 delete mw.loader.testCallback;
836 assert.ok( true, 'callback' );
837 done();
838 };
839
840 // Go!
841 mw.loader.load( target );
842 } );
843
844 QUnit.test( 'Empty string module name - T28804', function ( assert ) {
845 var done = false;
846
847 assert.strictEqual( mw.loader.getState( '' ), null, 'State (unregistered)' );
848
849 mw.loader.register( '', 'v1' );
850 assert.strictEqual( mw.loader.getState( '' ), 'registered', 'State (registered)' );
851 assert.strictEqual( mw.loader.getVersion( '' ), 'v1', 'Version' );
852
853 mw.loader.implement( '', function () {
854 done = true;
855 } );
856
857 return mw.loader.using( '', function () {
858 assert.strictEqual( done, true, 'script ran' );
859 assert.strictEqual( mw.loader.getState( '' ), 'ready', 'State (ready)' );
860 } );
861 } );
862
863 QUnit.test( 'Executing race - T112232', function ( assert ) {
864 var done = false;
865
866 // The red herring schedules its CSS buffer first. In T112232, a bug in the
867 // state machine would cause the job for testRaceLoadMe to run with an earlier job.
868 mw.loader.implement(
869 'testRaceRedHerring',
870 function () {},
871 { css: [ '.mw-testRaceRedHerring {}' ] }
872 );
873 mw.loader.implement(
874 'testRaceLoadMe',
875 function () {
876 done = true;
877 },
878 { css: [ '.mw-testRaceLoadMe { float: left; }' ] }
879 );
880
881 mw.loader.load( [ 'testRaceRedHerring', 'testRaceLoadMe' ] );
882 return mw.loader.using( 'testRaceLoadMe', function () {
883 assert.strictEqual( done, true, 'script ran' );
884 assert.strictEqual( mw.loader.getState( 'testRaceLoadMe' ), 'ready', 'state' );
885 } );
886 } );
887
888 QUnit.test( 'Stale response caching - T117587', function ( assert ) {
889 var count = 0;
890 // Enable store and stub timeout/idle scheduling
891 this.sandbox.stub( mw.loader.store, 'enabled', true );
892 this.sandbox.stub( window, 'setTimeout', function ( fn ) {
893 fn();
894 } );
895 this.sandbox.stub( mw, 'requestIdleCallback', function ( fn ) {
896 fn();
897 } );
898
899 mw.loader.register( 'test.stale', 'v2' );
900 assert.strictEqual( mw.loader.store.get( 'test.stale' ), false, 'Not in store' );
901
902 mw.loader.implement( 'test.stale@v1', function () {
903 count++;
904 } );
905
906 return mw.loader.using( 'test.stale' )
907 .then( function () {
908 assert.strictEqual( count, 1 );
909 // After implementing, registry contains version as implemented by the response.
910 assert.strictEqual( mw.loader.getVersion( 'test.stale' ), 'v1', 'Override version' );
911 assert.strictEqual( mw.loader.getState( 'test.stale' ), 'ready' );
912 assert.strictEqual( typeof mw.loader.store.get( 'test.stale' ), 'string', 'In store' );
913 } )
914 .then( function () {
915 // Reset run time, but keep mw.loader.store
916 mw.loader.moduleRegistry[ 'test.stale' ].script = undefined;
917 mw.loader.moduleRegistry[ 'test.stale' ].state = 'registered';
918 mw.loader.moduleRegistry[ 'test.stale' ].version = 'v2';
919
920 // Module was stored correctly as v1
921 // On future navigations, it will be ignored until evicted
922 assert.strictEqual( mw.loader.store.get( 'test.stale' ), false, 'Not in store' );
923 } );
924 } );
925
926 QUnit.test( 'Stale response caching - backcompat', function ( assert ) {
927 var script = 0;
928 // Enable store and stub timeout/idle scheduling
929 this.sandbox.stub( mw.loader.store, 'enabled', true );
930 this.sandbox.stub( window, 'setTimeout', function ( fn ) {
931 fn();
932 } );
933 this.sandbox.stub( mw, 'requestIdleCallback', function ( fn ) {
934 fn();
935 } );
936
937 mw.loader.register( 'test.stalebc', 'v2' );
938 assert.strictEqual( mw.loader.store.get( 'test.stalebc' ), false, 'Not in store' );
939
940 mw.loader.implement( 'test.stalebc', function () {
941 script++;
942 } );
943
944 return mw.loader.using( 'test.stalebc' )
945 .then( function () {
946 assert.strictEqual( script, 1, 'module script ran' );
947 assert.strictEqual( mw.loader.getState( 'test.stalebc' ), 'ready' );
948 assert.strictEqual( typeof mw.loader.store.get( 'test.stalebc' ), 'string', 'In store' );
949 } )
950 .then( function () {
951 // Reset run time, but keep mw.loader.store
952 mw.loader.moduleRegistry[ 'test.stalebc' ].script = undefined;
953 mw.loader.moduleRegistry[ 'test.stalebc' ].state = 'registered';
954 mw.loader.moduleRegistry[ 'test.stalebc' ].version = 'v2';
955
956 // Legacy behaviour is storing under the expected version,
957 // which woudl lead to whitewashing and stale values (T117587).
958 assert.ok( mw.loader.store.get( 'test.stalebc' ), 'In store' );
959 } );
960 } );
961
962 QUnit.test( 'require()', function ( assert ) {
963 mw.loader.register( [
964 [ 'test.require1', '0' ],
965 [ 'test.require2', '0' ],
966 [ 'test.require3', '0' ],
967 [ 'test.require4', '0', [ 'test.require3' ] ]
968 ] );
969 mw.loader.implement( 'test.require1', function () {} );
970 mw.loader.implement( 'test.require2', function ( $, jQuery, require, module ) {
971 module.exports = 1;
972 } );
973 mw.loader.implement( 'test.require3', function ( $, jQuery, require, module ) {
974 module.exports = function () {
975 return 'hello world';
976 };
977 } );
978 mw.loader.implement( 'test.require4', function ( $, jQuery, require, module ) {
979 var other = require( 'test.require3' );
980 module.exports = {
981 pizza: function () {
982 return other();
983 }
984 };
985 } );
986 return mw.loader.using( [ 'test.require1', 'test.require2', 'test.require3', 'test.require4' ] ).then( function ( require ) {
987 var module1, module2, module3, module4;
988
989 module1 = require( 'test.require1' );
990 module2 = require( 'test.require2' );
991 module3 = require( 'test.require3' );
992 module4 = require( 'test.require4' );
993
994 assert.strictEqual( typeof module1, 'object', 'export of module with no export' );
995 assert.strictEqual( module2, 1, 'export a number' );
996 assert.strictEqual( module3(), 'hello world', 'export a function' );
997 assert.strictEqual( typeof module4.pizza, 'function', 'export an object' );
998 assert.strictEqual( module4.pizza(), 'hello world', 'module can require other modules' );
999
1000 assert.throws( function () {
1001 require( '_badmodule' );
1002 }, /is not loaded/, 'Requesting non-existent modules throws error.' );
1003 } );
1004 } );
1005
1006 QUnit.test( 'require() in debug mode', function ( assert ) {
1007 var path = mw.config.get( 'wgScriptPath' );
1008 mw.loader.register( [
1009 [ 'test.require.define', '0' ],
1010 [ 'test.require.callback', '0', [ 'test.require.define' ] ]
1011 ] );
1012 mw.loader.implement( 'test.require.callback', [ QUnit.fixurl( path + '/tests/qunit/data/requireCallMwLoaderTestCallback.js' ) ] );
1013 mw.loader.implement( 'test.require.define', [ QUnit.fixurl( path + '/tests/qunit/data/defineCallMwLoaderTestCallback.js' ) ] );
1014
1015 return mw.loader.using( 'test.require.callback' ).then( function ( require ) {
1016 var cb = require( 'test.require.callback' );
1017 assert.strictEqual( cb.immediate, 'Defined.', 'module.exports and require work in debug mode' );
1018 // Must use try-catch because cb.later() will throw if require is undefined,
1019 // which doesn't work well inside Deferred.then() when using jQuery 1.x with QUnit
1020 try {
1021 assert.strictEqual( cb.later(), 'Defined.', 'require works asynchrously in debug mode' );
1022 } catch ( e ) {
1023 assert.strictEqual( String( e ), null, 'require works asynchrously in debug mode' );
1024 }
1025 } );
1026 } );
1027
1028 QUnit.test( 'Implicit dependencies', function ( assert ) {
1029 var user = 0,
1030 site = 0,
1031 siteFromUser = 0;
1032
1033 mw.loader.implement(
1034 'site',
1035 function () {
1036 site++;
1037 }
1038 );
1039 mw.loader.implement(
1040 'user',
1041 function () {
1042 user++;
1043 siteFromUser = site;
1044 }
1045 );
1046
1047 return mw.loader.using( 'user', function () {
1048 assert.strictEqual( site, 1, 'site module' );
1049 assert.strictEqual( user, 1, 'user module' );
1050 assert.strictEqual( siteFromUser, 1, 'site ran before user' );
1051 } ).always( function () {
1052 // Reset
1053 mw.loader.moduleRegistry[ 'site' ].state = 'registered';
1054 mw.loader.moduleRegistry[ 'user' ].state = 'registered';
1055 } );
1056 } );
1057
1058 }() );