我已經沒有問題,整理出嘲諷的成功條件,但似乎無法捉摸如何使用興農和Qunit測試和Ajax功能時嘲笑失敗/超時條件:如何使用Sinon/Qunit模擬「超時」或「失敗」響應?
我的設立是這樣的:
$(document).ready(function() {
module("myTests", {
setup: function() {
xhr = sinon.sandbox.useFakeXMLHttpRequest();
xhr.requests = [];
xhr.onCreate = function (request) {
xhr.requests.push(request);
};
myObj = new MyObj("#elemSelector");
},
teardown: function() {
myObj.destroy();
xhr.restore();
}
});
和我的成功案例測試,開心地運行和接收/通過接收到的數據傳遞到成功的方法是這樣的:
test("The data fetch method reacts correctly to receiving data", function() {
sinon.spy(MyObject.prototype, "ajaxSuccess");
MyObject.prototype.fetchData();
//check a call got heard
equal(1, xhr.requests.length);
//return a success method for that obj
xhr.requests[0].respond(200, { "Content-Type": "application/json" },
'[{ "responseData": "some test data" }]');
//check the correct success method was called
ok(MyObj.prototype.ajaxSuccess.calledOnce);
MyObj.prototype.ajaxSuccess.restore();
});
不過,我不知道是什麼我應該代替推杆這個:
xhr.requests[0].respond(200, { "Content-Type": "application/json" },
'[{ "responseData": "some test data" }]');
使我的ajax調用處理程序「聽到」一個失敗或超時的方法?我唯一能想到的就是這樣:
xhr.requests[0].respond(408);
但它不起作用。
我在做什麼錯,或者我誤解了什麼?所有幫助非常感謝:)
超時是在給定時間內缺乏響應,所以你不能返回超時 –
我希望sinon可能會克服,併爲所有類型的響應提供標準化的接口。如果我不能使用sinon'返回'超時 - 那麼我該如何僞造一個呢? –
我不知道sinon所以也許有一些特定的,但通常你設置超時說1ms,並使用服務器或模擬服務器端的等待。 –