This is an interesting question. Although I might not give you a direct answer to this question, I would like to strike him.
The code below shows three such examples (rather tests). See It in 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(); }); });
Notes:
errorFunction
- the errorFunction function, called from done if readySatate === 4 && status === 0
, as well as all other error
/ fail
callbacksmakeAPICall
returns jqXHR
, which uses done
and fail
callbacks.getData
is a utility function that generates a huge payload: used in test1- the second test is to create a dummy ajax call with an empty
url
to simulate readyState->4 & status->0
- The third test mimics a regular test of the URL of an invalid request.
- for all three scenarios, I used the jqXHR object that I created using
$.ajax({some params & async false})
async: false
helps me create a dummy object and pass it functions through spy
source share