2 * QUnit - A JavaScript Unit Testing Framework
4 * http://docs.jquery.com/QUnit
6 * Copyright (c) 2009 John Resig, Jörn Zaefferer
7 * Dual licensed under the MIT (MIT-LICENSE.txt)
8 * and GPL (GPL-LICENSE.txt) licenses.
15 // Initialize the configuration options
18 stats: { all: 0, bad: 0 },
19 moduleStats: { all: 0, bad: 0 },
29 var tests = id("qunit-tests"),
30 banner = id("qunit-banner"),
31 result = id("qunit-testresult");
38 banner.className = "";
42 result.parentNode.removeChild( result );
46 // call on start of module test to prepend name to all tests
47 module: function(name, testEnvironment) {
48 config.currentModule = name;
50 synchronize(function() {
51 if ( config.currentModule ) {
52 QUnit.moduleDone( config.currentModule, config.moduleStats.bad, config.moduleStats.all );
55 config.currentModule = name;
56 config.moduleTestEnvironment = testEnvironment;
57 config.moduleStats = { all: 0, bad: 0 };
59 QUnit.moduleStart( name, testEnvironment );
63 asyncTest: function(testName, expected, callback) {
64 if ( arguments.length === 2 ) {
69 QUnit.test(testName, expected, callback, true);
72 test: function(testName, expected, callback, async) {
73 var name = testName, testEnvironment, testEnvironmentArg;
75 if ( arguments.length === 2 ) {
79 // is 2nd argument a testEnvironment?
80 if ( expected && typeof expected === 'object') {
81 testEnvironmentArg = expected;
85 if ( config.currentModule ) {
86 name = config.currentModule + " module: " + name;
89 if ( !validTest(name) ) {
93 synchronize(function() {
94 QUnit.testStart( testName );
96 testEnvironment = extend({
98 teardown: function() {}
99 }, config.moduleTestEnvironment);
100 if (testEnvironmentArg) {
101 extend(testEnvironment,testEnvironmentArg);
104 // allow utility functions to access the current test environment
105 QUnit.current_testEnvironment = testEnvironment;
107 config.assertions = [];
108 config.expected = expected;
111 if ( !config.pollution ) {
115 testEnvironment.setup.call(testEnvironment);
117 QUnit.ok( false, "Setup failed on " + name + ": " + e.message );
125 callback.call(testEnvironment);
127 fail("Test " + name + " died, exception and test follows", e, callback);
128 QUnit.ok( false, "Died on test #" + (config.assertions.length + 1) + ": " + e.message );
129 // else next test will carry the responsibility
132 // Restart the tests if they're blocking
133 if ( config.blocking ) {
139 synchronize(function() {
142 testEnvironment.teardown.call(testEnvironment);
144 QUnit.ok( false, "Teardown failed on " + name + ": " + e.message );
150 fail("reset() failed, following Test " + name + ", exception and reset fn follows", e, reset);
153 if ( config.expected && config.expected != config.assertions.length ) {
154 QUnit.ok( false, "Expected " + config.expected + " assertions, but " + config.assertions.length + " were run" );
157 var good = 0, bad = 0,
158 tests = id("qunit-tests");
160 config.stats.all += config.assertions.length;
161 config.moduleStats.all += config.assertions.length;
164 var ol = document.createElement("ol");
165 ol.style.display = "none";
167 for ( var i = 0; i < config.assertions.length; i++ ) {
168 var assertion = config.assertions[i];
170 var li = document.createElement("li");
171 li.className = assertion.result ? "pass" : "fail";
172 li.appendChild(document.createTextNode(assertion.message || "(no message)"));
173 ol.appendChild( li );
175 if ( assertion.result ) {
180 config.moduleStats.bad++;
184 var b = document.createElement("strong");
185 b.innerHTML = name + " <b style='color:black;'>(<b class='fail'>" + bad + "</b>, <b class='pass'>" + good + "</b>, " + config.assertions.length + ")</b>";
187 addEvent(b, "click", function() {
188 var next = b.nextSibling, display = next.style.display;
189 next.style.display = display === "none" ? "block" : "none";
192 addEvent(b, "dblclick", function(e) {
193 var target = e && e.target ? e.target : window.event.srcElement;
194 if ( target.nodeName.toLowerCase() === "strong" ) {
195 var text = "", node = target.firstChild;
197 while ( node.nodeType === 3 ) {
198 text += node.nodeValue;
199 node = node.nextSibling;
202 text = text.replace(/(^\s*|\s*$)/g, "");
204 if ( window.location ) {
205 window.location.href = window.location.href.match(/^(.+?)(\?.*)?$/)[1] + "?" + encodeURIComponent(text);
210 var li = document.createElement("li");
211 li.className = bad ? "fail" : "pass";
213 li.appendChild( ol );
214 tests.appendChild( li );
217 var toolbar = id("qunit-testrunner-toolbar");
219 toolbar.style.display = "block";
220 id("qunit-filter-pass").disabled = null;
221 id("qunit-filter-missing").disabled = null;
226 for ( var i = 0; i < config.assertions.length; i++ ) {
227 if ( !config.assertions[i].result ) {
230 config.moduleStats.bad++;
235 QUnit.testDone( testName, bad, config.assertions.length );
237 if ( !window.setTimeout && !config.queue.length ) {
242 if ( window.setTimeout && !config.doneTimer ) {
243 config.doneTimer = window.setTimeout(function(){
244 if ( !config.queue.length ) {
254 * Specify the number of expected assertions to gurantee that failed test (no assertions are run at all) don't slip through.
256 expect: function(asserts) {
257 config.expected = asserts;
262 * @example ok( "asdfasdf".length > 5, "There must be at least 5 chars" );
264 ok: function(a, msg) {
267 config.assertions.push({
274 * Checks that the first two arguments are equal, with an optional message.
275 * Prints out both actual and expected values.
277 * Prefered to ok( actual == expected, message )
279 * @example equal( format("Received {0} bytes.", 2), "Received 2 bytes." );
281 * @param Object actual
282 * @param Object expected
283 * @param String message (optional)
285 equal: function(actual, expected, message) {
286 push(expected == actual, actual, expected, message);
289 notEqual: function(actual, expected, message) {
290 push(expected != actual, actual, expected, message);
293 deepEqual: function(a, b, message) {
294 push(QUnit.equiv(a, b), a, b, message);
297 notDeepEqual: function(a, b, message) {
298 push(!QUnit.equiv(a, b), a, b, message);
301 strictEqual: function(actual, expected, message) {
302 push(expected === actual, actual, expected, message);
305 notStrictEqual: function(actual, expected, message) {
306 push(expected !== actual, actual, expected, message);
310 // A slight delay, to avoid any current callbacks
311 if ( window.setTimeout ) {
312 window.setTimeout(function() {
313 if ( config.timeout ) {
314 clearTimeout(config.timeout);
317 config.blocking = false;
321 config.blocking = false;
326 stop: function(timeout) {
327 config.blocking = true;
329 if ( timeout && window.setTimeout ) {
330 config.timeout = window.setTimeout(function() {
331 QUnit.ok( false, "Test timed out" );
338 * Resets the test setup. Useful for tests that modify the DOM.
341 if ( window.jQuery ) {
342 jQuery("#main").html( config.fixture );
343 jQuery.event.global = {};
344 jQuery.ajaxSettings = extend({}, config.ajaxSettings);
349 * Trigger an event on an element.
351 * @example triggerEvent( document.body, "click" );
353 * @param DOMElement elem
356 triggerEvent: function( elem, type, event ) {
357 if ( document.createEvent ) {
358 event = document.createEvent("MouseEvents");
359 event.initMouseEvent(type, true, true, elem.ownerDocument.defaultView,
360 0, 0, 0, 0, 0, false, false, false, false, 0, null);
361 elem.dispatchEvent( event );
363 } else if ( elem.fireEvent ) {
364 elem.fireEvent("on"+type);
368 // Safe object type checking
369 is: function( type, obj ) {
370 return Object.prototype.toString.call( obj ) === "[object "+ type +"]";
374 done: function(failures, total) {},
375 log: function(result, message) {},
376 testStart: function(name) {},
377 testDone: function(name, failures, total) {},
378 moduleStart: function(name, testEnvironment) {},
379 moduleDone: function(name, failures, total) {}
382 // Backwards compatibility, deprecated
383 QUnit.equals = QUnit.equal;
384 QUnit.same = QUnit.deepEqual;
386 // Maintain internal state
388 // The queue of tests to run
391 // block until document ready
397 var location = window.location || { search: "", protocol: "file:" },
398 GETParams = location.search.slice(1).split('&');
400 for ( var i = 0; i < GETParams.length; i++ ) {
401 GETParams[i] = decodeURIComponent( GETParams[i] );
402 if ( GETParams[i] === "noglobals" ) {
403 GETParams.splice( i, 1 );
405 config.noglobals = true;
406 } else if ( GETParams[i].search('=') > -1 ) {
407 GETParams.splice( i, 1 );
412 // restrict modules/tests by get parameters
413 config.filters = GETParams;
415 // Figure out if we're running the tests from a server or not
416 QUnit.isLocal = !!(location.protocol === 'file:');
419 // Expose the API as global variables, unless an 'exports'
420 // object exists, in that case we assume we're in CommonJS
421 if ( typeof exports === "undefined" || typeof require === "undefined" ) {
422 extend(window, QUnit);
423 window.QUnit = QUnit;
425 extend(exports, QUnit);
426 exports.QUnit = QUnit;
429 if ( typeof document === "undefined" || document.readyState === "complete" ) {
430 config.autorun = true;
433 addEvent(window, "load", function() {
434 // Initialize the config, saving the execution queue
435 var oldconfig = extend({}, config);
437 extend(config, oldconfig);
439 config.blocking = false;
441 var userAgent = id("qunit-userAgent");
443 userAgent.innerHTML = navigator.userAgent;
446 var toolbar = id("qunit-testrunner-toolbar");
448 toolbar.style.display = "none";
450 var filter = document.createElement("input");
451 filter.type = "checkbox";
452 filter.id = "qunit-filter-pass";
453 filter.disabled = true;
454 addEvent( filter, "click", function() {
455 var li = document.getElementsByTagName("li");
456 for ( var i = 0; i < li.length; i++ ) {
457 if ( li[i].className.indexOf("pass") > -1 ) {
458 li[i].style.display = filter.checked ? "none" : "";
462 toolbar.appendChild( filter );
464 var label = document.createElement("label");
465 label.setAttribute("for", "qunit-filter-pass");
466 label.innerHTML = "Hide passed tests";
467 toolbar.appendChild( label );
469 var missing = document.createElement("input");
470 missing.type = "checkbox";
471 missing.id = "qunit-filter-missing";
472 missing.disabled = true;
473 addEvent( missing, "click", function() {
474 var li = document.getElementsByTagName("li");
475 for ( var i = 0; i < li.length; i++ ) {
476 if ( li[i].className.indexOf("fail") > -1 && li[i].innerHTML.indexOf('missing test - untested code is broken code') > - 1 ) {
477 li[i].parentNode.parentNode.style.display = missing.checked ? "none" : "block";
481 toolbar.appendChild( missing );
483 label = document.createElement("label");
484 label.setAttribute("for", "qunit-filter-missing");
485 label.innerHTML = "Hide missing tests (untested code is broken code)";
486 toolbar.appendChild( label );
489 var main = id('main');
491 config.fixture = main.innerHTML;
494 if ( window.jQuery ) {
495 config.ajaxSettings = window.jQuery.ajaxSettings;
502 if ( config.doneTimer && window.clearTimeout ) {
503 window.clearTimeout( config.doneTimer );
504 config.doneTimer = null;
507 if ( config.queue.length ) {
508 config.doneTimer = window.setTimeout(function(){
509 if ( !config.queue.length ) {
519 config.autorun = true;
521 // Log the last module results
522 if ( config.currentModule ) {
523 QUnit.moduleDone( config.currentModule, config.moduleStats.bad, config.moduleStats.all );
526 var banner = id("qunit-banner"),
527 tests = id("qunit-tests"),
528 html = ['Tests completed in ',
529 +new Date - config.started, ' milliseconds.<br/>',
530 '<span class="passed">', config.stats.all - config.stats.bad, '</span> tests of <span class="total">', config.stats.all, '</span> passed, <span class="failed">', config.stats.bad,'</span> failed.'].join('');
533 banner.className = (config.stats.bad ? "qunit-fail" : "qunit-pass");
537 var result = id("qunit-testresult");
540 result = document.createElement("p");
541 result.id = "qunit-testresult";
542 result.className = "result";
543 tests.parentNode.insertBefore( result, tests.nextSibling );
546 result.innerHTML = html;
549 QUnit.done( config.stats.bad, config.stats.all );
552 function validTest( name ) {
553 var i = config.filters.length,
561 var filter = config.filters[i],
562 not = filter.charAt(0) == '!';
565 filter = filter.slice(1);
568 if ( name.indexOf(filter) !== -1 ) {
580 function push(result, actual, expected, message) {
581 message = message || (result ? "okay" : "failed");
582 QUnit.ok( result, result ? message + ": " + QUnit.jsDump.parse(expected) : message + ", expected: " + QUnit.jsDump.parse(expected) + " result: " + QUnit.jsDump.parse(actual) );
585 function synchronize( callback ) {
586 config.queue.push( callback );
588 if ( config.autorun && !config.blocking ) {
594 var start = (new Date()).getTime();
596 while ( config.queue.length && !config.blocking ) {
597 if ( config.updateRate <= 0 || (((new Date()).getTime() - start) < config.updateRate) ) {
598 config.queue.shift()();
601 setTimeout( process, 13 );
607 function saveGlobal() {
608 config.pollution = [];
610 if ( config.noglobals ) {
611 for ( var key in window ) {
612 config.pollution.push( key );
617 function checkPollution( name ) {
618 var old = config.pollution;
621 var newGlobals = diff( old, config.pollution );
622 if ( newGlobals.length > 0 ) {
623 ok( false, "Introduced global variable(s): " + newGlobals.join(", ") );
627 var deletedGlobals = diff( config.pollution, old );
628 if ( deletedGlobals.length > 0 ) {
629 ok( false, "Deleted global variable(s): " + deletedGlobals.join(", ") );
634 // returns a new Array with the elements that are in a but not in b
635 function diff( a, b ) {
636 var result = a.slice();
637 for ( var i = 0; i < result.length; i++ ) {
638 for ( var j = 0; j < b.length; j++ ) {
639 if ( result[i] === b[j] ) {
649 function fail(message, exception, callback) {
650 if ( typeof console !== "undefined" && console.error && console.warn ) {
651 console.error(message);
652 console.error(exception);
653 console.warn(callback.toString());
655 } else if ( window.opera && opera.postError ) {
656 opera.postError(message, exception, callback.toString);
660 function extend(a, b) {
661 for ( var prop in b ) {
668 function addEvent(elem, type, fn) {
669 if ( elem.addEventListener ) {
670 elem.addEventListener( type, fn, false );
671 } else if ( elem.attachEvent ) {
672 elem.attachEvent( "on" + type, fn );
679 return !!(typeof document !== "undefined" && document && document.getElementById) &&
680 document.getElementById( name );
683 // Test for equality any JavaScript type.
684 // Discussions and reference: http://philrathe.com/articles/equiv
685 // Test suites: http://philrathe.com/tests/equiv
686 // Author: Philippe Rathé <prathe@gmail.com>
687 QUnit.equiv = function () {
689 var innerEquiv; // the real equiv function
690 var callers = []; // stack to decide between skip/abort functions
691 var parents = []; // stack to avoiding loops from circular referencing
694 // Determine what is o.
696 if (QUnit.is("String", o)) {
699 } else if (QUnit.is("Boolean", o)) {
702 } else if (QUnit.is("Number", o)) {
710 } else if (typeof o === "undefined") {
713 // consider: typeof null === object
714 } else if (o === null) {
717 // consider: typeof [] === object
718 } else if (QUnit.is( "Array", o)) {
721 // consider: typeof new Date() === object
722 } else if (QUnit.is( "Date", o)) {
725 // consider: /./ instanceof Object;
726 // /./ instanceof RegExp;
727 // typeof /./ === "function"; // => false in IE and Opera,
728 // true in FF and Safari
729 } else if (QUnit.is( "RegExp", o)) {
732 } else if (typeof o === "object") {
735 } else if (QUnit.is( "Function", o)) {
742 // Call the o related callback with the given arguments.
743 function bindCallbacks(o, callbacks, args) {
744 var prop = hoozit(o);
746 if (hoozit(callbacks[prop]) === "function") {
747 return callbacks[prop].apply(callbacks, args);
749 return callbacks[prop]; // or undefined
754 var callbacks = function () {
756 // for string, boolean, number and null
757 function useStrictEquality(b, a) {
758 if (b instanceof a.constructor || a instanceof b.constructor) {
759 // to catch short annotaion VS 'new' annotation of a declaration
761 // var j = new Number(1);
769 "string": useStrictEquality,
770 "boolean": useStrictEquality,
771 "number": useStrictEquality,
772 "null": useStrictEquality,
773 "undefined": useStrictEquality,
775 "nan": function (b) {
779 "date": function (b, a) {
780 return hoozit(b) === "date" && a.valueOf() === b.valueOf();
783 "regexp": function (b, a) {
784 return hoozit(b) === "regexp" &&
785 a.source === b.source && // the regex itself
786 a.global === b.global && // and its modifers (gmi) ...
787 a.ignoreCase === b.ignoreCase &&
788 a.multiline === b.multiline;
791 // - skip when the property is a method of an instance (OOP)
792 // - abort otherwise,
793 // initial === would have catch identical references anyway
794 "function": function () {
795 var caller = callers[callers.length - 1];
796 return caller !== Object &&
797 typeof caller !== "undefined";
800 "array": function (b, a) {
804 // b could be an object literal here
805 if ( ! (hoozit(b) === "array")) {
810 if (len !== b.length) { // safe and faster
814 //track reference to avoid circular references
816 for (i = 0; i < len; i++) {
818 for(j=0;j<parents.length;j++){
819 if(parents[j] === a[i]){
820 loop = true;//dont rewalk array
823 if (!loop && ! innerEquiv(a[i], b[i])) {
832 "object": function (b, a) {
834 var eq = true; // unless we can proove it
835 var aProperties = [], bProperties = []; // collection of strings
837 // comparing constructors is more strict than using instanceof
838 if ( a.constructor !== b.constructor) {
842 // stack constructor before traversing properties
843 callers.push(a.constructor);
844 //track reference to avoid circular references
847 for (i in a) { // be strict: don't ensures hasOwnProperty and go deep
849 for(j=0;j<parents.length;j++){
850 if(parents[j] === a[i])
851 loop = true; //don't go down the same path twice
853 aProperties.push(i); // collect a's properties
855 if (!loop && ! innerEquiv(a[i], b[i])) {
861 callers.pop(); // unstack, we are done
865 bProperties.push(i); // collect b's properties
868 // Ensures identical properties name
869 return eq && innerEquiv(aProperties.sort(), bProperties.sort());
874 innerEquiv = function () { // can take multiple arguments
875 var args = Array.prototype.slice.apply(arguments);
876 if (args.length < 2) {
877 return true; // end transition
880 return (function (a, b) {
882 return true; // catch the most you can
883 } else if (a === null || b === null || typeof a === "undefined" || typeof b === "undefined" || hoozit(a) !== hoozit(b)) {
884 return false; // don't lose time with error prone cases
886 return bindCallbacks(a, callbacks, [b, a]);
889 // apply transition with (1..n) arguments
890 })(args[0], args[1]) && arguments.callee.apply(this, args.splice(1, args.length -1));
899 * Copyright (c) 2008 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com
900 * Licensed under BSD (http://www.opensource.org/licenses/bsd-license.php)
902 * @projectDescription Advanced and extensible data dumping for Javascript.
904 * @author Ariel Flesler
905 * @link {http://flesler.blogspot.com/2008/05/jsdump-pretty-dump-of-any-javascript.html}
907 QUnit.jsDump = (function() {
908 function quote( str ) {
909 return '"' + str.toString().replace(/"/g, '\\"') + '"';
911 function literal( o ) {
914 function join( pre, arr, post ) {
915 var s = jsDump.separator(),
916 base = jsDump.indent(),
917 inner = jsDump.indent(1);
919 arr = arr.join( ',' + s + inner );
922 return [ pre, inner + arr, base + post ].join(s);
924 function array( arr ) {
925 var i = arr.length, ret = Array(i);
928 ret[i] = this.parse( arr[i] );
930 return join( '[', ret, ']' );
933 var reName = /^function (\w+)/;
936 parse:function( obj, type ) { //type is used mostly internally, you can fix a (custom)type in advance
937 var parser = this.parsers[ type || this.typeOf(obj) ];
938 type = typeof parser;
940 return type == 'function' ? parser.call( this, obj ) :
941 type == 'string' ? parser :
944 typeOf:function( obj ) {
946 if ( obj === null ) {
948 } else if (typeof obj === "undefined") {
950 } else if (QUnit.is("RegExp", obj)) {
952 } else if (QUnit.is("Date", obj)) {
954 } else if (QUnit.is("Function", obj)) {
956 } else if (obj.setInterval && obj.document && !obj.nodeType) {
958 } else if (obj.nodeType === 9) {
960 } else if (obj.nodeType) {
962 } else if (typeof obj === "object" && typeof obj.length === "number" && obj.length >= 0) {
969 separator:function() {
970 return this.multiline ? this.HTML ? '<br />' : '\n' : this.HTML ? ' ' : ' ';
972 indent:function( extra ) {// extra can be a number, shortcut for increasing-calling-decreasing
973 if ( !this.multiline )
975 var chr = this.indentChar;
977 chr = chr.replace(/\t/g,' ').replace(/ /g,' ');
978 return Array( this._depth_ + (extra||0) ).join(chr);
981 this._depth_ += a || 1;
984 this._depth_ -= a || 1;
986 setParser:function( name, parser ) {
987 this.parsers[name] = parser;
989 // The next 3 are exposed so you can use them
995 // This is the list of parsers, to modify them, use jsDump.setParser
998 document: '[Document]',
999 error:'[ERROR]', //when no parser is found, shouldn't happen
1000 unknown: '[Unknown]',
1002 undefined:'undefined',
1003 'function':function( fn ) {
1004 var ret = 'function',
1005 name = 'name' in fn ? fn.name : (reName.exec(fn)||[])[1];//functions never have name in IE
1010 ret = [ ret, this.parse( fn, 'functionArgs' ), '){'].join('');
1011 return join( ret, this.parse(fn,'functionCode'), '}' );
1016 object:function( map ) {
1019 for ( var key in map )
1020 ret.push( this.parse(key,'key') + ': ' + this.parse(map[key]) );
1022 return join( '{', ret, '}' );
1024 node:function( node ) {
1025 var open = this.HTML ? '<' : '<',
1026 close = this.HTML ? '>' : '>';
1028 var tag = node.nodeName.toLowerCase(),
1031 for ( var a in this.DOMAttrs ) {
1032 var val = node[this.DOMAttrs[a]];
1034 ret += ' ' + a + '=' + this.parse( val, 'attribute' );
1036 return ret + close + open + '/' + tag + close;
1038 functionArgs:function( fn ) {//function calls it internally, it's the arguments part of the function
1040 if ( !l ) return '';
1042 var args = Array(l);
1044 args[l] = String.fromCharCode(97+l);//97 is 'a'
1045 return ' ' + args.join(', ') + ' ';
1047 key:quote, //object calls it internally, the key part of an item in a map
1048 functionCode:'[code]', //function calls it internally, it's the content of the function
1049 attribute:quote, //node calls it internally, it's an html attribute value
1052 regexp:literal, //regex
1056 DOMAttrs:{//attributes to dump from nodes, name=>realName
1061 HTML:false,//if true, entities are escaped ( <, >, \t, space and \n )
1062 indentChar:' ',//indentation unit
1063 multiline:false //if true, items in a collection, are separated by a \n, else just a space.