2 * QUnit 1.1.0pre - 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;
25 toString = Object.prototype.toString,
26 hasOwn = Object.prototype.hasOwnProperty;
28 var Test = function(name, testName, expected, testEnvironmentArg, async, callback) {
30 this.testName = testName;
31 this.expected = expected;
32 this.testEnvironmentArg = testEnvironmentArg;
34 this.callback = callback;
39 var tests = id("qunit-tests");
41 var b = document.createElement("strong");
42 b.innerHTML = "Running " + this.name;
43 var li = document.createElement("li");
45 li.className = "running";
46 li.id = this.id = "test-output" + testId++;
47 tests.appendChild( li );
51 if (this.module != config.previousModule) {
52 if ( config.previousModule ) {
53 runLoggingCallbacks('moduleDone', QUnit, {
54 name: config.previousModule,
55 failed: config.moduleStats.bad,
56 passed: config.moduleStats.all - config.moduleStats.bad,
57 total: config.moduleStats.all
60 config.previousModule = this.module;
61 config.moduleStats = { all: 0, bad: 0 };
62 runLoggingCallbacks( 'moduleStart', QUnit, {
67 config.current = this;
68 this.testEnvironment = extend({
70 teardown: function() {}
71 }, this.moduleTestEnvironment);
72 if (this.testEnvironmentArg) {
73 extend(this.testEnvironment, this.testEnvironmentArg);
76 runLoggingCallbacks( 'testStart', QUnit, {
81 // allow utility functions to access the current test environment
83 QUnit.current_testEnvironment = this.testEnvironment;
86 if ( !config.pollution ) {
90 this.testEnvironment.setup.call(this.testEnvironment);
92 QUnit.ok( false, "Setup failed on " + this.testName + ": " + e.message );
100 if ( config.notrycatch ) {
101 this.callback.call(this.testEnvironment);
105 this.callback.call(this.testEnvironment);
107 fail("Test " + this.testName + " died, exception and test follows", e, this.callback);
108 QUnit.ok( false, "Died on test #" + (this.assertions.length + 1) + ": " + e.message + " - " + QUnit.jsDump.parse(e) );
109 // else next test will carry the responsibility
112 // Restart the tests if they're blocking
113 if ( config.blocking ) {
118 teardown: function() {
120 this.testEnvironment.teardown.call(this.testEnvironment);
123 QUnit.ok( false, "Teardown failed on " + this.testName + ": " + e.message );
127 if ( this.expected && this.expected != this.assertions.length ) {
128 QUnit.ok( false, "Expected " + this.expected + " assertions, but " + this.assertions.length + " were run" );
131 var good = 0, bad = 0,
132 tests = id("qunit-tests");
134 config.stats.all += this.assertions.length;
135 config.moduleStats.all += this.assertions.length;
138 var ol = document.createElement("ol");
140 for ( var i = 0; i < this.assertions.length; i++ ) {
141 var assertion = this.assertions[i];
143 var li = document.createElement("li");
144 li.className = assertion.result ? "pass" : "fail";
145 li.innerHTML = assertion.message || (assertion.result ? "okay" : "failed");
146 ol.appendChild( li );
148 if ( assertion.result ) {
153 config.moduleStats.bad++;
157 // store result when possible
158 if ( QUnit.config.reorder && defined.sessionStorage ) {
160 sessionStorage.setItem("qunit-" + this.module + "-" + this.testName, bad);
162 sessionStorage.removeItem("qunit-" + this.module + "-" + this.testName);
167 ol.style.display = "none";
170 var b = document.createElement("strong");
171 b.innerHTML = this.name + " <b class='counts'>(<b class='failed'>" + bad + "</b>, <b class='passed'>" + good + "</b>, " + this.assertions.length + ")</b>";
173 var a = document.createElement("a");
174 a.innerHTML = "Rerun";
175 a.href = QUnit.url({ filter: getText([b]).replace(/\([^)]+\)$/, "").replace(/(^\s*|\s*$)/g, "") });
177 addEvent(b, "click", function() {
178 var next = b.nextSibling.nextSibling,
179 display = next.style.display;
180 next.style.display = display === "none" ? "block" : "none";
183 addEvent(b, "dblclick", function(e) {
184 var target = e && e.target ? e.target : window.event.srcElement;
185 if ( target.nodeName.toLowerCase() == "span" || target.nodeName.toLowerCase() == "b" ) {
186 target = target.parentNode;
188 if ( window.location && target.nodeName.toLowerCase() === "strong" ) {
189 window.location = QUnit.url({ filter: getText([target]).replace(/\([^)]+\)$/, "").replace(/(^\s*|\s*$)/g, "") });
193 var li = id(this.id);
194 li.className = bad ? "fail" : "pass";
195 li.removeChild( li.firstChild );
198 li.appendChild( ol );
201 for ( var i = 0; i < this.assertions.length; i++ ) {
202 if ( !this.assertions[i].result ) {
205 config.moduleStats.bad++;
213 fail("reset() failed, following Test " + this.testName + ", exception and reset fn follows", e, QUnit.reset);
216 runLoggingCallbacks( 'testDone', QUnit, {
220 passed: this.assertions.length - bad,
221 total: this.assertions.length
227 synchronize(function() {
231 // each of these can by async
232 synchronize(function() {
235 synchronize(function() {
238 synchronize(function() {
241 synchronize(function() {
245 // defer when previous test run passed, if storage is available
246 var bad = QUnit.config.reorder && defined.sessionStorage && +sessionStorage.getItem("qunit-" + this.module + "-" + this.testName);
258 // call on start of module test to prepend name to all tests
259 module: function(name, testEnvironment) {
260 config.currentModule = name;
261 config.currentModuleTestEnviroment = testEnvironment;
264 asyncTest: function(testName, expected, callback) {
265 if ( arguments.length === 2 ) {
270 QUnit.test(testName, expected, callback, true);
273 test: function(testName, expected, callback, async) {
274 var name = '<span class="test-name">' + testName + '</span>', testEnvironmentArg;
276 if ( arguments.length === 2 ) {
280 // is 2nd argument a testEnvironment?
281 if ( expected && typeof expected === 'object') {
282 testEnvironmentArg = expected;
286 if ( config.currentModule ) {
287 name = '<span class="module-name">' + config.currentModule + "</span>: " + name;
290 if ( !validTest(config.currentModule + ": " + testName) ) {
294 var test = new Test(name, testName, expected, testEnvironmentArg, async, callback);
295 test.module = config.currentModule;
296 test.moduleTestEnvironment = config.currentModuleTestEnviroment;
301 * Specify the number of expected assertions to gurantee that failed test (no assertions are run at all) don't slip through.
303 expect: function(asserts) {
304 config.current.expected = asserts;
309 * @example ok( "asdfasdf".length > 5, "There must be at least 5 chars" );
311 ok: function(a, msg) {
317 msg = escapeInnerText(msg);
318 runLoggingCallbacks( 'log', QUnit, details );
319 config.current.assertions.push({
326 * Checks that the first two arguments are equal, with an optional message.
327 * Prints out both actual and expected values.
329 * Prefered to ok( actual == expected, message )
331 * @example equal( format("Received {0} bytes.", 2), "Received 2 bytes." );
333 * @param Object actual
334 * @param Object expected
335 * @param String message (optional)
337 equal: function(actual, expected, message) {
338 QUnit.push(expected == actual, actual, expected, message);
341 notEqual: function(actual, expected, message) {
342 QUnit.push(expected != actual, actual, expected, message);
345 deepEqual: function(actual, expected, message) {
346 QUnit.push(QUnit.equiv(actual, expected), actual, expected, message);
349 notDeepEqual: function(actual, expected, message) {
350 QUnit.push(!QUnit.equiv(actual, expected), actual, expected, message);
353 strictEqual: function(actual, expected, message) {
354 QUnit.push(expected === actual, actual, expected, message);
357 notStrictEqual: function(actual, expected, message) {
358 QUnit.push(expected !== actual, actual, expected, message);
361 raises: function(block, expected, message) {
362 var actual, ok = false;
364 if (typeof expected === 'string') {
376 // we don't want to validate thrown error
379 // expected is a regexp
380 } else if (QUnit.objectType(expected) === "regexp") {
381 ok = expected.test(actual);
382 // expected is a constructor
383 } else if (actual instanceof expected) {
385 // expected is a validation function which returns true is validation passed
386 } else if (expected.call({}, actual) === true) {
391 QUnit.ok(ok, message);
394 start: function(count) {
395 config.semaphore -= count || 1;
396 if (config.semaphore > 0) {
397 // don't start until equal number of stop-calls
400 if (config.semaphore < 0) {
401 // ignore if start is called more often then stop
402 config.semaphore = 0;
404 // A slight delay, to avoid any current callbacks
405 if ( defined.setTimeout ) {
406 window.setTimeout(function() {
407 if (config.semaphore > 0) {
410 if ( config.timeout ) {
411 clearTimeout(config.timeout);
414 config.blocking = false;
418 config.blocking = false;
423 stop: function(count) {
424 config.semaphore += count || 1;
425 config.blocking = true;
427 if ( config.testTimeout && defined.setTimeout ) {
428 clearTimeout(config.timeout);
429 config.timeout = window.setTimeout(function() {
430 QUnit.ok( false, "Test timed out" );
431 config.semaphore = 1;
433 }, config.testTimeout);
438 //We want access to the constructor's prototype
443 //Make F QUnit's constructor so that we can add to the prototype later
444 QUnit.constructor = F;
447 // Backwards compatibility, deprecated
448 QUnit.equals = QUnit.equal;
449 QUnit.same = QUnit.deepEqual;
451 // Maintain internal state
453 // The queue of tests to run
456 // block until document ready
459 // when enabled, show only failing tests
460 // gets persisted through sessionStorage and can be changed in UI via checkbox
463 // by default, run previously failed tests first
464 // very useful in combination with "Hide passed tests" checked
467 // by default, modify document.title when suite is done
470 urlConfig: ['noglobals', 'notrycatch'],
472 //logging callback queues
484 var location = window.location || { search: "", protocol: "file:" },
485 params = location.search.slice( 1 ).split( "&" ),
486 length = params.length,
491 for ( var i = 0; i < length; i++ ) {
492 current = params[ i ].split( "=" );
493 current[ 0 ] = decodeURIComponent( current[ 0 ] );
494 // allow just a key to turn on a flag, e.g., test.html?noglobals
495 current[ 1 ] = current[ 1 ] ? decodeURIComponent( current[ 1 ] ) : true;
496 urlParams[ current[ 0 ] ] = current[ 1 ];
500 QUnit.urlParams = urlParams;
501 config.filter = urlParams.filter;
503 // Figure out if we're running the tests from a server or not
504 QUnit.isLocal = !!(location.protocol === 'file:');
507 // Expose the API as global variables, unless an 'exports'
508 // object exists, in that case we assume we're in CommonJS
509 if ( typeof exports === "undefined" || typeof require === "undefined" ) {
510 extend(window, QUnit);
511 window.QUnit = QUnit;
513 extend(exports, QUnit);
514 exports.QUnit = QUnit;
517 // define these after exposing globals to keep them in these QUnit namespace only
521 // Initialize the configuration options
524 stats: { all: 0, bad: 0 },
525 moduleStats: { all: 0, bad: 0 },
536 var tests = id( "qunit-tests" ),
537 banner = id( "qunit-banner" ),
538 result = id( "qunit-testresult" );
541 tests.innerHTML = "";
545 banner.className = "";
549 result.parentNode.removeChild( result );
553 result = document.createElement( "p" );
554 result.id = "qunit-testresult";
555 result.className = "result";
556 tests.parentNode.insertBefore( result, tests );
557 result.innerHTML = 'Running...<br/> ';
562 * Resets the test setup. Useful for tests that modify the DOM.
564 * If jQuery is available, uses jQuery's html(), otherwise just innerHTML.
567 if ( window.jQuery ) {
568 jQuery( "#qunit-fixture" ).html( config.fixture );
570 var main = id( 'qunit-fixture' );
572 main.innerHTML = config.fixture;
578 * Trigger an event on an element.
580 * @example triggerEvent( document.body, "click" );
582 * @param DOMElement elem
585 triggerEvent: function( elem, type, event ) {
586 if ( document.createEvent ) {
587 event = document.createEvent("MouseEvents");
588 event.initMouseEvent(type, true, true, elem.ownerDocument.defaultView,
589 0, 0, 0, 0, 0, false, false, false, false, 0, null);
590 elem.dispatchEvent( event );
592 } else if ( elem.fireEvent ) {
593 elem.fireEvent("on"+type);
597 // Safe object type checking
598 is: function( type, obj ) {
599 return QUnit.objectType( obj ) == type;
602 objectType: function( obj ) {
603 if (typeof obj === "undefined") {
606 // consider: typeof null === object
612 var type = toString.call( obj ).match(/^\[object\s(.*)\]$/)[1] || '';
627 return type.toLowerCase();
629 if (typeof obj === "object") {
635 push: function(result, actual, expected, message) {
643 message = escapeInnerText(message) || (result ? "okay" : "failed");
644 message = '<span class="test-message">' + message + "</span>";
645 expected = escapeInnerText(QUnit.jsDump.parse(expected));
646 actual = escapeInnerText(QUnit.jsDump.parse(actual));
647 var output = message + '<table><tr class="test-expected"><th>Expected: </th><td><pre>' + expected + '</pre></td></tr>';
648 if (actual != expected) {
649 output += '<tr class="test-actual"><th>Result: </th><td><pre>' + actual + '</pre></td></tr>';
650 output += '<tr class="test-diff"><th>Diff: </th><td><pre>' + QUnit.diff(expected, actual) +'</pre></td></tr>';
653 var source = sourceFromStacktrace();
655 details.source = source;
656 output += '<tr class="test-source"><th>Source: </th><td><pre>' + escapeInnerText(source) + '</pre></td></tr>';
659 output += "</table>";
661 runLoggingCallbacks( 'log', QUnit, details );
663 config.current.assertions.push({
669 url: function( params ) {
670 params = extend( extend( {}, QUnit.urlParams ), params );
671 var querystring = "?",
673 for ( key in params ) {
674 if ( !hasOwn.call( params, key ) ) {
677 querystring += encodeURIComponent( key ) + "=" +
678 encodeURIComponent( params[ key ] ) + "&";
680 return window.location.pathname + querystring.slice( 0, -1 );
688 //QUnit.constructor is set to the empty F() above so that we can add to it's prototype later
689 //Doing this allows us to tell if the following methods have been overwritten on the actual
690 //QUnit object, which is a deprecated way of using the callbacks.
691 extend(QUnit.constructor.prototype, {
692 // Logging callbacks; all receive a single argument with the listed properties
693 // run test/logs.html for any related changes
694 begin: registerLoggingCallback('begin'),
695 // done: { failed, passed, total, runtime }
696 done: registerLoggingCallback('done'),
697 // log: { result, actual, expected, message }
698 log: registerLoggingCallback('log'),
699 // testStart: { name }
700 testStart: registerLoggingCallback('testStart'),
701 // testDone: { name, failed, passed, total }
702 testDone: registerLoggingCallback('testDone'),
703 // moduleStart: { name }
704 moduleStart: registerLoggingCallback('moduleStart'),
705 // moduleDone: { name, failed, passed, total }
706 moduleDone: registerLoggingCallback('moduleDone')
709 if ( typeof document === "undefined" || document.readyState === "complete" ) {
710 config.autorun = true;
713 QUnit.load = function() {
714 runLoggingCallbacks( 'begin', QUnit, {} );
716 // Initialize the config, saving the execution queue
717 var oldconfig = extend({}, config);
719 extend(config, oldconfig);
721 config.blocking = false;
723 var urlConfigHtml = '', len = config.urlConfig.length;
724 for ( var i = 0, val; i < len, val = config.urlConfig[i]; i++ ) {
725 config[val] = QUnit.urlParams[val];
726 urlConfigHtml += '<label><input name="' + val + '" type="checkbox"' + ( config[val] ? ' checked="checked"' : '' ) + '>' + val + '</label>';
729 var userAgent = id("qunit-userAgent");
731 userAgent.innerHTML = navigator.userAgent;
733 var banner = id("qunit-header");
735 banner.innerHTML = '<a href="' + QUnit.url({ filter: undefined }) + '"> ' + banner.innerHTML + '</a> ' + urlConfigHtml;
736 addEvent( banner, "change", function( event ) {
738 params[ event.target.name ] = event.target.checked ? true : undefined;
739 window.location = QUnit.url( params );
743 var toolbar = id("qunit-testrunner-toolbar");
745 var filter = document.createElement("input");
746 filter.type = "checkbox";
747 filter.id = "qunit-filter-pass";
748 addEvent( filter, "click", function() {
749 var ol = document.getElementById("qunit-tests");
750 if ( filter.checked ) {
751 ol.className = ol.className + " hidepass";
753 var tmp = " " + ol.className.replace( /[\n\t\r]/g, " " ) + " ";
754 ol.className = tmp.replace(/ hidepass /, " ");
756 if ( defined.sessionStorage ) {
757 if (filter.checked) {
758 sessionStorage.setItem("qunit-filter-passed-tests", "true");
760 sessionStorage.removeItem("qunit-filter-passed-tests");
764 if ( config.hidepassed || defined.sessionStorage && sessionStorage.getItem("qunit-filter-passed-tests") ) {
765 filter.checked = true;
766 var ol = document.getElementById("qunit-tests");
767 ol.className = ol.className + " hidepass";
769 toolbar.appendChild( filter );
771 var label = document.createElement("label");
772 label.setAttribute("for", "qunit-filter-pass");
773 label.innerHTML = "Hide passed tests";
774 toolbar.appendChild( label );
777 var main = id('qunit-fixture');
779 config.fixture = main.innerHTML;
782 if (config.autostart) {
787 addEvent(window, "load", QUnit.load);
790 config.autorun = true;
792 // Log the last module results
793 if ( config.currentModule ) {
794 runLoggingCallbacks( 'moduleDone', QUnit, {
795 name: config.currentModule,
796 failed: config.moduleStats.bad,
797 passed: config.moduleStats.all - config.moduleStats.bad,
798 total: config.moduleStats.all
802 var banner = id("qunit-banner"),
803 tests = id("qunit-tests"),
804 runtime = +new Date - config.started,
805 passed = config.stats.all - config.stats.bad,
807 'Tests completed in ',
809 ' milliseconds.<br/>',
810 '<span class="passed">',
812 '</span> tests of <span class="total">',
814 '</span> passed, <span class="failed">',
820 banner.className = (config.stats.bad ? "qunit-fail" : "qunit-pass");
824 id( "qunit-testresult" ).innerHTML = html;
827 if ( config.altertitle && typeof document !== "undefined" && document.title ) {
828 // show ✖ for good, ✔ for bad suite result in title
829 // use escape sequences in case file gets loaded with non-utf-8-charset
831 (config.stats.bad ? "\u2716" : "\u2714"),
832 document.title.replace(/^[\u2714\u2716] /i, "")
836 runLoggingCallbacks( 'done', QUnit, {
837 failed: config.stats.bad,
839 total: config.stats.all,
844 function validTest( name ) {
845 var filter = config.filter,
852 var not = filter.charAt( 0 ) === "!";
854 filter = filter.slice( 1 );
857 if ( name.indexOf( filter ) !== -1 ) {
868 // so far supports only Firefox, Chrome and Opera (buggy)
869 // could be extended in the future to use something like https://github.com/csnover/TraceKit
870 function sourceFromStacktrace() {
876 return e.stacktrace.split("\n")[6];
877 } else if (e.stack) {
879 return e.stack.split("\n")[4];
880 } else if (e.sourceURL) {
882 // TODO sourceURL points at the 'throw new Error' line above, useless
883 //return e.sourceURL + ":" + e.line;
888 function escapeInnerText(s) {
893 return s.replace(/[\&<>]/g, function(s) {
895 case "&": return "&";
896 case "<": return "<";
897 case ">": return ">";
903 function synchronize( callback ) {
904 config.queue.push( callback );
906 if ( config.autorun && !config.blocking ) {
912 var start = (new Date()).getTime();
914 while ( config.queue.length && !config.blocking ) {
915 if ( config.updateRate <= 0 || (((new Date()).getTime() - start) < config.updateRate) ) {
916 config.queue.shift()();
918 window.setTimeout( process, 13 );
922 if (!config.blocking && !config.queue.length) {
927 function saveGlobal() {
928 config.pollution = [];
930 if ( config.noglobals ) {
931 for ( var key in window ) {
932 if ( !hasOwn.call( window, key ) ) {
935 config.pollution.push( key );
940 function checkPollution( name ) {
941 var old = config.pollution;
944 var newGlobals = diff( config.pollution, old );
945 if ( newGlobals.length > 0 ) {
946 ok( false, "Introduced global variable(s): " + newGlobals.join(", ") );
949 var deletedGlobals = diff( old, config.pollution );
950 if ( deletedGlobals.length > 0 ) {
951 ok( false, "Deleted global variable(s): " + deletedGlobals.join(", ") );
955 // returns a new Array with the elements that are in a but not in b
956 function diff( a, b ) {
957 var result = a.slice();
958 for ( var i = 0; i < result.length; i++ ) {
959 for ( var j = 0; j < b.length; j++ ) {
960 if ( result[i] === b[j] ) {
970 function fail(message, exception, callback) {
971 if ( typeof console !== "undefined" && console.error && console.warn ) {
972 console.error(message);
973 console.error(exception);
974 console.warn(callback.toString());
976 } else if ( window.opera && opera.postError ) {
977 opera.postError(message, exception, callback.toString);
981 function extend(a, b) {
982 for ( var prop in b ) {
983 if ( b[prop] === undefined ) {
993 function addEvent(elem, type, fn) {
994 if ( elem.addEventListener ) {
995 elem.addEventListener( type, fn, false );
996 } else if ( elem.attachEvent ) {
997 elem.attachEvent( "on" + type, fn );
1004 return !!(typeof document !== "undefined" && document && document.getElementById) &&
1005 document.getElementById( name );
1008 function registerLoggingCallback(key){
1009 return function(callback){
1010 config[key].push( callback );
1014 // Supports deprecated method of completely overwriting logging callbacks
1015 function runLoggingCallbacks(key, scope, args) {
1018 if ( QUnit.hasOwnProperty(key) ) {
1019 QUnit[key].call(scope, args);
1021 callbacks = config[key];
1022 for( var i = 0; i < callbacks.length; i++ ) {
1023 callbacks[i].call( scope, args );
1028 // Test for equality any JavaScript type.
1029 // Author: Philippe Rathé <prathe@gmail.com>
1030 QUnit.equiv = function () {
1032 var innerEquiv; // the real equiv function
1033 var callers = []; // stack to decide between skip/abort functions
1034 var parents = []; // stack to avoiding loops from circular referencing
1036 // Call the o related callback with the given arguments.
1037 function bindCallbacks(o, callbacks, args) {
1038 var prop = QUnit.objectType(o);
1040 if (QUnit.objectType(callbacks[prop]) === "function") {
1041 return callbacks[prop].apply(callbacks, args);
1043 return callbacks[prop]; // or undefined
1048 var callbacks = function () {
1050 // for string, boolean, number and null
1051 function useStrictEquality(b, a) {
1052 if (b instanceof a.constructor || a instanceof b.constructor) {
1053 // to catch short annotaion VS 'new' annotation of a
1056 // var j = new Number(1);
1064 "string" : useStrictEquality,
1065 "boolean" : useStrictEquality,
1066 "number" : useStrictEquality,
1067 "null" : useStrictEquality,
1068 "undefined" : useStrictEquality,
1070 "nan" : function(b) {
1074 "date" : function(b, a) {
1075 return QUnit.objectType(b) === "date"
1076 && a.valueOf() === b.valueOf();
1079 "regexp" : function(b, a) {
1080 return QUnit.objectType(b) === "regexp"
1081 && a.source === b.source && // the regex itself
1082 a.global === b.global && // and its modifers
1084 a.ignoreCase === b.ignoreCase
1085 && a.multiline === b.multiline;
1088 // - skip when the property is a method of an instance (OOP)
1089 // - abort otherwise,
1090 // initial === would have catch identical references anyway
1091 "function" : function() {
1092 var caller = callers[callers.length - 1];
1093 return caller !== Object && typeof caller !== "undefined";
1096 "array" : function(b, a) {
1100 // b could be an object literal here
1101 if (!(QUnit.objectType(b) === "array")) {
1106 if (len !== b.length) { // safe and faster
1110 // track reference to avoid circular references
1112 for (i = 0; i < len; i++) {
1114 for (j = 0; j < parents.length; j++) {
1115 if (parents[j] === a[i]) {
1116 loop = true;// dont rewalk array
1119 if (!loop && !innerEquiv(a[i], b[i])) {
1128 "object" : function(b, a) {
1130 var eq = true; // unless we can proove it
1131 var aProperties = [], bProperties = []; // collection of
1134 // comparing constructors is more strict than using
1136 if (a.constructor !== b.constructor) {
1140 // stack constructor before traversing properties
1141 callers.push(a.constructor);
1142 // track reference to avoid circular references
1145 for (i in a) { // be strict: don't ensures hasOwnProperty
1148 for (j = 0; j < parents.length; j++) {
1149 if (parents[j] === a[i])
1150 loop = true; // don't go down the same path
1153 aProperties.push(i); // collect a's properties
1155 if (!loop && !innerEquiv(a[i], b[i])) {
1161 callers.pop(); // unstack, we are done
1165 bProperties.push(i); // collect b's properties
1168 // Ensures identical properties name
1170 && innerEquiv(aProperties.sort(), bProperties
1176 innerEquiv = function() { // can take multiple arguments
1177 var args = Array.prototype.slice.apply(arguments);
1178 if (args.length < 2) {
1179 return true; // end transition
1182 return (function(a, b) {
1184 return true; // catch the most you can
1185 } else if (a === null || b === null || typeof a === "undefined"
1186 || typeof b === "undefined"
1187 || QUnit.objectType(a) !== QUnit.objectType(b)) {
1188 return false; // don't lose time with error prone cases
1190 return bindCallbacks(a, callbacks, [ b, a ]);
1193 // apply transition with (1..n) arguments
1194 })(args[0], args[1])
1195 && arguments.callee.apply(this, args.splice(1,
1204 * jsDump Copyright (c) 2008 Ariel Flesler - aflesler(at)gmail(dot)com |
1205 * http://flesler.blogspot.com Licensed under BSD
1206 * (http://www.opensource.org/licenses/bsd-license.php) Date: 5/15/2008
1208 * @projectDescription Advanced and extensible data dumping for Javascript.
1210 * @author Ariel Flesler
1211 * @link {http://flesler.blogspot.com/2008/05/jsdump-pretty-dump-of-any-javascript.html}
1213 QUnit.jsDump = (function() {
1214 function quote( str ) {
1215 return '"' + str.toString().replace(/"/g, '\\"') + '"';
1217 function literal( o ) {
1220 function join( pre, arr, post ) {
1221 var s = jsDump.separator(),
1222 base = jsDump.indent(),
1223 inner = jsDump.indent(1);
1225 arr = arr.join( ',' + s + inner );
1228 return [ pre, inner + arr, base + post ].join(s);
1230 function array( arr, stack ) {
1231 var i = arr.length, ret = Array(i);
1234 ret[i] = this.parse( arr[i] , undefined , stack);
1236 return join( '[', ret, ']' );
1239 var reName = /^function (\w+)/;
1242 parse:function( obj, type, stack ) { //type is used mostly internally, you can fix a (custom)type in advance
1243 stack = stack || [ ];
1244 var parser = this.parsers[ type || this.typeOf(obj) ];
1245 type = typeof parser;
1246 var inStack = inArray(obj, stack);
1247 if (inStack != -1) {
1248 return 'recursion('+(inStack - stack.length)+')';
1251 if (type == 'function') {
1253 var res = parser.call( this, obj, stack );
1258 return (type == 'string') ? parser : this.parsers.error;
1260 typeOf:function( obj ) {
1262 if ( obj === null ) {
1264 } else if (typeof obj === "undefined") {
1266 } else if (QUnit.is("RegExp", obj)) {
1268 } else if (QUnit.is("Date", obj)) {
1270 } else if (QUnit.is("Function", obj)) {
1272 } else if (typeof obj.setInterval !== undefined && typeof obj.document !== "undefined" && typeof obj.nodeType === "undefined") {
1274 } else if (obj.nodeType === 9) {
1276 } else if (obj.nodeType) {
1278 } else if (typeof obj === "object" && typeof obj.length === "number" && obj.length >= 0) {
1285 separator:function() {
1286 return this.multiline ? this.HTML ? '<br />' : '\n' : this.HTML ? ' ' : ' ';
1288 indent:function( extra ) {// extra can be a number, shortcut for increasing-calling-decreasing
1289 if ( !this.multiline )
1291 var chr = this.indentChar;
1293 chr = chr.replace(/\t/g,' ').replace(/ /g,' ');
1294 return Array( this._depth_ + (extra||0) ).join(chr);
1297 this._depth_ += a || 1;
1299 down:function( a ) {
1300 this._depth_ -= a || 1;
1302 setParser:function( name, parser ) {
1303 this.parsers[name] = parser;
1305 // The next 3 are exposed so you can use them
1311 // This is the list of parsers, to modify them, use jsDump.setParser
1314 document: '[Document]',
1315 error:'[ERROR]', //when no parser is found, shouldn't happen
1316 unknown: '[Unknown]',
1318 'undefined':'undefined',
1319 'function':function( fn ) {
1320 var ret = 'function',
1321 name = 'name' in fn ? fn.name : (reName.exec(fn)||[])[1];//functions never have name in IE
1326 ret = [ ret, QUnit.jsDump.parse( fn, 'functionArgs' ), '){'].join('');
1327 return join( ret, QUnit.jsDump.parse(fn,'functionCode'), '}' );
1332 object:function( map, stack ) {
1335 for ( var key in map ) {
1337 ret.push( QUnit.jsDump.parse(key,'key') + ': ' + QUnit.jsDump.parse(val, undefined, stack));
1339 QUnit.jsDump.down();
1340 return join( '{', ret, '}' );
1342 node:function( node ) {
1343 var open = QUnit.jsDump.HTML ? '<' : '<',
1344 close = QUnit.jsDump.HTML ? '>' : '>';
1346 var tag = node.nodeName.toLowerCase(),
1349 for ( var a in QUnit.jsDump.DOMAttrs ) {
1350 var val = node[QUnit.jsDump.DOMAttrs[a]];
1352 ret += ' ' + a + '=' + QUnit.jsDump.parse( val, 'attribute' );
1354 return ret + close + open + '/' + tag + close;
1356 functionArgs:function( fn ) {//function calls it internally, it's the arguments part of the function
1358 if ( !l ) return '';
1360 var args = Array(l);
1362 args[l] = String.fromCharCode(97+l);//97 is 'a'
1363 return ' ' + args.join(', ') + ' ';
1365 key:quote, //object calls it internally, the key part of an item in a map
1366 functionCode:'[code]', //function calls it internally, it's the content of the function
1367 attribute:quote, //node calls it internally, it's an html attribute value
1370 regexp:literal, //regex
1374 DOMAttrs:{//attributes to dump from nodes, name=>realName
1379 HTML:false,//if true, entities are escaped ( <, >, \t, space and \n )
1380 indentChar:' ',//indentation unit
1381 multiline:true //if true, items in a collection, are separated by a \n, else just a space.
1388 function getText( elems ) {
1391 for ( var i = 0; elems[i]; i++ ) {
1394 // Get the text from text nodes and CDATA nodes
1395 if ( elem.nodeType === 3 || elem.nodeType === 4 ) {
1396 ret += elem.nodeValue;
1398 // Traverse everything else, except comment nodes
1399 } else if ( elem.nodeType !== 8 ) {
1400 ret += getText( elem.childNodes );
1408 function inArray( elem, array ) {
1409 if ( array.indexOf ) {
1410 return array.indexOf( elem );
1413 for ( var i = 0, length = array.length; i < length; i++ ) {
1414 if ( array[ i ] === elem ) {
1423 * Javascript Diff Algorithm
1424 * By John Resig (http://ejohn.org/)
1425 * Modified by Chu Alan "sprite"
1427 * Released under the MIT license.
1430 * http://ejohn.org/projects/javascript-diff-algorithm/
1432 * Usage: QUnit.diff(expected, actual)
1434 * 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"
1436 QUnit.diff = (function() {
1437 function diff(o, n) {
1441 for (var i = 0; i < n.length; i++) {
1442 if (ns[n[i]] == null)
1447 ns[n[i]].rows.push(i);
1450 for (var i = 0; i < o.length; i++) {
1451 if (os[o[i]] == null)
1456 os[o[i]].rows.push(i);
1460 if ( !hasOwn.call( ns, i ) ) {
1463 if (ns[i].rows.length == 1 && typeof(os[i]) != "undefined" && os[i].rows.length == 1) {
1464 n[ns[i].rows[0]] = {
1465 text: n[ns[i].rows[0]],
1468 o[os[i].rows[0]] = {
1469 text: o[os[i].rows[0]],
1475 for (var i = 0; i < n.length - 1; i++) {
1476 if (n[i].text != null && n[i + 1].text == null && n[i].row + 1 < o.length && o[n[i].row + 1].text == null &&
1477 n[i + 1] == o[n[i].row + 1]) {
1483 text: o[n[i].row + 1],
1489 for (var i = n.length - 1; i > 0; i--) {
1490 if (n[i].text != null && n[i - 1].text == null && n[i].row > 0 && o[n[i].row - 1].text == null &&
1491 n[i - 1] == o[n[i].row - 1]) {
1497 text: o[n[i].row - 1],
1509 return function(o, n) {
1510 o = o.replace(/\s+$/, '');
1511 n = n.replace(/\s+$/, '');
1512 var out = diff(o == "" ? [] : o.split(/\s+/), n == "" ? [] : n.split(/\s+/));
1516 var oSpace = o.match(/\s+/g);
1517 if (oSpace == null) {
1523 var nSpace = n.match(/\s+/g);
1524 if (nSpace == null) {
1531 if (out.n.length == 0) {
1532 for (var i = 0; i < out.o.length; i++) {
1533 str += '<del>' + out.o[i] + oSpace[i] + "</del>";
1537 if (out.n[0].text == null) {
1538 for (n = 0; n < out.o.length && out.o[n].text == null; n++) {
1539 str += '<del>' + out.o[n] + oSpace[n] + "</del>";
1543 for (var i = 0; i < out.n.length; i++) {
1544 if (out.n[i].text == null) {
1545 str += '<ins>' + out.n[i] + nSpace[i] + "</ins>";
1550 for (n = out.n[i].row + 1; n < out.o.length && out.o[n].text == null; n++) {
1551 pre += '<del>' + out.o[n] + oSpace[n] + "</del>";
1553 str += " " + out.n[i].text + nSpace[i] + pre;