Skip to content

Instantly share code, notes, and snippets.

@esbie
Created October 30, 2011 06:18
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save esbie/1325575 to your computer and use it in GitHub Desktop.
Save esbie/1325575 to your computer and use it in GitHub Desktop.
Jasmine spy syntactic sugar for dealing with success/error callbacks (aka jQuery.ajax)
/**
* An extension that always calls success when a spy is called.
*
* @example
* spyOn(foo, 'bar').andCallSuccessWith("baz");
* var options = {
* success: jasmine.createSpy();
* }
* foo.bar(options);
* expect(options.success).toBeCalledWith("baz");
*/
jasmine.Spy.prototype.andCallSuccessWith = function() {
var args = arguments;
this.plan = function(options) {
//if the last arg is a function instead of options,
//assume that it is the success function
var lastArg = arguments[arguments.length-1];
if (lastArg instanceof Function) {
lastArg.apply(this, args);
} else {
options.success.apply(this, args);
}
};
return this;
};
/**
* An extension that always calls error when a spy is called.
*
* @example
* spyOn(foo, 'bar').andCallErrorWith("baz");
* var options = {
* error: jasmine.createSpy();
* }
* foo.bar(options);
* expect(options.error).toBeCalledWith("baz");
*/
jasmine.Spy.prototype.andCallErrorWith = function() {
var args = arguments;
this.plan = function(options) {
options.error.apply(this, args);
};
return this;
};
/**
* An extension that always calls complete when a spy is called.
*
* @example
* spyOn(foo, 'bar').andCallCompleteWith("baz");
* var options = {
* complete: jasmine.createSpy();
* }
* foo.bar(options);
* expect(options.complete).toBeCalledWith("baz");
*/
jasmine.Spy.prototype.andCallCompleteWith = function() {
var args = arguments;
var origPlan = this.plan;
this.plan = function(options) {
//if there was an original plan, enact it now!
origPlan && origPlan.apply(this, args);
options.complete.apply(this, args);
};
return this;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment