929fa1fb5e64856bba8361d9b6bc806c86e9afc1
2 ( function ( $, mw
, QUnit
) {
8 * Make a safe copy of localEnv:
9 * - Creates a copy so that when the same object reference to module hooks is
10 * used by multipe test hooks, our QUnit.module extension will not wrap the
11 * callbacks multiple times. Instead, they wrap using a new object.
12 * - Normalise setup/teardown to avoid having to repeat this in each extension
13 * (deprecated in QUnit 1.16, removed in QUnit 2).
14 * - Strip any other properties.
16 function makeSafeEnv( localEnv
) {
18 beforeEach
: localEnv
.setup
|| localEnv
.beforeEach
,
19 afterEach
: localEnv
.teardown
|| localEnv
.afterEach
24 * Add bogus to url to prevent IE crazy caching
26 * @param {string} value a relative path (eg. 'data/foo.js'
27 * or 'data/test.php?foo=bar').
28 * @return {string} Such as 'data/foo.js?131031765087663960'
30 QUnit
.fixurl = function ( value
) {
31 return value
+ ( /\?/.test( value
) ? '&' : '?' )
32 + String( new Date().getTime() )
33 + String( parseInt( Math
.random() * 100000, 10 ) );
40 // For each test() that is asynchronous, allow this time to pass before
41 // killing the test and assuming timeout failure.
42 QUnit
.config
.testTimeout
= 60 * 1000;
44 // Reduce default animation duration from 400ms to 0ms for unit tests
45 // eslint-disable-next-line no-underscore-dangle
46 $.fx
.speeds
._default
= 0;
48 // Add a checkbox to QUnit header to toggle MediaWiki ResourceLoader debug mode.
49 QUnit
.config
.urlConfig
.push( {
51 label
: 'Enable ResourceLoaderDebug',
52 tooltip
: 'Enable debug mode in ResourceLoader',
59 * Glue code for nicer integration with QUnit setup/teardown
60 * Inspired by http://sinonjs.org/releases/sinon-qunit-1.0.0.js
62 sinon
.assert
.fail = function ( msg
) {
63 QUnit
.assert
.ok( false, msg
);
65 sinon
.assert
.pass = function ( msg
) {
66 QUnit
.assert
.ok( true, msg
);
71 properties
: [ 'spy', 'stub', 'mock', 'sandbox' ],
72 // Don't fake timers by default
76 // Extend QUnit.module to provide a Sinon sandbox.
78 var orgModule
= QUnit
.module
;
79 QUnit
.module = function ( name
, localEnv
, executeNow
) {
80 var orgBeforeEach
, orgAfterEach
;
81 if ( QUnit
.config
.moduleStack
.length
) {
82 // In a nested module, don't re-run our handlers.
83 return orgModule
.apply( this, arguments
);
85 if ( arguments
.length
=== 2 && typeof localEnv
=== 'function' ) {
86 executeNow
= localEnv
;
90 localEnv
= localEnv
|| {};
91 orgBeforeEach
= localEnv
.beforeEach
;
92 orgAfterEach
= localEnv
.afterEach
;
93 localEnv
.beforeEach = function () {
94 var config
= sinon
.getConfig( sinon
.config
);
95 config
.injectInto
= this;
96 sinon
.sandbox
.create( config
);
98 if ( orgBeforeEach
) {
99 return orgBeforeEach
.apply( this, arguments
);
102 localEnv
.afterEach = function () {
104 if ( orgAfterEach
) {
105 ret
= orgAfterEach
.apply( this, arguments
);
108 this.sandbox
.verifyAndRestore();
111 return orgModule( name
, localEnv
, executeNow
);
115 // Extend QUnit.module to provide a fixture element.
117 var orgModule
= QUnit
.module
;
118 QUnit
.module = function ( name
, localEnv
, executeNow
) {
119 var orgBeforeEach
, orgAfterEach
;
120 if ( QUnit
.config
.moduleStack
.length
) {
121 // In a nested module, don't re-run our handlers.
122 return orgModule
.apply( this, arguments
);
124 if ( arguments
.length
=== 2 && typeof localEnv
=== 'function' ) {
125 executeNow
= localEnv
;
126 localEnv
= undefined;
129 localEnv
= localEnv
|| {};
130 orgBeforeEach
= localEnv
.beforeEach
;
131 orgAfterEach
= localEnv
.afterEach
;
132 localEnv
.beforeEach = function () {
133 this.fixture
= document
.createElement( 'div' );
134 this.fixture
.id
= 'qunit-fixture';
135 document
.body
.appendChild( this.fixture
);
137 if ( orgBeforeEach
) {
138 return orgBeforeEach
.apply( this, arguments
);
141 localEnv
.afterEach = function () {
143 if ( orgAfterEach
) {
144 ret
= orgAfterEach
.apply( this, arguments
);
147 this.fixture
.parentNode
.removeChild( this.fixture
);
150 return orgModule( name
, localEnv
, executeNow
);
154 // Extend QUnit.module to normalise localEnv.
155 // NOTE: This MUST be the last QUnit.module extension so that the above extensions
156 // may safely modify the object and assume beforeEach/afterEach.
158 var orgModule
= QUnit
.module
;
159 QUnit
.module = function ( name
, localEnv
, executeNow
) {
160 if ( typeof localEnv
=== 'object' ) {
161 localEnv
= makeSafeEnv( localEnv
);
163 return orgModule( name
, localEnv
, executeNow
);
168 * Reset mw.config and others to a fresh copy of the live config for each test(),
169 * and restore it back to the live one afterwards.
171 * @param {Object} [localEnv]
172 * @example (see test suite at the bottom of this file)
175 QUnit
.newMwEnvironment
= ( function () {
176 var warn
, error
, liveConfig
, liveMessages
,
177 MwMap
= mw
.config
.constructor, // internal use only
180 liveConfig
= mw
.config
;
181 liveMessages
= mw
.messages
;
183 function suppressWarnings() {
184 if ( warn
=== undefined ) {
186 error
= mw
.log
.error
;
187 mw
.log
.warn
= mw
.log
.error
= $.noop
;
191 function restoreWarnings() {
192 // Guard against calls not balanced with suppressWarnings()
193 if ( warn
!== undefined ) {
195 mw
.log
.error
= error
;
196 warn
= error
= undefined;
200 function freshConfigCopy( custom
) {
202 // Tests should mock all factors that directly influence the tested code.
203 // For backwards compatibility though we set mw.config to a fresh copy of the live
204 // config. This way any modifications made to mw.config during the test will not
205 // affect other tests, nor the global scope outside the test runner.
206 // This is a shallow copy, since overriding an array or object value via "custom"
207 // should replace it. Setting a config property means you override it, not extend it.
208 // NOTE: It is important that we suppress warnings because extend() will also access
209 // deprecated properties and trigger deprecation warnings from mw.log#deprecate.
211 copy
= $.extend( {}, liveConfig
.get(), custom
);
217 function freshMessagesCopy( custom
) {
218 return $.extend( /* deep */true, {}, liveMessages
.get(), custom
);
222 * @param {jQuery.Event} event
223 * @param {jqXHR} jqXHR
224 * @param {Object} ajaxOptions
226 function trackAjax( event
, jqXHR
, ajaxOptions
) {
227 ajaxRequests
.push( { xhr
: jqXHR
, options
: ajaxOptions
} );
230 return function ( orgEnv
) {
231 var localEnv
= orgEnv
? makeSafeEnv( orgEnv
) : {};
232 // MediaWiki env testing
233 localEnv
.config
= orgEnv
&& orgEnv
.config
|| {};
234 localEnv
.messages
= orgEnv
&& orgEnv
.messages
|| {};
237 beforeEach: function () {
238 // Greetings, mock environment!
239 mw
.config
= new MwMap();
240 mw
.config
.set( freshConfigCopy( localEnv
.config
) );
241 mw
.messages
= new MwMap();
242 mw
.messages
.set( freshMessagesCopy( localEnv
.messages
) );
243 // Update reference to mw.messages
244 mw
.jqueryMsg
.setParserDefaults( {
245 messages
: mw
.messages
248 this.suppressWarnings
= suppressWarnings
;
249 this.restoreWarnings
= restoreWarnings
;
251 // Start tracking ajax requests
252 $( document
).on( 'ajaxSend', trackAjax
);
254 if ( localEnv
.beforeEach
) {
255 return localEnv
.beforeEach
.apply( this, arguments
);
259 afterEach: function () {
260 var timers
, pending
, $activeLen
, ret
;
262 if ( localEnv
.afterEach
) {
263 ret
= localEnv
.afterEach
.apply( this, arguments
);
266 // Stop tracking ajax requests
267 $( document
).off( 'ajaxSend', trackAjax
);
269 // As a convenience feature, automatically restore warnings if they're
270 // still suppressed by the end of the test.
273 // Farewell, mock environment!
274 mw
.config
= liveConfig
;
275 mw
.messages
= liveMessages
;
276 // Restore reference to mw.messages
277 mw
.jqueryMsg
.setParserDefaults( {
278 messages
: liveMessages
281 // Tests should use fake timers or wait for animations to complete
282 // Check for incomplete animations/requests/etc and throw if there are any.
283 if ( $.timers
&& $.timers
.length
!== 0 ) {
284 timers
= $.timers
.length
;
285 $.each( $.timers
, function ( i
, timer
) {
286 var node
= timer
.elem
;
287 mw
.log
.warn( 'Unfinished animation #' + i
+ ' in ' + timer
.queue
+ ' queue on ' +
288 mw
.html
.element( node
.nodeName
.toLowerCase(), $( node
).getAttrs() )
291 // Force animations to stop to give the next test a clean start
295 throw new Error( 'Unfinished animations: ' + timers
);
298 // Test should use fake XHR, wait for requests, or call abort()
299 $activeLen
= $.active
;
300 if ( $activeLen
!== undefined && $activeLen
!== 0 ) {
301 pending
= $.grep( ajaxRequests
, function ( ajax
) {
302 return ajax
.xhr
.state() === 'pending';
304 if ( pending
.length
!== $activeLen
) {
305 mw
.log
.warn( 'Pending requests does not match jQuery.active count' );
307 // Force requests to stop to give the next test a clean start
308 $.each( ajaxRequests
, function ( i
, ajax
) {
310 'AJAX request #' + i
+ ' (state: ' + ajax
.xhr
.state() + ')',
317 throw new Error( 'Pending AJAX requests: ' + pending
.length
+ ' (active: ' + $activeLen
+ ')' );
326 // $.when stops as soon as one fails, which makes sense in most
327 // practical scenarios, but not in a unit test where we really do
328 // need to wait until all of them are finished.
329 QUnit
.whenPromisesComplete = function () {
330 var altPromises
= [];
332 $.each( arguments
, function ( i
, arg
) {
333 var alt
= $.Deferred();
334 altPromises
.push( alt
);
336 // Whether this one fails or not, forwards it to
337 // the 'done' (resolve) callback of the alternative promise.
338 arg
.always( alt
.resolve
);
341 return $.when
.apply( $, altPromises
);
345 * Recursively convert a node to a plain object representing its structure.
346 * Only considers attributes and contents (elements and text nodes).
347 * Attribute values are compared strictly and not normalised.
350 * @return {Object|string} Plain JavaScript value representing the node.
352 function getDomStructure( node
) {
353 var $node
, children
, processedChildren
, i
, len
, el
;
355 if ( node
.nodeType
=== Node
.ELEMENT_NODE
) {
356 children
= $node
.contents();
357 processedChildren
= [];
358 for ( i
= 0, len
= children
.length
; i
< len
; i
++ ) {
360 if ( el
.nodeType
=== Node
.ELEMENT_NODE
|| el
.nodeType
=== Node
.TEXT_NODE
) {
361 processedChildren
.push( getDomStructure( el
) );
366 tagName
: node
.tagName
,
367 attributes
: $node
.getAttrs(),
368 contents
: processedChildren
371 // Should be text node
377 * Gets structure of node for this HTML.
379 * @param {string} html HTML markup for one or more nodes.
381 function getHtmlStructure( html
) {
382 var el
= $( '<div>' ).append( html
)[ 0 ];
383 return getDomStructure( el
);
387 * Add-on assertion helpers
389 // Define the add-ons
392 // Expect boolean true
393 assertTrue: function ( actual
, message
) {
395 result
: actual
=== true,
402 // Expect boolean false
403 assertFalse: function ( actual
, message
) {
405 result
: actual
=== false,
412 // Expect numerical value less than X
413 lt: function ( actual
, expected
, message
) {
415 result
: actual
< expected
,
417 expected
: 'less than ' + expected
,
422 // Expect numerical value less than or equal to X
423 ltOrEq: function ( actual
, expected
, message
) {
425 result
: actual
<= expected
,
427 expected
: 'less than or equal to ' + expected
,
432 // Expect numerical value greater than X
433 gt: function ( actual
, expected
, message
) {
435 result
: actual
> expected
,
437 expected
: 'greater than ' + expected
,
442 // Expect numerical value greater than or equal to X
443 gtOrEq: function ( actual
, expected
, message
) {
445 result
: actual
>= true,
447 expected
: 'greater than or equal to ' + expected
,
453 * Asserts that two HTML strings are structurally equivalent.
455 * @param {string} actualHtml Actual HTML markup.
456 * @param {string} expectedHtml Expected HTML markup
457 * @param {string} message Assertion message.
459 htmlEqual: function ( actualHtml
, expectedHtml
, message
) {
460 var actual
= getHtmlStructure( actualHtml
),
461 expected
= getHtmlStructure( expectedHtml
);
463 result
: QUnit
.equiv( actual
, expected
),
471 * Asserts that two HTML strings are not structurally equivalent.
473 * @param {string} actualHtml Actual HTML markup.
474 * @param {string} expectedHtml Expected HTML markup.
475 * @param {string} message Assertion message.
477 notHtmlEqual: function ( actualHtml
, expectedHtml
, message
) {
478 var actual
= getHtmlStructure( actualHtml
),
479 expected
= getHtmlStructure( expectedHtml
);
482 result
: !QUnit
.equiv( actual
, expected
),
491 $.extend( QUnit
.assert
, addons
);
494 * Small test suite to confirm proper functionality of the utilities and
495 * initializations defined above in this file.
497 QUnit
.module( 'testrunner', QUnit
.newMwEnvironment( {
499 this.mwHtmlLive
= mw
.html
;
501 escape: function () {
506 teardown: function () {
507 mw
.html
= this.mwHtmlLive
;
517 QUnit
.test( 'Setup', function ( assert
) {
518 assert
.equal( mw
.html
.escape( 'foo' ), 'mocked', 'setup() callback was ran.' );
519 assert
.equal( mw
.config
.get( 'testVar' ), 'foo', 'config object applied' );
520 assert
.equal( mw
.messages
.get( 'testMsg' ), 'Foo.', 'messages object applied' );
522 mw
.config
.set( 'testVar', 'bar' );
523 mw
.messages
.set( 'testMsg', 'Bar.' );
526 QUnit
.test( 'Teardown', function ( assert
) {
527 assert
.equal( mw
.config
.get( 'testVar' ), 'foo', 'config object restored and re-applied after test()' );
528 assert
.equal( mw
.messages
.get( 'testMsg' ), 'Foo.', 'messages object restored and re-applied after test()' );
531 QUnit
.test( 'Loader status', function ( assert
) {
533 modules
= mw
.loader
.getModuleNames(),
537 for ( i
= 0, len
= modules
.length
; i
< len
; i
++ ) {
538 state
= mw
.loader
.getState( modules
[ i
] );
539 if ( state
=== 'error' ) {
540 error
.push( modules
[ i
] );
541 } else if ( state
=== 'missing' ) {
542 missing
.push( modules
[ i
] );
546 assert
.deepEqual( error
, [], 'Modules in error state' );
547 assert
.deepEqual( missing
, [], 'Modules in missing state' );
550 QUnit
.test( 'assert.htmlEqual', function ( assert
) {
552 '<div><p class="some classes" data-length="10">Child paragraph with <a href="http://example.com">A link</a></p>Regular text<span>A span</span></div>',
553 '<div><p data-length=\'10\' class=\'some classes\'>Child paragraph with <a href=\'http://example.com\' >A link</a></p>Regular text<span>A span</span></div>',
554 'Attribute order, spacing and quotation marks (equal)'
558 '<div><p class="some classes" data-length="10">Child paragraph with <a href="http://example.com">A link</a></p>Regular text<span>A span</span></div>',
559 '<div><p data-length=\'10\' class=\'some more classes\'>Child paragraph with <a href=\'http://example.com\' >A link</a></p>Regular text<span>A span</span></div>',
560 'Attribute order, spacing and quotation marks (not equal)'
564 '<label for="firstname" accesskey="f" class="important">First</label><input id="firstname" /><label for="lastname" accesskey="l" class="minor">Last</label><input id="lastname" />',
565 '<label for="firstname" accesskey="f" class="important">First</label><input id="firstname" /><label for="lastname" accesskey="l" class="minor">Last</label><input id="lastname" />',
566 'Multiple root nodes (equal)'
570 '<label for="firstname" accesskey="f" class="important">First</label><input id="firstname" /><label for="lastname" accesskey="l" class="minor">Last</label><input id="lastname" />',
571 '<label for="firstname" accesskey="f" class="important">First</label><input id="firstname" /><label for="lastname" accesskey="l" class="important" >Last</label><input id="lastname" />',
572 'Multiple root nodes (not equal, last label node is different)'
576 'fo"o<br/>b>ar',
578 'Extra escaping is equal'
583 'Text escaping (not equal)'
587 'foo<a href="http://example.com">example</a>bar',
588 'foo<a href="http://example.com">example</a>bar',
589 'Outer text nodes are compared (equal)'
593 'foo<a href="http://example.com">example</a>bar',
594 'foo<a href="http://example.com">example</a>quux',
595 'Outer text nodes are compared (last text node different)'
599 QUnit
.module( 'testrunner-after', QUnit
.newMwEnvironment() );
601 QUnit
.test( 'Teardown', function ( assert
) {
602 assert
.equal( mw
.html
.escape( '<' ), '<', 'teardown() callback was ran.' );
603 assert
.equal( mw
.config
.get( 'testVar' ), null, 'config object restored to live in next module()' );
604 assert
.equal( mw
.messages
.get( 'testMsg' ), null, 'messages object restored to live in next module()' );
607 QUnit
.module( 'testrunner-each', {
608 beforeEach: function () {
609 this.mwHtmlLive
= mw
.html
;
611 afterEach: function () {
612 mw
.html
= this.mwHtmlLive
;
615 QUnit
.test( 'beforeEach', function ( assert
) {
616 assert
.ok( this.mwHtmlLive
, 'setup() ran' );
619 QUnit
.test( 'afterEach', function ( assert
) {
620 assert
.equal( mw
.html
.escape( '<' ), '<', 'afterEach() ran' );
623 QUnit
.module( 'testrunner-each-compat', {
625 this.mwHtmlLive
= mw
.html
;
627 teardown: function () {
628 mw
.html
= this.mwHtmlLive
;
631 QUnit
.test( 'setup', function ( assert
) {
632 assert
.ok( this.mwHtmlLive
, 'setup() ran' );
635 QUnit
.test( 'teardown', function ( assert
) {
636 assert
.equal( mw
.html
.escape( '<' ), '<', 'teardown() ran' );
639 // Regression test for 'this.sandbox undefined' error, fixed by
640 // ensuring Sinon setup/teardown is not re-run on inner module.
641 QUnit
.module( 'testrunner-nested', function () {
642 QUnit
.module( 'testrunner-nested-inner', function () {
643 QUnit
.test( 'Dummy', function ( assert
) {
644 assert
.ok( true, 'Nested modules supported' );
649 }( jQuery
, mediaWiki
, QUnit
) );