2 * QUnit - A JavaScript Unit Testing Framework
4 * http://docs.jquery.com/QUnit
6 * Copyright (c) 2011 John Resig, Jörn Zaefferer
7 * Dual licensed under the MIT (MIT-LICENSE.txt)
8 * or GPL (GPL-LICENSE.txt) licenses.
14 setTimeout: typeof window.setTimeout !== "undefined",
15 sessionStorage: (function() {
17 return !!sessionStorage.getItem;
26 var Test = function(name, testName, expected, testEnvironmentArg, async, callback) {
28 this.testName = testName;
29 this.expected = expected;
30 this.testEnvironmentArg = testEnvironmentArg;
32 this.callback = callback;
37 var tests = id("qunit-tests");
39 var b = document.createElement("strong");
40 b.innerHTML = "Running " + this.name;
41 var li = document.createElement("li");
43 li.className = "running";
44 li.id = this.id = "test-output" + testId++;
45 tests.appendChild( li );
49 if (this.module != config.previousModule) {
50 if ( config.previousModule ) {
51 runLoggingCallbacks('moduleDone', QUnit, {
52 name: config.previousModule,
53 failed: config.moduleStats.bad,
54 passed: config.moduleStats.all - config.moduleStats.bad,
55 total: config.moduleStats.all
58 config.previousModule = this.module;
59 config.moduleStats = { all: 0, bad: 0 };
60 runLoggingCallbacks( 'moduleStart', QUnit, {
65 config.current = this;
66 this.testEnvironment = extend({
68 teardown: function() {}
69 }, this.moduleTestEnvironment);
70 if (this.testEnvironmentArg) {
71 extend(this.testEnvironment, this.testEnvironmentArg);
74 runLoggingCallbacks( 'testStart', QUnit, {
79 // allow utility functions to access the current test environment
81 QUnit.current_testEnvironment = this.testEnvironment;
84 if ( !config.pollution ) {
88 this.testEnvironment.setup.call(this.testEnvironment);
90 QUnit.ok( false, "Setup failed on " + this.testName + ": " + e.message );
98 if ( config.notrycatch ) {
99 this.callback.call(this.testEnvironment);
103 this.callback.call(this.testEnvironment);
105 fail("Test " + this.testName + " died, exception and test follows", e, this.callback);
106 QUnit.ok( false, "Died on test #" + (this.assertions.length + 1) + ": " + e.message + " - " + QUnit.jsDump.parse(e) );
107 // else next test will carry the responsibility
110 // Restart the tests if they're blocking
111 if ( config.blocking ) {
116 teardown: function() {
118 this.testEnvironment.teardown.call(this.testEnvironment);
121 QUnit.ok( false, "Teardown failed on " + this.testName + ": " + e.message );
125 if ( this.expected && this.expected != this.assertions.length ) {
126 QUnit.ok( false, "Expected " + this.expected + " assertions, but " + this.assertions.length + " were run" );
129 var good = 0, bad = 0,
130 tests = id("qunit-tests");
132 config.stats.all += this.assertions.length;
133 config.moduleStats.all += this.assertions.length;
136 var ol = document.createElement("ol");
138 for ( var i = 0; i < this.assertions.length; i++ ) {
139 var assertion = this.assertions[i];
141 var li = document.createElement("li");
142 li.className = assertion.result ? "pass" : "fail";
143 li.innerHTML = assertion.message || (assertion.result ? "okay" : "failed");
144 ol.appendChild( li );
146 if ( assertion.result ) {
151 config.moduleStats.bad++;
155 // store result when possible
156 if ( QUnit.config.reorder && defined.sessionStorage ) {
158 sessionStorage.setItem("qunit-" + this.module + "-" + this.testName, bad);
160 sessionStorage.removeItem("qunit-" + this.module + "-" + this.testName);
165 ol.style.display = "none";
168 var b = document.createElement("strong");
169 b.innerHTML = this.name + " <b class='counts'>(<b class='failed'>" + bad + "</b>, <b class='passed'>" + good + "</b>, " + this.assertions.length + ")</b>";
171 var a = document.createElement("a");
172 a.innerHTML = "Rerun";
173 a.href = QUnit.url({ filter: getText([b]).replace(/\([^)]+\)$/, "").replace(/(^\s*|\s*$)/g, "") });
175 addEvent(b, "click", function() {
176 var next = b.nextSibling.nextSibling,
177 display = next.style.display;
178 next.style.display = display === "none" ? "block" : "none";
181 addEvent(b, "dblclick", function(e) {
182 var target = e && e.target ? e.target : window.event.srcElement;
183 if ( target.nodeName.toLowerCase() == "span" || target.nodeName.toLowerCase() == "b" ) {
184 target = target.parentNode;
186 if ( window.location && target.nodeName.toLowerCase() === "strong" ) {
187 window.location = QUnit.url({ filter: getText([target]).replace(/\([^)]+\)$/, "").replace(/(^\s*|\s*$)/g, "") });
191 var li = id(this.id);
192 li.className = bad ? "fail" : "pass";
193 li.removeChild( li.firstChild );
196 li.appendChild( ol );
199 for ( var i = 0; i < this.assertions.length; i++ ) {
200 if ( !this.assertions[i].result ) {
203 config.moduleStats.bad++;
211 fail("reset() failed, following Test " + this.testName + ", exception and reset fn follows", e, QUnit.reset);
214 runLoggingCallbacks( 'testDone', QUnit, {
218 passed: this.assertions.length - bad,
219 total: this.assertions.length
225 synchronize(function() {
229 // each of these can by async
230 synchronize(function() {
233 synchronize(function() {
236 synchronize(function() {
239 synchronize(function() {
243 // defer when previous test run passed, if storage is available
244 var bad = QUnit.config.reorder && defined.sessionStorage && +sessionStorage.getItem("qunit-" + this.module + "-" + this.testName);
256 // call on start of module test to prepend name to all tests
257 module: function(name, testEnvironment) {
258 config.currentModule = name;
259 config.currentModuleTestEnviroment = testEnvironment;
262 asyncTest: function(testName, expected, callback) {
263 if ( arguments.length === 2 ) {
268 QUnit.test(testName, expected, callback, true);
271 test: function(testName, expected, callback, async) {
272 var name = '<span class="test-name">' + testName + '</span>', testEnvironmentArg;
274 if ( arguments.length === 2 ) {
278 // is 2nd argument a testEnvironment?
279 if ( expected && typeof expected === 'object') {
280 testEnvironmentArg = expected;
284 if ( config.currentModule ) {
285 name = '<span class="module-name">' + config.currentModule + "</span>: " + name;
288 if ( !validTest(config.currentModule + ": " + testName) ) {
292 var test = new Test(name, testName, expected, testEnvironmentArg, async, callback);
293 test.module = config.currentModule;
294 test.moduleTestEnvironment = config.currentModuleTestEnviroment;
299 * Specify the number of expected assertions to gurantee that failed test (no assertions are run at all) don't slip through.
301 expect: function(asserts) {
302 config.current.expected = asserts;
307 * @example ok( "asdfasdf".length > 5, "There must be at least 5 chars" );
309 ok: function(a, msg) {
315 msg = escapeInnerText(msg);
316 runLoggingCallbacks( 'log', QUnit, details );
317 config.current.assertions.push({
324 * Checks that the first two arguments are equal, with an optional message.
325 * Prints out both actual and expected values.
327 * Prefered to ok( actual == expected, message )
329 * @example equal( format("Received {0} bytes.", 2), "Received 2 bytes." );
331 * @param Object actual
332 * @param Object expected
333 * @param String message (optional)
335 equal: function(actual, expected, message) {
336 QUnit.push(expected == actual, actual, expected, message);
339 notEqual: function(actual, expected, message) {
340 QUnit.push(expected != actual, actual, expected, message);
343 deepEqual: function(actual, expected, message) {
344 QUnit.push(QUnit.equiv(actual, expected), actual, expected, message);
347 notDeepEqual: function(actual, expected, message) {
348 QUnit.push(!QUnit.equiv(actual, expected), actual, expected, message);
351 strictEqual: function(actual, expected, message) {
352 QUnit.push(expected === actual, actual, expected, message);
355 notStrictEqual: function(actual, expected, message) {
356 QUnit.push(expected !== actual, actual, expected, message);
359 raises: function(block, expected, message) {
360 var actual, ok = false;
362 if (typeof expected === 'string') {
374 // we don't want to validate thrown error
377 // expected is a regexp
378 } else if (QUnit.objectType(expected) === "regexp") {
379 ok = expected.test(actual);
380 // expected is a constructor
381 } else if (actual instanceof expected) {
383 // expected is a validation function which returns true is validation passed
384 } else if (expected.call({}, actual) === true) {
389 QUnit.ok(ok, message);
392 start: function(count) {
393 config.semaphore -= count || 1;
394 if (config.semaphore > 0) {
395 // don't start until equal number of stop-calls
398 if (config.semaphore < 0) {
399 // ignore if start is called more often then stop
400 config.semaphore = 0;
402 // A slight delay, to avoid any current callbacks
403 if ( defined.setTimeout ) {
404 window.setTimeout(function() {
405 if (config.semaphore > 0) {
408 if ( config.timeout ) {
409 clearTimeout(config.timeout);
412 config.blocking = false;
416 config.blocking = false;
421 stop: function(count) {
422 config.semaphore += count || 1;
423 config.blocking = true;
425 if ( config.testTimeout && defined.setTimeout ) {
426 clearTimeout(config.timeout);
427 config.timeout = window.setTimeout(function() {
428 QUnit.ok( false, "Test timed out" );
429 config.semaphore = 1;
431 }, config.testTimeout);
436 //We want access to the constructor's prototype
441 //Make F QUnit's constructor so that we can add to the prototype later
442 QUnit.constructor = F;
445 // Backwards compatibility, deprecated
446 QUnit.equals = QUnit.equal;
447 QUnit.same = QUnit.deepEqual;
449 // Maintain internal state
451 // The queue of tests to run
454 // block until document ready
457 // when enabled, show only failing tests
458 // gets persisted through sessionStorage and can be changed in UI via checkbox
461 // by default, run previously failed tests first
462 // very useful in combination with "Hide passed tests" checked
465 // by default, modify document.title when suite is done
468 urlConfig: ['noglobals', 'notrycatch'],
470 //logging callback queues
482 var location = window.location || { search: "", protocol: "file:" },
483 params = location.search.slice( 1 ).split( "&" ),
484 length = params.length,
489 for ( var i = 0; i < length; i++ ) {
490 current = params[ i ].split( "=" );
491 current[ 0 ] = decodeURIComponent( current[ 0 ] );
492 // allow just a key to turn on a flag, e.g., test.html?noglobals
493 current[ 1 ] = current[ 1 ] ? decodeURIComponent( current[ 1 ] ) : true;
494 urlParams[ current[ 0 ] ] = current[ 1 ];
498 QUnit.urlParams = urlParams;
499 config.filter = urlParams.filter;
501 // Figure out if we're running the tests from a server or not
502 QUnit.isLocal = !!(location.protocol === 'file:');
505 // Expose the API as global variables, unless an 'exports'
506 // object exists, in that case we assume we're in CommonJS
507 if ( typeof exports === "undefined" || typeof require === "undefined" ) {
508 extend(window, QUnit);
509 window.QUnit = QUnit;
511 extend(exports, QUnit);
512 exports.QUnit = QUnit;
515 // define these after exposing globals to keep them in these QUnit namespace only
519 // Initialize the configuration options
522 stats: { all: 0, bad: 0 },
523 moduleStats: { all: 0, bad: 0 },
534 var tests = id( "qunit-tests" ),
535 banner = id( "qunit-banner" ),
536 result = id( "qunit-testresult" );
539 tests.innerHTML = "";
543 banner.className = "";
547 result.parentNode.removeChild( result );
551 result = document.createElement( "p" );
552 result.id = "qunit-testresult";
553 result.className = "result";
554 tests.parentNode.insertBefore( result, tests );
555 result.innerHTML = 'Running...<br/> ';
560 * Resets the test setup. Useful for tests that modify the DOM.
562 * If jQuery is available, uses jQuery's html(), otherwise just innerHTML.
565 if ( window.jQuery ) {
566 jQuery( "#qunit-fixture" ).html( config.fixture );
568 var main = id( 'qunit-fixture' );
570 main.innerHTML = config.fixture;
576 * Trigger an event on an element.
578 * @example triggerEvent( document.body, "click" );
580 * @param DOMElement elem
583 triggerEvent: function( elem, type, event ) {
584 if ( document.createEvent ) {
585 event = document.createEvent("MouseEvents");
586 event.initMouseEvent(type, true, true, elem.ownerDocument.defaultView,
587 0, 0, 0, 0, 0, false, false, false, false, 0, null);
588 elem.dispatchEvent( event );
590 } else if ( elem.fireEvent ) {
591 elem.fireEvent("on"+type);
595 // Safe object type checking
596 is: function( type, obj ) {
597 return QUnit.objectType( obj ) == type;
600 objectType: function( obj ) {
601 if (typeof obj === "undefined") {
604 // consider: typeof null === object
610 var type = Object.prototype.toString.call( obj )
611 .match(/^\[object\s(.*)\]$/)[1] || '';
626 return type.toLowerCase();
628 if (typeof obj === "object") {
634 push: function(result, actual, expected, message) {
642 message = escapeInnerText(message) || (result ? "okay" : "failed");
643 message = '<span class="test-message">' + message + "</span>";
644 expected = escapeInnerText(QUnit.jsDump.parse(expected));
645 actual = escapeInnerText(QUnit.jsDump.parse(actual));
646 var output = message + '<table><tr class="test-expected"><th>Expected: </th><td><pre>' + expected + '</pre></td></tr>';
647 if (actual != expected) {
648 output += '<tr class="test-actual"><th>Result: </th><td><pre>' + actual + '</pre></td></tr>';
649 output += '<tr class="test-diff"><th>Diff: </th><td><pre>' + QUnit.diff(expected, actual) +'</pre></td></tr>';
652 var source = sourceFromStacktrace();
654 details.source = source;
655 output += '<tr class="test-source"><th>Source: </th><td><pre>' + escapeInnerText(source) + '</pre></td></tr>';
658 output += "</table>";
660 runLoggingCallbacks( 'log', QUnit, details );
662 config.current.assertions.push({
668 url: function( params ) {
669 params = extend( extend( {}, QUnit.urlParams ), params );
670 var querystring = "?",
672 for ( key in params ) {
673 querystring += encodeURIComponent( key ) + "=" +
674 encodeURIComponent( params[ key ] ) + "&";
676 return window.location.pathname + querystring.slice( 0, -1 );
684 //QUnit.constructor is set to the empty F() above so that we can add to it's prototype later
685 //Doing this allows us to tell if the following methods have been overwritten on the actual
686 //QUnit object, which is a deprecated way of using the callbacks.
687 extend(QUnit.constructor.prototype, {
688 // Logging callbacks; all receive a single argument with the listed properties
689 // run test/logs.html for any related changes
690 begin: registerLoggingCallback('begin'),
691 // done: { failed, passed, total, runtime }
692 done: registerLoggingCallback('done'),
693 // log: { result, actual, expected, message }
694 log: registerLoggingCallback('log'),
695 // testStart: { name }
696 testStart: registerLoggingCallback('testStart'),
697 // testDone: { name, failed, passed, total }
698 testDone: registerLoggingCallback('testDone'),
699 // moduleStart: { name }
700 moduleStart: registerLoggingCallback('moduleStart'),
701 // moduleDone: { name, failed, passed, total }
702 moduleDone: registerLoggingCallback('moduleDone')
705 if ( typeof document === "undefined" || document.readyState === "complete" ) {
706 config.autorun = true;
709 QUnit.load = function() {
710 runLoggingCallbacks( 'begin', QUnit, {} );
712 // Initialize the config, saving the execution queue
713 var oldconfig = extend({}, config);
715 extend(config, oldconfig);
717 config.blocking = false;
719 var urlConfigHtml = '', len = config.urlConfig.length;
720 for ( var i = 0, val; i < len, val = config.urlConfig[i]; i++ ) {
721 config[val] = QUnit.urlParams[val];
722 urlConfigHtml += '<label><input name="' + val + '" type="checkbox"' + ( config[val] ? ' checked="checked"' : '' ) + '>' + val + '</label>';
725 var userAgent = id("qunit-userAgent");
727 userAgent.innerHTML = navigator.userAgent;
729 var banner = id("qunit-header");
731 banner.innerHTML = '<a href="' + QUnit.url({ filter: undefined }) + '"> ' + banner.innerHTML + '</a> ' + urlConfigHtml;
732 addEvent( banner, "change", function( event ) {
734 params[ event.target.name ] = event.target.checked ? true : undefined;
735 window.location = QUnit.url( params );
739 var toolbar = id("qunit-testrunner-toolbar");
741 var filter = document.createElement("input");
742 filter.type = "checkbox";
743 filter.id = "qunit-filter-pass";
744 addEvent( filter, "click", function() {
745 var ol = document.getElementById("qunit-tests");
746 if ( filter.checked ) {
747 ol.className = ol.className + " hidepass";
749 var tmp = " " + ol.className.replace( /[\n\t\r]/g, " " ) + " ";
750 ol.className = tmp.replace(/ hidepass /, " ");
752 if ( defined.sessionStorage ) {
753 if (filter.checked) {
754 sessionStorage.setItem("qunit-filter-passed-tests", "true");
756 sessionStorage.removeItem("qunit-filter-passed-tests");
760 if ( config.hidepassed || defined.sessionStorage && sessionStorage.getItem("qunit-filter-passed-tests") ) {
761 filter.checked = true;
762 var ol = document.getElementById("qunit-tests");
763 ol.className = ol.className + " hidepass";
765 toolbar.appendChild( filter );
767 var label = document.createElement("label");
768 label.setAttribute("for", "qunit-filter-pass");
769 label.innerHTML = "Hide passed tests";
770 toolbar.appendChild( label );
773 var main = id('qunit-fixture');
775 config.fixture = main.innerHTML;
778 if (config.autostart) {
783 addEvent(window, "load", QUnit.load);
786 config.autorun = true;
788 // Log the last module results
789 if ( config.currentModule ) {
790 runLoggingCallbacks( 'moduleDone', QUnit, {
791 name: config.currentModule,
792 failed: config.moduleStats.bad,
793 passed: config.moduleStats.all - config.moduleStats.bad,
794 total: config.moduleStats.all
798 var banner = id("qunit-banner"),
799 tests = id("qunit-tests"),
800 runtime = +new Date - config.started,
801 passed = config.stats.all - config.stats.bad,
803 'Tests completed in ',
805 ' milliseconds.<br/>',
806 '<span class="passed">',
808 '</span> tests of <span class="total">',
810 '</span> passed, <span class="failed">',
816 banner.className = (config.stats.bad ? "qunit-fail" : "qunit-pass");
820 id( "qunit-testresult" ).innerHTML = html;
823 if ( config.altertitle && typeof document !== "undefined" && document.title ) {
824 // show ✖ for good, ✔ for bad suite result in title
825 // use escape sequences in case file gets loaded with non-utf-8-charset
827 (config.stats.bad ? "\u2716" : "\u2714"),
828 document.title.replace(/^[\u2714\u2716] /i, "")
832 runLoggingCallbacks( 'done', QUnit, {
833 failed: config.stats.bad,
835 total: config.stats.all,
840 function validTest( name ) {
841 var filter = config.filter,
848 var not = filter.charAt( 0 ) === "!";
850 filter = filter.slice( 1 );
853 if ( name.indexOf( filter ) !== -1 ) {
864 // so far supports only Firefox, Chrome and Opera (buggy)
865 // could be extended in the future to use something like https://github.com/csnover/TraceKit
866 function sourceFromStacktrace() {
872 return e.stacktrace.split("\n")[6];
873 } else if (e.stack) {
875 return e.stack.split("\n")[4];
876 } else if (e.sourceURL) {
878 // TODO sourceURL points at the 'throw new Error' line above, useless
879 //return e.sourceURL + ":" + e.line;
884 function escapeInnerText(s) {
889 return s.replace(/[\&<>]/g, function(s) {
891 case "&": return "&";
892 case "<": return "<";
893 case ">": return ">";
899 function synchronize( callback ) {
900 config.queue.push( callback );
902 if ( config.autorun && !config.blocking ) {
908 var start = (new Date()).getTime();
910 while ( config.queue.length && !config.blocking ) {
911 if ( config.updateRate <= 0 || (((new Date()).getTime() - start) < config.updateRate) ) {
912 config.queue.shift()();
914 window.setTimeout( process, 13 );
918 if (!config.blocking && !config.queue.length) {
923 function saveGlobal() {
924 config.pollution = [];
926 if ( config.noglobals ) {
927 for ( var key in window ) {
928 config.pollution.push( key );
933 function checkPollution( name ) {
934 var old = config.pollution;
937 var newGlobals = diff( config.pollution, old );
938 if ( newGlobals.length > 0 ) {
939 ok( false, "Introduced global variable(s): " + newGlobals.join(", ") );
942 var deletedGlobals = diff( old, config.pollution );
943 if ( deletedGlobals.length > 0 ) {
944 ok( false, "Deleted global variable(s): " + deletedGlobals.join(", ") );
948 // returns a new Array with the elements that are in a but not in b
949 function diff( a, b ) {
950 var result = a.slice();
951 for ( var i = 0; i < result.length; i++ ) {
952 for ( var j = 0; j < b.length; j++ ) {
953 if ( result[i] === b[j] ) {
963 function fail(message, exception, callback) {
964 if ( typeof console !== "undefined" && console.error && console.warn ) {
965 console.error(message);
966 console.error(exception);
967 console.warn(callback.toString());
969 } else if ( window.opera && opera.postError ) {
970 opera.postError(message, exception, callback.toString);
974 function extend(a, b) {
975 for ( var prop in b ) {
976 if ( b[prop] === undefined ) {
986 function addEvent(elem, type, fn) {
987 if ( elem.addEventListener ) {
988 elem.addEventListener( type, fn, false );
989 } else if ( elem.attachEvent ) {
990 elem.attachEvent( "on" + type, fn );
997 return !!(typeof document !== "undefined" && document && document.getElementById) &&
998 document.getElementById( name );
1001 function registerLoggingCallback(key){
1002 return function(callback){
1003 config[key].push( callback );
1007 // Supports deprecated method of completely overwriting logging callbacks
1008 function runLoggingCallbacks(key, scope, args) {
1011 if ( QUnit.hasOwnProperty(key) ) {
1012 QUnit[key].call(scope, args);
1014 callbacks = config[key];
1015 for( var i = 0; i < callbacks.length; i++ ) {
1016 callbacks[i].call( scope, args );
1021 // Test for equality any JavaScript type.
1022 // Author: Philippe Rathé <prathe@gmail.com>
1023 QUnit.equiv = function () {
1025 var innerEquiv; // the real equiv function
1026 var callers = []; // stack to decide between skip/abort functions
1027 var parents = []; // stack to avoiding loops from circular referencing
1029 // Call the o related callback with the given arguments.
1030 function bindCallbacks(o, callbacks, args) {
1031 var prop = QUnit.objectType(o);
1033 if (QUnit.objectType(callbacks[prop]) === "function") {
1034 return callbacks[prop].apply(callbacks, args);
1036 return callbacks[prop]; // or undefined
1041 var callbacks = function () {
1043 // for string, boolean, number and null
1044 function useStrictEquality(b, a) {
1045 if (b instanceof a.constructor || a instanceof b.constructor) {
1046 // to catch short annotaion VS 'new' annotation of a
1049 // var j = new Number(1);
1057 "string" : useStrictEquality,
1058 "boolean" : useStrictEquality,
1059 "number" : useStrictEquality,
1060 "null" : useStrictEquality,
1061 "undefined" : useStrictEquality,
1063 "nan" : function(b) {
1067 "date" : function(b, a) {
1068 return QUnit.objectType(b) === "date"
1069 && a.valueOf() === b.valueOf();
1072 "regexp" : function(b, a) {
1073 return QUnit.objectType(b) === "regexp"
1074 && a.source === b.source && // the regex itself
1075 a.global === b.global && // and its modifers
1077 a.ignoreCase === b.ignoreCase
1078 && a.multiline === b.multiline;
1081 // - skip when the property is a method of an instance (OOP)
1082 // - abort otherwise,
1083 // initial === would have catch identical references anyway
1084 "function" : function() {
1085 var caller = callers[callers.length - 1];
1086 return caller !== Object && typeof caller !== "undefined";
1089 "array" : function(b, a) {
1093 // b could be an object literal here
1094 if (!(QUnit.objectType(b) === "array")) {
1099 if (len !== b.length) { // safe and faster
1103 // track reference to avoid circular references
1105 for (i = 0; i < len; i++) {
1107 for (j = 0; j < parents.length; j++) {
1108 if (parents[j] === a[i]) {
1109 loop = true;// dont rewalk array
1112 if (!loop && !innerEquiv(a[i], b[i])) {
1121 "object" : function(b, a) {
1123 var eq = true; // unless we can proove it
1124 var aProperties = [], bProperties = []; // collection of
1127 // comparing constructors is more strict than using
1129 if (a.constructor !== b.constructor) {
1133 // stack constructor before traversing properties
1134 callers.push(a.constructor);
1135 // track reference to avoid circular references
1138 for (i in a) { // be strict: don't ensures hasOwnProperty
1141 for (j = 0; j < parents.length; j++) {
1142 if (parents[j] === a[i])
1143 loop = true; // don't go down the same path
1146 aProperties.push(i); // collect a's properties
1148 if (!loop && !innerEquiv(a[i], b[i])) {
1154 callers.pop(); // unstack, we are done
1158 bProperties.push(i); // collect b's properties
1161 // Ensures identical properties name
1163 && innerEquiv(aProperties.sort(), bProperties
1169 innerEquiv = function() { // can take multiple arguments
1170 var args = Array.prototype.slice.apply(arguments);
1171 if (args.length < 2) {
1172 return true; // end transition
1175 return (function(a, b) {
1177 return true; // catch the most you can
1178 } else if (a === null || b === null || typeof a === "undefined"
1179 || typeof b === "undefined"
1180 || QUnit.objectType(a) !== QUnit.objectType(b)) {
1181 return false; // don't lose time with error prone cases
1183 return bindCallbacks(a, callbacks, [ b, a ]);
1186 // apply transition with (1..n) arguments
1187 })(args[0], args[1])
1188 && arguments.callee.apply(this, args.splice(1,
1197 * jsDump Copyright (c) 2008 Ariel Flesler - aflesler(at)gmail(dot)com |
1198 * http://flesler.blogspot.com Licensed under BSD
1199 * (http://www.opensource.org/licenses/bsd-license.php) Date: 5/15/2008
1201 * @projectDescription Advanced and extensible data dumping for Javascript.
1203 * @author Ariel Flesler
1204 * @link {http://flesler.blogspot.com/2008/05/jsdump-pretty-dump-of-any-javascript.html}
1206 QUnit.jsDump = (function() {
1207 function quote( str ) {
1208 return '"' + str.toString().replace(/"/g, '\\"') + '"';
1210 function literal( o ) {
1213 function join( pre, arr, post ) {
1214 var s = jsDump.separator(),
1215 base = jsDump.indent(),
1216 inner = jsDump.indent(1);
1218 arr = arr.join( ',' + s + inner );
1221 return [ pre, inner + arr, base + post ].join(s);
1223 function array( arr, stack ) {
1224 var i = arr.length, ret = Array(i);
1227 ret[i] = this.parse( arr[i] , undefined , stack);
1229 return join( '[', ret, ']' );
1232 var reName = /^function (\w+)/;
1235 parse:function( obj, type, stack ) { //type is used mostly internally, you can fix a (custom)type in advance
1236 stack = stack || [ ];
1237 var parser = this.parsers[ type || this.typeOf(obj) ];
1238 type = typeof parser;
1239 var inStack = inArray(obj, stack);
1240 if (inStack != -1) {
1241 return 'recursion('+(inStack - stack.length)+')';
1244 if (type == 'function') {
1246 var res = parser.call( this, obj, stack );
1251 return (type == 'string') ? parser : this.parsers.error;
1253 typeOf:function( obj ) {
1255 if ( obj === null ) {
1257 } else if (typeof obj === "undefined") {
1259 } else if (QUnit.is("RegExp", obj)) {
1261 } else if (QUnit.is("Date", obj)) {
1263 } else if (QUnit.is("Function", obj)) {
1265 } else if (typeof obj.setInterval !== undefined && typeof obj.document !== "undefined" && typeof obj.nodeType === "undefined") {
1267 } else if (obj.nodeType === 9) {
1269 } else if (obj.nodeType) {
1271 } else if (typeof obj === "object" && typeof obj.length === "number" && obj.length >= 0) {
1278 separator:function() {
1279 return this.multiline ? this.HTML ? '<br />' : '\n' : this.HTML ? ' ' : ' ';
1281 indent:function( extra ) {// extra can be a number, shortcut for increasing-calling-decreasing
1282 if ( !this.multiline )
1284 var chr = this.indentChar;
1286 chr = chr.replace(/\t/g,' ').replace(/ /g,' ');
1287 return Array( this._depth_ + (extra||0) ).join(chr);
1290 this._depth_ += a || 1;
1292 down:function( a ) {
1293 this._depth_ -= a || 1;
1295 setParser:function( name, parser ) {
1296 this.parsers[name] = parser;
1298 // The next 3 are exposed so you can use them
1304 // This is the list of parsers, to modify them, use jsDump.setParser
1307 document: '[Document]',
1308 error:'[ERROR]', //when no parser is found, shouldn't happen
1309 unknown: '[Unknown]',
1311 'undefined':'undefined',
1312 'function':function( fn ) {
1313 var ret = 'function',
1314 name = 'name' in fn ? fn.name : (reName.exec(fn)||[])[1];//functions never have name in IE
1319 ret = [ ret, QUnit.jsDump.parse( fn, 'functionArgs' ), '){'].join('');
1320 return join( ret, QUnit.jsDump.parse(fn,'functionCode'), '}' );
1325 object:function( map, stack ) {
1328 for ( var key in map ) {
1330 ret.push( QUnit.jsDump.parse(key,'key') + ': ' + QUnit.jsDump.parse(val, undefined, stack));
1332 QUnit.jsDump.down();
1333 return join( '{', ret, '}' );
1335 node:function( node ) {
1336 var open = QUnit.jsDump.HTML ? '<' : '<',
1337 close = QUnit.jsDump.HTML ? '>' : '>';
1339 var tag = node.nodeName.toLowerCase(),
1342 for ( var a in QUnit.jsDump.DOMAttrs ) {
1343 var val = node[QUnit.jsDump.DOMAttrs[a]];
1345 ret += ' ' + a + '=' + QUnit.jsDump.parse( val, 'attribute' );
1347 return ret + close + open + '/' + tag + close;
1349 functionArgs:function( fn ) {//function calls it internally, it's the arguments part of the function
1351 if ( !l ) return '';
1353 var args = Array(l);
1355 args[l] = String.fromCharCode(97+l);//97 is 'a'
1356 return ' ' + args.join(', ') + ' ';
1358 key:quote, //object calls it internally, the key part of an item in a map
1359 functionCode:'[code]', //function calls it internally, it's the content of the function
1360 attribute:quote, //node calls it internally, it's an html attribute value
1363 regexp:literal, //regex
1367 DOMAttrs:{//attributes to dump from nodes, name=>realName
1372 HTML:false,//if true, entities are escaped ( <, >, \t, space and \n )
1373 indentChar:' ',//indentation unit
1374 multiline:true //if true, items in a collection, are separated by a \n, else just a space.
1381 function getText( elems ) {
1384 for ( var i = 0; elems[i]; i++ ) {
1387 // Get the text from text nodes and CDATA nodes
1388 if ( elem.nodeType === 3 || elem.nodeType === 4 ) {
1389 ret += elem.nodeValue;
1391 // Traverse everything else, except comment nodes
1392 } else if ( elem.nodeType !== 8 ) {
1393 ret += getText( elem.childNodes );
1401 function inArray( elem, array ) {
1402 if ( array.indexOf ) {
1403 return array.indexOf( elem );
1406 for ( var i = 0, length = array.length; i < length; i++ ) {
1407 if ( array[ i ] === elem ) {
1416 * Javascript Diff Algorithm
1417 * By John Resig (http://ejohn.org/)
1418 * Modified by Chu Alan "sprite"
1420 * Released under the MIT license.
1423 * http://ejohn.org/projects/javascript-diff-algorithm/
1425 * Usage: QUnit.diff(expected, actual)
1427 * QUnit.diff("the quick brown fox jumped over", "the quick fox jumps over") == "the quick <del>brown </del> fox <del>jumped </del><ins>jumps </ins> over"
1429 QUnit.diff = (function() {
1430 function diff(o, n) {
1434 for (var i = 0; i < n.length; i++) {
1435 if (ns[n[i]] == null)
1440 ns[n[i]].rows.push(i);
1443 for (var i = 0; i < o.length; i++) {
1444 if (os[o[i]] == null)
1449 os[o[i]].rows.push(i);
1453 if (ns[i].rows.length == 1 && typeof(os[i]) != "undefined" && os[i].rows.length == 1) {
1454 n[ns[i].rows[0]] = {
1455 text: n[ns[i].rows[0]],
1458 o[os[i].rows[0]] = {
1459 text: o[os[i].rows[0]],
1465 for (var i = 0; i < n.length - 1; i++) {
1466 if (n[i].text != null && n[i + 1].text == null && n[i].row + 1 < o.length && o[n[i].row + 1].text == null &&
1467 n[i + 1] == o[n[i].row + 1]) {
1473 text: o[n[i].row + 1],
1479 for (var i = n.length - 1; i > 0; i--) {
1480 if (n[i].text != null && n[i - 1].text == null && n[i].row > 0 && o[n[i].row - 1].text == null &&
1481 n[i - 1] == o[n[i].row - 1]) {
1487 text: o[n[i].row - 1],
1499 return function(o, n) {
1500 o = o.replace(/\s+$/, '');
1501 n = n.replace(/\s+$/, '');
1502 var out = diff(o == "" ? [] : o.split(/\s+/), n == "" ? [] : n.split(/\s+/));
1506 var oSpace = o.match(/\s+/g);
1507 if (oSpace == null) {
1513 var nSpace = n.match(/\s+/g);
1514 if (nSpace == null) {
1521 if (out.n.length == 0) {
1522 for (var i = 0; i < out.o.length; i++) {
1523 str += '<del>' + out.o[i] + oSpace[i] + "</del>";
1527 if (out.n[0].text == null) {
1528 for (n = 0; n < out.o.length && out.o[n].text == null; n++) {
1529 str += '<del>' + out.o[n] + oSpace[n] + "</del>";
1533 for (var i = 0; i < out.n.length; i++) {
1534 if (out.n[i].text == null) {
1535 str += '<ins>' + out.n[i] + nSpace[i] + "</ins>";
1540 for (n = out.n[i].row + 1; n < out.o.length && out.o[n].text == null; n++) {
1541 pre += '<del>' + out.o[n] + oSpace[n] + "</del>";
1543 str += " " + out.n[i].text + nSpace[i] + pre;