[英]Karma Jasmine Async Testing not working
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. setTimeout
也在函数中。 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. 现在,在我的测试中,我调用了包含setTimeout的函数,并且收到一个错误消息,即我在
setTimeout
内部使用的元素未定义/为空。
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: 我试图将
done
包含在我的it
,并将函数调用放入setTimeout中,就像这样:
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. 我尝试导入
$timeout
(我实际上使用的是angular),然后将函数调用放入$timeout
然后放入$timeout.flush
,但是没有任何效果。 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. 我不知道,如果你真的打算调用包含从另一个超时内超时功能,但无论如何,这是可行的,如果你被允许改变
callTheFunctionThatContainsTheTimeout
功能。
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();
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.