[英]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
,我有以下傳遞測試:
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
的回調氣味很糟糕,如果我做了太多的話,它會減慢我的測試套件的速度。
但是,我覺得意圖是相當清楚的,它似乎確實測試了我想要的。
有沒有更好的方法,請您解釋一下您的答案中發生了什么?
傳遞您的匿名函數以將表單顯示為參數,並在追加后在回調中調用它。 為了確保它被調用,你可以使它成為一個$ .ajax請求,它也包含錯誤回調。
這樣,當get請求完成且沒有多余時間或過早調用時,就會調用它。
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);
});
});
你應該使用sinons fakeServer 。 當$.ajax
調用完成后,這將立即調用您的ajax回調。 看到這個jsFiddle
before(function(){
var server = sinon.fakeServer.create();
server.respondWith('response');
})
it("showForm calls jQuery.append", function () {
var spy = sinon.spy($.fn, "append");
presenter.showForm('/fake');
server.respond();
expect(spy.called).to.be.equal(true);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.