我在模拟成功条件时没有遇到任何问题,但似乎无法理解在使用 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 调用处理程序听到
失败或超时方法?我唯一想尝试的是:
xhr.requests[0].respond(408);
但它不起作用。
我做错了什么或者我误解了什么?非常感谢所有帮助:)
最佳答案
对于超时,sinon的fake timers有帮助。使用它们你不需要将超时设置为 1ms。至于失败,你的做法looks correct大部头书。你能给我们更多的代码,尤其是故障处理程序吗?
关于javascript - 如何使用 Sinon/Qunit 模拟 'timeout' 或 'failure' 响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16560475/