我在整理模拟成功条件时没有问题,但似乎无法理解在使用Sinon和Qunit测试和 ajax 函数时如何模拟失败/超时条件:
我的设置是这样的:
$(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 调用处理程序hear
成为失败或超时方法?我唯一能想到尝试的是:
xhr.requests[0].respond(408);
但它不起作用。
我做错了什么或我误解了什么?非常感谢所有帮助:)