Last active
July 30, 2018 16:51
-
-
Save chrisdel101/e11e76fb07ff4c6d7989fcb26a26272d to your computer and use it in GitHub Desktop.
Test ajax errors
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//BASIC FUNCTION | |
function fetchJSON (src) { | |
let promise = $.ajax({ | |
dataType: 'json', | |
url: src, | |
error: function (jqXHR, response) { | |
console.log('inside') | |
console.log(jqXHR) | |
var msg = '' | |
if (jqXHR.status === 0) { | |
msg = 'Not connect.\n Verify Network.' | |
} else if (jqXHR.status === 404) { | |
msg = 'Requested page not found. [404]' | |
} else if (jqXHR.status === 500) { | |
msg = 'Internal Server Error [500].' | |
} else if (response === 'parsererror') { | |
msg = 'Requested JSON parse failed.' | |
} else if (response === 'timeout') { | |
msg = 'Time out error.' | |
} else if (response === 'abort') { | |
msg = 'Ajax request aborted.' | |
} else { | |
msg = 'Uncaught Error.\n' + jqXHR.responseText | |
} | |
console.log('fetchJSON failed to complete JSON fetch.', msg) | |
} | |
}) | |
return promise | |
} | |
describe('testing error functionality stubbed ajax', function () { | |
before(function () { | |
let stub = sinon.stub($, 'ajax') | |
// set it to resolve to custom response | |
let fakeJqXHR = { | |
responseJSON: '', | |
responseText: '', | |
status: 404, | |
statusText: 'Not Found' | |
} | |
stub.rejects(fakeJqXHR) | |
}) | |
after(function () { | |
$.ajax.restore() | |
}) | |
it('test error', function () { | |
//use a fake url | |
let results = fetchJSON('fake.com') | |
results.then(result => console.log(result)) | |
// want result to be ' msg = 'Requested page not found. [404]' from fetchJSON error section | |
}) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment