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
, orgExecute
;
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 // Wrap executeNow() so that we can detect nested modules
91 orgExecute
= executeNow
;
92 executeNow = function () {
95 ret
= orgExecute
.apply( this, arguments
);
101 localEnv
= localEnv
|| {};
102 orgBeforeEach
= localEnv
.beforeEach
;
103 orgAfterEach
= localEnv
.afterEach
;
104 localEnv
.beforeEach = function () {
105 var config
= sinon
.getConfig( sinon
.config
);
106 config
.injectInto
= this;
107 sinon
.sandbox
.create( config
);
109 if ( orgBeforeEach
) {
110 return orgBeforeEach
.apply( this, arguments
);
113 localEnv
.afterEach = function () {
115 if ( orgAfterEach
) {
116 ret
= orgAfterEach
.apply( this, arguments
);
119 this.sandbox
.verifyAndRestore();
122 return orgModule( name
, localEnv
, executeNow
);
126 // Extend QUnit.module to provide a fixture element.
128 var orgModule
= QUnit
.module
;
129 QUnit
.module = function ( name
, localEnv
, executeNow
) {
130 var orgBeforeEach
, orgAfterEach
;
132 // In a nested module, don't re-run our handlers.
133 return orgModule
.apply( this, arguments
);
135 if ( arguments
.length
=== 2 && typeof localEnv
=== 'function' ) {
136 executeNow
= localEnv
;
137 localEnv
= undefined;
140 localEnv
= localEnv
|| {};
141 orgBeforeEach
= localEnv
.beforeEach
;
142 orgAfterEach
= localEnv
.afterEach
;
143 localEnv
.beforeEach = function () {
144 this.fixture
= document
.createElement( 'div' );
145 this.fixture
.id
= 'qunit-fixture';
146 document
.body
.appendChild( this.fixture
);
148 if ( orgBeforeEach
) {
149 return orgBeforeEach
.apply( this, arguments
);
152 localEnv
.afterEach = function () {
154 if ( orgAfterEach
) {
155 ret
= orgAfterEach
.apply( this, arguments
);
158 this.fixture
.parentNode
.removeChild( this.fixture
);
161 return orgModule( name
, localEnv
, executeNow
);
165 // Extend QUnit.module to normalise localEnv.
166 // NOTE: This MUST be the last QUnit.module extension so that the above extensions
167 // may safely modify the object and assume beforeEach/afterEach.
169 var orgModule
= QUnit
.module
;
170 QUnit
.module = function ( name
, localEnv
, executeNow
) {
171 if ( typeof localEnv
=== 'object' ) {
172 localEnv
= makeSafeEnv( localEnv
);
174 return orgModule( name
, localEnv
, executeNow
);
179 * Reset mw.config and others to a fresh copy of the live config for each test(),
180 * and restore it back to the live one afterwards.
182 * @param {Object} [localEnv]
183 * @example (see test suite at the bottom of this file)
186 QUnit
.newMwEnvironment
= ( function () {
187 var warn
, error
, liveConfig
, liveMessages
,
188 MwMap
= mw
.config
.constructor, // internal use only
191 liveConfig
= mw
.config
;
192 liveMessages
= mw
.messages
;
194 function suppressWarnings() {
195 if ( warn
=== undefined ) {
197 error
= mw
.log
.error
;
198 mw
.log
.warn
= mw
.log
.error
= $.noop
;
202 function restoreWarnings() {
203 // Guard against calls not balanced with suppressWarnings()
204 if ( warn
!== undefined ) {
206 mw
.log
.error
= error
;
207 warn
= error
= undefined;
211 function freshConfigCopy( custom
) {
213 // Tests should mock all factors that directly influence the tested code.
214 // For backwards compatibility though we set mw.config to a fresh copy of the live
215 // config. This way any modifications made to mw.config during the test will not
216 // affect other tests, nor the global scope outside the test runner.
217 // This is a shallow copy, since overriding an array or object value via "custom"
218 // should replace it. Setting a config property means you override it, not extend it.
219 // NOTE: It is important that we suppress warnings because extend() will also access
220 // deprecated properties and trigger deprecation warnings from mw.log#deprecate.
222 copy
= $.extend( {}, liveConfig
.get(), custom
);
228 function freshMessagesCopy( custom
) {
229 return $.extend( /* deep */true, {}, liveMessages
.get(), custom
);
233 * @param {jQuery.Event} event
234 * @param {jqXHR} jqXHR
235 * @param {Object} ajaxOptions
237 function trackAjax( event
, jqXHR
, ajaxOptions
) {
238 ajaxRequests
.push( { xhr
: jqXHR
, options
: ajaxOptions
} );
241 return function ( orgEnv
) {
242 var localEnv
= orgEnv
? makeSafeEnv( orgEnv
) : {};
243 // MediaWiki env testing
244 localEnv
.config
= orgEnv
&& orgEnv
.config
|| {};
245 localEnv
.messages
= orgEnv
&& orgEnv
.messages
|| {};
248 beforeEach: function () {
249 // Greetings, mock environment!
250 mw
.config
= new MwMap();
251 mw
.config
.set( freshConfigCopy( localEnv
.config
) );
252 mw
.messages
= new MwMap();
253 mw
.messages
.set( freshMessagesCopy( localEnv
.messages
) );
254 // Update reference to mw.messages
255 mw
.jqueryMsg
.setParserDefaults( {
256 messages
: mw
.messages
259 this.suppressWarnings
= suppressWarnings
;
260 this.restoreWarnings
= restoreWarnings
;
262 // Start tracking ajax requests
263 $( document
).on( 'ajaxSend', trackAjax
);
265 if ( localEnv
.beforeEach
) {
266 return localEnv
.beforeEach
.apply( this, arguments
);
270 afterEach: function () {
271 var timers
, pending
, $activeLen
, ret
;
273 if ( localEnv
.afterEach
) {
274 ret
= localEnv
.afterEach
.apply( this, arguments
);
277 // Stop tracking ajax requests
278 $( document
).off( 'ajaxSend', trackAjax
);
280 // As a convenience feature, automatically restore warnings if they're
281 // still suppressed by the end of the test.
284 // Farewell, mock environment!
285 mw
.config
= liveConfig
;
286 mw
.messages
= liveMessages
;
287 // Restore reference to mw.messages
288 mw
.jqueryMsg
.setParserDefaults( {
289 messages
: liveMessages
292 // Tests should use fake timers or wait for animations to complete
293 // Check for incomplete animations/requests/etc and throw if there are any.
294 if ( $.timers
&& $.timers
.length
!== 0 ) {
295 timers
= $.timers
.length
;
296 $.each( $.timers
, function ( i
, timer
) {
297 var node
= timer
.elem
;
298 mw
.log
.warn( 'Unfinished animation #' + i
+ ' in ' + timer
.queue
+ ' queue on ' +
299 mw
.html
.element( node
.nodeName
.toLowerCase(), $( node
).getAttrs() )
302 // Force animations to stop to give the next test a clean start
306 throw new Error( 'Unfinished animations: ' + timers
);
309 // Test should use fake XHR, wait for requests, or call abort()
310 $activeLen
= $.active
;
311 if ( $activeLen
!== undefined && $activeLen
!== 0 ) {
312 pending
= $.grep( ajaxRequests
, function ( ajax
) {
313 return ajax
.xhr
.state() === 'pending';
315 if ( pending
.length
!== $activeLen
) {
316 mw
.log
.warn( 'Pending requests does not match jQuery.active count' );
318 // Force requests to stop to give the next test a clean start
319 $.each( ajaxRequests
, function ( i
, ajax
) {
321 'AJAX request #' + i
+ ' (state: ' + ajax
.xhr
.state() + ')',
328 throw new Error( 'Pending AJAX requests: ' + pending
.length
+ ' (active: ' + $activeLen
+ ')' );
337 // $.when stops as soon as one fails, which makes sense in most
338 // practical scenarios, but not in a unit test where we really do
339 // need to wait until all of them are finished.
340 QUnit
.whenPromisesComplete = function () {
341 var altPromises
= [];
343 $.each( arguments
, function ( i
, arg
) {
344 var alt
= $.Deferred();
345 altPromises
.push( alt
);
347 // Whether this one fails or not, forwards it to
348 // the 'done' (resolve) callback of the alternative promise.
349 arg
.always( alt
.resolve
);
352 return $.when
.apply( $, altPromises
);
356 * Recursively convert a node to a plain object representing its structure.
357 * Only considers attributes and contents (elements and text nodes).
358 * Attribute values are compared strictly and not normalised.
361 * @return {Object|string} Plain JavaScript value representing the node.
363 function getDomStructure( node
) {
364 var $node
, children
, processedChildren
, i
, len
, el
;
366 if ( node
.nodeType
=== Node
.ELEMENT_NODE
) {
367 children
= $node
.contents();
368 processedChildren
= [];
369 for ( i
= 0, len
= children
.length
; i
< len
; i
++ ) {
371 if ( el
.nodeType
=== Node
.ELEMENT_NODE
|| el
.nodeType
=== Node
.TEXT_NODE
) {
372 processedChildren
.push( getDomStructure( el
) );
377 tagName
: node
.tagName
,
378 attributes
: $node
.getAttrs(),
379 contents
: processedChildren
382 // Should be text node
388 * Gets structure of node for this HTML.
390 * @param {string} html HTML markup for one or more nodes.
392 function getHtmlStructure( html
) {
393 var el
= $( '<div>' ).append( html
)[ 0 ];
394 return getDomStructure( el
);
398 * Add-on assertion helpers
400 // Define the add-ons
403 // Expect boolean true
404 assertTrue: function ( actual
, message
) {
406 result
: actual
=== true,
413 // Expect boolean false
414 assertFalse: function ( actual
, message
) {
416 result
: actual
=== false,
423 // Expect numerical value less than X
424 lt: function ( actual
, expected
, message
) {
426 result
: actual
< expected
,
428 expected
: 'less than ' + expected
,
433 // Expect numerical value less than or equal to X
434 ltOrEq: function ( actual
, expected
, message
) {
436 result
: actual
<= expected
,
438 expected
: 'less than or equal to ' + expected
,
443 // Expect numerical value greater than X
444 gt: function ( actual
, expected
, message
) {
446 result
: actual
> expected
,
448 expected
: 'greater than ' + expected
,
453 // Expect numerical value greater than or equal to X
454 gtOrEq: function ( actual
, expected
, message
) {
456 result
: actual
>= true,
458 expected
: 'greater than or equal to ' + expected
,
464 * Asserts that two HTML strings are structurally equivalent.
466 * @param {string} actualHtml Actual HTML markup.
467 * @param {string} expectedHtml Expected HTML markup
468 * @param {string} message Assertion message.
470 htmlEqual: function ( actualHtml
, expectedHtml
, message
) {
471 var actual
= getHtmlStructure( actualHtml
),
472 expected
= getHtmlStructure( expectedHtml
);
474 result
: QUnit
.equiv( actual
, expected
),
482 * Asserts that two HTML strings are not structurally equivalent.
484 * @param {string} actualHtml Actual HTML markup.
485 * @param {string} expectedHtml Expected HTML markup.
486 * @param {string} message Assertion message.
488 notHtmlEqual: function ( actualHtml
, expectedHtml
, message
) {
489 var actual
= getHtmlStructure( actualHtml
),
490 expected
= getHtmlStructure( expectedHtml
);
493 result
: !QUnit
.equiv( actual
, expected
),
502 $.extend( QUnit
.assert
, addons
);
505 * Small test suite to confirm proper functionality of the utilities and
506 * initializations defined above in this file.
508 QUnit
.module( 'testrunner', QUnit
.newMwEnvironment( {
510 this.mwHtmlLive
= mw
.html
;
512 escape: function () {
517 teardown: function () {
518 mw
.html
= this.mwHtmlLive
;
528 QUnit
.test( 'Setup', function ( assert
) {
529 assert
.equal( mw
.html
.escape( 'foo' ), 'mocked', 'setup() callback was ran.' );
530 assert
.equal( mw
.config
.get( 'testVar' ), 'foo', 'config object applied' );
531 assert
.equal( mw
.messages
.get( 'testMsg' ), 'Foo.', 'messages object applied' );
533 mw
.config
.set( 'testVar', 'bar' );
534 mw
.messages
.set( 'testMsg', 'Bar.' );
537 QUnit
.test( 'Teardown', function ( assert
) {
538 assert
.equal( mw
.config
.get( 'testVar' ), 'foo', 'config object restored and re-applied after test()' );
539 assert
.equal( mw
.messages
.get( 'testMsg' ), 'Foo.', 'messages object restored and re-applied after test()' );
542 QUnit
.test( 'Loader status', function ( assert
) {
544 modules
= mw
.loader
.getModuleNames(),
548 for ( i
= 0, len
= modules
.length
; i
< len
; i
++ ) {
549 state
= mw
.loader
.getState( modules
[ i
] );
550 if ( state
=== 'error' ) {
551 error
.push( modules
[ i
] );
552 } else if ( state
=== 'missing' ) {
553 missing
.push( modules
[ i
] );
557 assert
.deepEqual( error
, [], 'Modules in error state' );
558 assert
.deepEqual( missing
, [], 'Modules in missing state' );
561 QUnit
.test( 'assert.htmlEqual', function ( assert
) {
563 '<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>',
564 '<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>',
565 'Attribute order, spacing and quotation marks (equal)'
569 '<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>',
570 '<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>',
571 'Attribute order, spacing and quotation marks (not equal)'
575 '<label for="firstname" accesskey="f" class="important">First</label><input id="firstname" /><label for="lastname" accesskey="l" class="minor">Last</label><input id="lastname" />',
576 '<label for="firstname" accesskey="f" class="important">First</label><input id="firstname" /><label for="lastname" accesskey="l" class="minor">Last</label><input id="lastname" />',
577 'Multiple root nodes (equal)'
581 '<label for="firstname" accesskey="f" class="important">First</label><input id="firstname" /><label for="lastname" accesskey="l" class="minor">Last</label><input id="lastname" />',
582 '<label for="firstname" accesskey="f" class="important">First</label><input id="firstname" /><label for="lastname" accesskey="l" class="important" >Last</label><input id="lastname" />',
583 'Multiple root nodes (not equal, last label node is different)'
587 'fo"o<br/>b>ar',
589 'Extra escaping is equal'
594 'Text escaping (not equal)'
598 'foo<a href="http://example.com">example</a>bar',
599 'foo<a href="http://example.com">example</a>bar',
600 'Outer text nodes are compared (equal)'
604 'foo<a href="http://example.com">example</a>bar',
605 'foo<a href="http://example.com">example</a>quux',
606 'Outer text nodes are compared (last text node different)'
610 QUnit
.module( 'testrunner-after', QUnit
.newMwEnvironment() );
612 QUnit
.test( 'Teardown', function ( assert
) {
613 assert
.equal( mw
.html
.escape( '<' ), '<', 'teardown() callback was ran.' );
614 assert
.equal( mw
.config
.get( 'testVar' ), null, 'config object restored to live in next module()' );
615 assert
.equal( mw
.messages
.get( 'testMsg' ), null, 'messages object restored to live in next module()' );
618 QUnit
.module( 'testrunner-each', {
619 beforeEach: function () {
620 this.mwHtmlLive
= mw
.html
;
622 afterEach: function () {
623 mw
.html
= this.mwHtmlLive
;
626 QUnit
.test( 'beforeEach', function ( assert
) {
627 assert
.ok( this.mwHtmlLive
, 'setup() ran' );
630 QUnit
.test( 'afterEach', function ( assert
) {
631 assert
.equal( mw
.html
.escape( '<' ), '<', 'afterEach() ran' );
634 QUnit
.module( 'testrunner-each-compat', {
636 this.mwHtmlLive
= mw
.html
;
638 teardown: function () {
639 mw
.html
= this.mwHtmlLive
;
642 QUnit
.test( 'setup', function ( assert
) {
643 assert
.ok( this.mwHtmlLive
, 'setup() ran' );
646 QUnit
.test( 'teardown', function ( assert
) {
647 assert
.equal( mw
.html
.escape( '<' ), '<', 'teardown() ran' );
650 // Regression test for 'this.sandbox undefined' error, fixed by
651 // ensuring Sinon setup/teardown is not re-run on inner module.
652 QUnit
.module( 'testrunner-nested', function () {
653 QUnit
.module( 'testrunner-nested-inner', function () {
654 QUnit
.test( 'Dummy', function ( assert
) {
655 assert
.ok( true, 'Nested modules supported' );
660 }( jQuery
, mediaWiki
, QUnit
) );