I'm currently trying to test something that uses async tasks, concrete I have the following lines:
setTimeout(function(){
//do something
},300);
The setTimeout
is in a function as well. Now in my test, I call this function, that contains the setTimeout and I'm getting an error, that the element I'm using inside of setTimeout
is not defined/null.
Now I tried out various ways but none seems to work.
I tried to include done
into my it
and put the function call in a setTimeout, just like so:
setTimeout(function(){
callTheFunctionThatContainsTheTimeout();
done();
});
Doesn't work. I tried to import $timeout
(I'm actually using angular), and then put the function call in $timeout
and put a $timeout.flush
afterwards, but nothing works. Does anybody know what I do wrong and how I can do it right?
I don't know if you really intended to call a function that contains the timeout from inside another timeout, but anyway this is feasible, if you are allowed to change the callTheFunctionThatContainsTheTimeout
function.
The function would look something like:
function callTheFunctionThatContainsTheTimeout(callback) {
setTimeout(function(){
console.log('ooo'); // do something here
callback(); // execute a callback function
},300);
}
And the test would be like:
it('something to do', function(done){
setTimeout(function(){
callTheFunctionThatContainsTheTimeout(function(){ // the callback function
expect(2+2).toEqual(4); // do your tests here
done();
});
},200);
});
And if you do not need a second timeout, the test would look like:
it('something to do', function(done){
callTheFunctionThatContainsTheTimeout(function(){ // the callback function
expect(2+2).toEqual(4); // do your test here
done();
});
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.