Sunday, March 6, 2011

Popcorn.js - Automated Plugin Unit Tests

I took the liberty of developing a unit test page for plugins. Originally, I just made a series of links that load the selected unit test into an iframe and called it a day. I knew it was too easy. Why not make them automated?

This was all made possible by this function: window.setTimeout(). Something I didn't know about setTimeout is that it runs "asynchronously", kind of like a thread in Java. I found this out when I put it in a for loop.

for (var i = 0; i < numOfTests; i++){
setTimeout(function(){output.src = testUrl[i];}, 5000);
}

This produced some very odd results because setTimeout didn't find it necessary to care about the nice for loop I put it in. Either i would always equal the same number, or it would equal all sorts of random numbers (negative ones included). Fortunately I found a fix on the web using closures:

for ( var i = 0, delay = 0; i < 10; delay += testDur[i], i++ ) {
(function ( j ) {
setTimeout(function() {
setTest( j );
}, delay);
})( i );
}

By doing this, the value of i (at the time it is called in the for loop) is saved within the closure. So now you can call setTimeout and be confident your iterator is working for you. I learned a lot today :)

No comments:

Post a Comment