-
-
Save toddb/2362021 to your computer and use it in GitHub Desktop.
Jasmine spy syntactic sugar for dealing with success/error callbacks (aka jQuery.ajax)
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
/** | |
* 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