为什么使用jasmine的运行和waitFor函数是必要的? [英] Why is using jasmine's runs and waitFor function necessary?
问题描述
我正在测试一段异步代码,其内容如下所示:
I'm testing an asynchronous piece of code with something that looks like this:
randomService.doSomething().then(function() {
console.log('I completed the operation!');
});
令人惊讶(对我而言)我发现它只是成功(即显示console.log输出)当包装在jasmine的中运行
函数时,如下所示:
Surprisingly (to me) I've found that it only succeeds (ie console.log output is shown) when wrapped inside jasmine's runs
function, like so:
var isDone = false;
runs(function() {
randomService.doSomething().then(function(data) {
console.log('I completed the operation!');
isDone = true;
});
});
waitsFor(function() {
return isDone;
}, 'Operation should be completed', 1000);
据我了解,我认为 waitsFor
只是为了延迟代码,换句话说我会使用它,如果我有更多的代码,我必须延迟,直到异步调用完成后 - 换句话说,我会认为我没有理由使用运行
和 waitsFor
因为这段代码后没有任何内容,对吧?这是我从阅读这个问题得到的印象:茉莉花运行和等待什么实际上做了什么?但显然我在某些时候已经把自己搞砸了。
As I understood it, I thought waitsFor
was only to delay the code, in other words I would use it if I had more code that I had to delay until after the asynchronous call completed - in other words, I would have thought that there'd be no reason for me to use runs
and waitsFor
since there's nothing that comes after this bit of code, right? That's the impression I got from reading this question: What do jasmine runs and waitsFor actually do? but obviously I've gotten myself mixed up at some point.
有没有人对此有任何想法?
Does anyone have any thoughts on this?
编辑:
这是一个有更多细节问题的Plunker:
http://plnkr.co/edit/3qnuj5N9Thb2UdgoxYaD?p=preview
注意第一个测试总是通过,第二个测试总是通过测试失败了。
另外,我确定我之前应该提到这个,但这是使用angularJS和Jasmine 1.3。
Note how the first test always passes, and the second test fails as it should. Also, I'm sure I should have mentioned this before, but this is using angularJS, and Jasmine 1.3.
推荐答案
<我觉得我发现了这个问题。以下是文章: http:// blogs.lessthandot.com/index.php/webdev/uidevelopment/javascript/testing-asynchronous-javascript-w-jasmine/
基本上这是必要的,因为Jasmine在完成测试之前不等待异步调用完成。根据这篇文章,如果一个调用需要足够长的时间并且稍后会有更多的测试,那么先前测试中的异步回调中的 expect
语句最终可以完全在另一个测试中执行,原始测试完成后。
Essentially it's necessary because Jasmine doesn't wait for the asynchronous calls to finish before it completes a test. According to the article, if a call takes long enough and there are more tests later, an expect
statement in an asynchronous callback in a previous test could finally execute in a different test entirely, after the original test completed.
使用运行
和等待
解决问题,因为他们强迫茉莉等待 waitsFor
完成,然后再进行下一次测试;这是一个没有实际意义的点,但是因为显然Jasmine 2.0以比1.3更好的方式处理异步测试,淘汰运行
和 waitsFor
。
Using runs
and waitsFor
solve the problem because they force jasmine to wait for the waitsFor
to finish before proceeding to the next test; This is a moot point however because evidently Jasmine 2.0 addresses asynchronous testing in a better way than 1.3, obsoleting runs
and waitsFor
.
这篇关于为什么使用jasmine的运行和waitFor函数是必要的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!