Skip to content

Instantly share code, notes, and snippets.

@chrisdel101
Last active July 30, 2018 16:51
Show Gist options
  • Save chrisdel101/e11e76fb07ff4c6d7989fcb26a26272d to your computer and use it in GitHub Desktop.
Save chrisdel101/e11e76fb07ff4c6d7989fcb26a26272d to your computer and use it in GitHub Desktop.
Test ajax errors
//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