Skip to content

Instantly share code, notes, and snippets.

@sdthornton
Last active September 6, 2018 08:00
Show Gist options
  • Save sdthornton/10301352 to your computer and use it in GitHub Desktop.
Save sdthornton/10301352 to your computer and use it in GitHub Desktop.
Testing jQuery.ajax with deferred method - .done() and .fail()
// Probably best to have this within setup
var ajaxStub = sinon.stub($, "ajax", function(event) {
var result = $.Deferred();
result.args = event;
return result;
});
// Usage example
var call = theAjaxCallToTest()
// OR (if theAjaxCallToTest() doesn't return the actual ajax call)
theAjaxCallToTest();
var call = $.ajax.getCall(0).returnValue
// To get the arguments initially passed into ajax call
call.args;
// To return successful ajax call (having used .done() )
call.resolve({ data: "data to be returned after .done()" });
// To return failing ajax call (having used .fail() )
call.reject({ data: "data to be return after .fail()" });
@yairEO
Copy link

yairEO commented Dec 7, 2016

What's the point of the ajaxStub variable if it isn't been used?

@krishna49609
Copy link

@yairEO to restore the stub.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment