在测试JavaScript时,还有比setTimeout更好的方法来等待asnyc回调吗? [英] Any better way than setTimeout to wait for asnyc callbacks when testing JavaScript?
问题描述
鉴于此代码:
showForm = function (url) {
return $.get(url, function (html) {
$('body').append();
});
};
使用 sinon.js
时, jQuery.mockjax.js
和 expect.js
,我有以下通过测试:
When using sinon.js
, jQuery.mockjax.js
and expect.js
, I have the following passing test:
it("showForm calls jQuery.append", function () {
$.mockjax({
url: '/fake'
});
var spy = sinon.spy($.fn, "append");
presenter.showForm('/fake');
setTimeout(function () {
expect(spy.called).to.be.equal(true);
}, 1000);
});
使用 setTimeout
函数等待来自异步 $。get
的回调闻起来很糟糕,如果我做了太多的话,它会减慢我的测试套件。
Using the setTimeout
function to wait on the callback from the asynchronous $.get
smells bad and it will slow down my test suite if I do too much of it.
然而,我觉得这个意图相当清楚,而且它似乎确实测试了我想要的东西。
However, I feel that the intent is reasonably clear and it does seem to test exactly what I want.
有没有更好的方法,请你解释一下是什么在你的答案中继续?
Is there a better way and can you please explain what's going on in your answer?
推荐答案
传递你的匿名函数将表单显示为参数并在回调后调用它附加。为了确保它被调用,你可以使它成为一个$ .ajax请求,它也包含错误回调。
Pass your anonymous function to show form as a parameter and have it called in the callback after the append. To ensure its called you could make it an $.ajax request that covers the error callback as well.
这样就可以在get请求完成且没有多余时间或过早调用时调用它。
This way it is called exactly when the get request finishes with no excess time or called too early.
showForm = function (url, callback) {
return $.get(url, function (html) {
$('body').append();
if(callback != undefined)
callback();
});
};
it("showForm calls jQuery.append", function () {
$.mockjax({
url: '/fake'
});
var spy = sinon.spy($.fn, "append");
presenter.showForm('/fake', function (){
expect(spy.called).to.be.equal(true);
});
});
这篇关于在测试JavaScript时,还有比setTimeout更好的方法来等待asnyc回调吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!