我已经没有问题,整理出嘲讽的成功条件,但似乎无法捉摸如何使用兴农和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,并使用服务器或模拟服务器端的等待。 –