这是一个有趣的问题。虽然我可能不会为您提供直接的答案,但我想试一试。
下面的代码说明了三个这样的例子(而不是测试)。见action
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 调用的 errorFunction
如果readySatate === 4 && status === 0 以及所有其他
error/fail 回调
-
makeAPICall 返回使用了 done 和 fail 回调的 jqXHR。
-
getData 是一个实用函数,可生成巨大的有效载荷:在 test1 中使用
- 第二个测试是关于用空
url进行虚拟ajax调用以模拟readyState->4 & status->0
- 第三个测试模拟了通常的错误请求 url 模式测试。
- 对于所有 3 个场景,我使用了由
$.ajax({some params & async false}) 创建的 jqXHR 对象
- 设置
async: false 帮助我生成一个虚拟对象并通过spy 将其传递给函数