这是个有趣的问题。尽管我可能不会为您提供直接的答案,但我想尝试一下。
下面的代码说明了三个这样的示例(而不是测试)。看到它在行动
var errorFunction = function(jqXHR, status, error) {
console.log('This is errorFunction')
}
var makeAPICall = function(url) {
return $.ajax({
url: url,
fail: errorFunction,
error: errorFunction
});
}
var testFunction = function() {
makeAPICall().done(function(data, status, xh) {
if (xh.status === 0 && xh.readyState == 4) {
errorFunction();
return;
}
console.log("this is successFunction");
}).fail(errorFunction);
}
var getData = function() {
var str = 'ABCDEFGHIJ'
var returnStr = '';
for (var i = 0; i < 3000; i++) {
returnStr += str;
}
return returnStr;
}
describe('test ajax errors', function() {
it('tests a failed call due to huge payload ', function() {
var xhrObj = $.ajax({
url: 'https://jsonplaceholder.typicode.com/posts?userId=' + getData(),
async: false
});
console.log('Below is the xhr object that is breing returned via spy');
console.log(xhrObj);
spyOn(window, 'makeAPICall').and.returnValue(xhrObj);
spyOn(window, 'errorFunction').and.callThrough();
testFunction();
expect(window.errorFunction).toHaveBeenCalled();
});
it('tests a failed call due to some n/w error scenario (readyState->4, status->0)', function() {
var xhrObj = $.ajax({
url: '',
async: false
});
xhrObj.status = 0;
xhrObj.statusText = 'error';
console.log('Below is the xhr object that is breing returned via spy');
console.log(xhrObj);
spyOn(window, 'makeAPICall').and.returnValue(xhrObj);
spyOn(window, 'errorFunction').and.callThrough();
testFunction();
expect(window.errorFunction).toHaveBeenCalled();
});
it('tests a failed call (bad url pattern)', function() {
var xhrObj = $.ajax({
url: 'https://jsonplaceholder.typicode.com/postssss/1',
async: false
});
console.log('Below is the xhr object that is breing returned via spy');
console.log(xhrObj);
spyOn(window, 'makeAPICall').and.returnValue(xhrObj);
spyOn(window, 'errorFunction').and.callThrough();
testFunction();
expect(window.errorFunction).toHaveBeenCalled();
});
});
笔记:
errorFunction
是从 done 调用的 errorFunctionreadySatate === 4 && status === 0
以及所有其他
error
/fail
回调
makeAPICall
返回jqXHR
使用done
&fail
回调的对象。
getData
是一个产生巨大载荷的实用函数:在 test1 中使用
- 第二个测试是关于用空进行虚拟 ajax 调用
url
以模拟readyState->4 & status->0
- 第三个测试模拟通常的错误请求 url 模式测试。
- 对于所有 3 个场景,我都使用了我创建的 jqXHR 对象
$.ajax({some params & async false})
- 设置
async: false
帮助我生成一个虚拟对象并通过spy