Problems unit testing setInterval function in Javascript
I am having difficulties testing window.setInterval function in my Javascript file. Below is the scenario... basically I have a setInterval function in a function which I want to test:
var dummy = false; // global variable not set anywhere else
var INTERVAL_TIME = 20; // global variable not set anywhere else
function myFunction()
{
var id = window.setInterval(function() {
if (...)
{
window.clearInterval(id);
}
else
{
if(...)
{
dummy = true;
}
}
}, INTERVAL_TIME);
}
And I have the following test code in JsTestDriver:
TestMyFunction.prototype.test_myFunction() {
myFunction();
assertTrue(dummy);
}
Everytime the te开发者_Go百科st executes, it fails and says dummy is false, as if the entire setInterval function was never called. I tried playing around with the interval with no success. If I put in an alert in the else clause, it popped up in a fraction of a second and disappeared (and test still fails).
The code works. I have a feeling that it is a timing issue, where the test finishes earlier than the setInterval function, hence complaining that dummy is not set to true. Any suggestions/solutions to this problem?
Thanks.
Why not put a setTimeout in your test, to delay checking for the value of dummy until after 25ms.
I used the JsUnitMockTimeout.js to simulate the setInterval function. It worked like a gem :)
assertTrue(dummy);
is executed before the timeInterval of 20ms. Since you are using interval, do you perdiodically poll for the dummy value? First time poll is going to give you false
unless you have a super slow PC.
It appears that "JsTestDriver cannot perform asynchronous testing". The only JS Unit testing frame work I have used with async support is Qunit.
Qunit has asyncTest which will work with ajax or timeouts.
PS: there a brand new JS Testing framework Evidence. I have not tried it.
精彩评论