jquery testrunner: reset global events after each run, speeds up a test run for ajax...
[jquery.git] / test / data / testrunner.js
1 var _config = {
2         fixture: null,
3         Test: [],
4         stats: {
5                 all: 0,
6                 bad: 0
7         },
8         queue: [],
9         blocking: true,
10         timeout: null,
11         expected: null,
12         currentModule: null,
13         asyncTimeout: 2 // seconds for async timeout
14 };
15
16 _config.filters = location.search.length > 1 && //restrict modules/tests by get parameters
17                 $.map( location.search.slice(1).split('&'), decodeURIComponent );
18
19 var isLocal = !!(window.location.protocol == 'file:');
20
21 $(function() {
22         $('#userAgent').html(navigator.userAgent);
23         runTest();      
24 });
25
26 function synchronize(callback) {
27         _config.queue[_config.queue.length] = callback;
28         if(!_config.blocking) {
29                 process();
30         }
31 }
32
33 function process() {
34         while(_config.queue.length && !_config.blocking) {
35                 var call = _config.queue[0];
36                 _config.queue = _config.queue.slice(1);
37                 call();
38         }
39 }
40
41 function stop(allowFailure) {
42         _config.blocking = true;
43         var handler = allowFailure ? start : function() {
44                 ok( false, "Test timed out" );
45                 start();
46         };
47         // Disabled, caused too many random errors
48         //_config.timeout = setTimeout(handler, _config.asyncTimeout * 1000);
49 }
50 function start() {
51         // A slight delay, to avoid any current callbacks
52         setTimeout(function(){
53                 if(_config.timeout)
54                         clearTimeout(_config.timeout);
55                 _config.blocking = false;
56                 process();
57         }, 13);
58 }
59
60 function validTest( name ) {
61         var filters = _config.filters;
62         if( !filters )
63                 return true;
64
65         var i = filters.length,
66                 run = false;
67         while( i-- ){
68                 var filter = filters[i],
69                         not = filter.charAt(0) == '!';
70                 if( not ) 
71                         filter = filter.slice(1);
72                 if( name.indexOf(filter) != -1 )
73                         return !not;
74                 if( not )
75                         run = true;
76         }
77         return run;
78 }
79
80 function runTest() {
81         _config.blocking = false;
82         var time = new Date();
83         _config.fixture = document.getElementById('main').innerHTML;
84         synchronize(function() {
85                 time = new Date() - time;
86                 $("<div>").html(['<p class="result">Tests completed in ',
87                         time, ' milliseconds.<br/>',
88                         _config.stats.bad, ' tests of ', _config.stats.all, ' failed.</p>']
89                         .join(''))
90                         .appendTo("body");
91                 $("#banner").addClass(_config.stats.bad ? "fail" : "pass");
92         });
93 }
94
95 function test(name, callback, nowait) {
96         if(_config.currentModule)
97                 name = _config.currentModule + " module: " + name;
98                 
99         if ( !validTest(name) )
100                 return;
101                 
102         synchronize(function() {
103                 _config.Test = [];
104                 try {
105                         callback();
106                 } catch(e) {
107                         if( typeof console != "undefined" && console.error && console.warn ) {
108                                 console.error("Test " + name + " died, exception and test follows");
109                                 console.error(e);
110                                 console.warn(callback.toString());
111                         }
112                         _config.Test.push( [ false, "Died on test #" + (_config.Test.length+1) + ": " + e ] );
113                 }
114         });
115         synchronize(function() {
116                 reset();
117                 
118                 // don't output pause tests
119                 if(nowait) return;
120                 
121                 if(_config.expected && _config.expected != _config.Test.length) {
122                         _config.Test.push( [ false, "Expected " + _config.expected + " assertions, but " + _config.Test.length + " were run" ] );
123                 }
124                 _config.expected = null;
125                 
126                 var good = 0, bad = 0;
127                 var ol = document.createElement("ol");
128                 ol.style.display = "none";
129                 var li = "", state = "pass";
130                 for ( var i = 0; i < _config.Test.length; i++ ) {
131                         var li = document.createElement("li");
132                         li.className = _config.Test[i][0] ? "pass" : "fail";
133                         li.innerHTML = _config.Test[i][1];
134                         ol.appendChild( li );
135                         
136                         _config.stats.all++;
137                         if ( !_config.Test[i][0] ) {
138                                 state = "fail";
139                                 bad++;
140                                 _config.stats.bad++;
141                         } else good++;
142                 }
143         
144                 var li = document.createElement("li");
145                 li.className = state;
146         
147                 var b = document.createElement("strong");
148                 b.innerHTML = name + " <b style='color:black;'>(<b class='fail'>" + bad + "</b>, <b class='pass'>" + good + "</b>, " + _config.Test.length + ")</b>";
149                 b.onclick = function(){
150                         var n = this.nextSibling;
151                         if ( jQuery.css( n, "display" ) == "none" )
152                                 n.style.display = "block";
153                         else
154                                 n.style.display = "none";
155                 };
156                 $(b).dblclick(function(event) {
157                         var target = jQuery(event.target).filter("strong").clone();
158                         if ( target.length ) {
159                                 target.children().remove();
160                                 location.href = location.href.match(/^(.+?)(\?.*)?$/)[1] + "?" + encodeURIComponent($.trim(target.text()));
161                         }
162                 });
163                 li.appendChild( b );
164                 li.appendChild( ol );
165         
166                 document.getElementById("tests").appendChild( li );             
167         });
168 }
169
170 // call on start of module test to prepend name to all tests
171 function module(moduleName) {
172         _config.currentModule = moduleName;
173 }
174
175 /**
176  * Specify the number of expected assertions to gurantee that failed test (no assertions are run at all) don't slip through.
177  */
178 function expect(asserts) {
179         _config.expected = asserts;
180 }
181
182 /**
183  * Resets the test setup. Useful for tests that modify the DOM.
184  */
185 function reset() {
186         $("#main").html( _config.fixture );
187         $.event.global = {};
188 }
189
190 /**
191  * Asserts true.
192  * @example ok( $("a").size() > 5, "There must be at least 5 anchors" );
193  */
194 function ok(a, msg) {
195         _config.Test.push( [ !!a, msg ] );
196 }
197
198 /**
199  * Asserts that two arrays are the same
200  */
201 function isSet(a, b, msg) {
202         var ret = true;
203         if ( a && b && a.length != undefined && a.length == b.length ) {
204                 for ( var i = 0; i < a.length; i++ )
205                         if ( a[i] != b[i] )
206                                 ret = false;
207         } else
208                 ret = false;
209         if ( !ret )
210                 _config.Test.push( [ ret, msg + " expected: " + serialArray(b) + " result: " + serialArray(a) ] );
211         else 
212                 _config.Test.push( [ ret, msg ] );
213 }
214
215 /**
216  * Asserts that two objects are equivalent
217  */
218 function isObj(a, b, msg) {
219         var ret = true;
220         
221         if ( a && b ) {
222                 for ( var i in a )
223                         if ( a[i] != b[i] )
224                                 ret = false;
225
226                 for ( i in b )
227                         if ( a[i] != b[i] )
228                                 ret = false;
229         } else
230                 ret = false;
231
232     _config.Test.push( [ ret, msg ] );
233 }
234
235 function serialArray( a ) {
236         var r = [];
237         
238         if ( a && a.length )
239         for ( var i = 0; i < a.length; i++ ) {
240             var str = a[i].nodeName;
241             if ( str ) {
242                 str = str.toLowerCase();
243                 if ( a[i].id )
244                     str += "#" + a[i].id;
245             } else
246                 str = a[i];
247             r.push( str );
248         }
249
250         return "[ " + r.join(", ") + " ]";
251 }
252
253 /**
254  * Returns an array of elements with the given IDs, eg.
255  * @example q("main", "foo", "bar")
256  * @result [<div id="main">, <span id="foo">, <input id="bar">]
257  */
258 function q() {
259         var r = [];
260         for ( var i = 0; i < arguments.length; i++ )
261                 r.push( document.getElementById( arguments[i] ) );
262         return r;
263 }
264
265 /**
266  * Asserts that a select matches the given IDs
267  * @example t("Check for something", "//[a]", ["foo", "baar"]);
268  * @result returns true if "//[a]" return two elements with the IDs 'foo' and 'baar'
269  */
270 function t(a,b,c) {
271         var f = jQuery(b);
272         var s = "";
273         for ( var i = 0; i < f.length; i++ )
274                 s += (s && ",") + '"' + f[i].id + '"';
275         isSet(f, q.apply(q,c), a + " (" + b + ")");
276 }
277
278 /**
279  * Add random number to url to stop IE from caching
280  *
281  * @example url("data/test.html")
282  * @result "data/test.html?10538358428943"
283  *
284  * @example url("data/test.php?foo=bar")
285  * @result "data/test.php?foo=bar&10538358345554"
286  */
287 function url(value) {
288         return value + (/\?/.test(value) ? "&" : "?") + new Date().getTime() + "" + parseInt(Math.random()*100000);
289 }
290
291 /**
292  * Checks that the first two arguments are equal, with an optional message.
293  * Prints out both expected and actual values on failure.
294  *
295  * Prefered to ok( expected == actual, message )
296  *
297  * @example equals( "Expected 2 characters.", v.formatMessage("Expected {0} characters.", 2) );
298  *
299  * @param Object actual
300  * @param Object expected
301  * @param String message (optional)
302  */
303 function equals(actual, expected, message) {
304         var result = expected == actual;
305         message = message || (result ? "okay" : "failed");
306         _config.Test.push( [ result, result ? message + ": " + expected : message + " expected: " + expected + " actual: " + actual ] );
307 }
308
309 /**
310  * Trigger an event on an element.
311  *
312  * @example triggerEvent( document.body, "click" );
313  *
314  * @param DOMElement elem
315  * @param String type
316  */
317 function triggerEvent( elem, type, event ) {
318         if ( jQuery.browser.mozilla || jQuery.browser.opera ) {
319                 event = document.createEvent("MouseEvents");
320                 event.initMouseEvent(type, true, true, elem.ownerDocument.defaultView,
321                         0, 0, 0, 0, 0, false, false, false, false, 0, null);
322                 elem.dispatchEvent( event );
323         } else if ( jQuery.browser.msie ) {
324                 elem.fireEvent("on"+type);
325         }
326 }