Created
April 14, 2016 10:55
-
-
Save jli168/f53fd3b298dd080135b98a10afa507ec to your computer and use it in GitHub Desktop.
unit test: favorite way to mock backbone endpoint and test callbacks, using `$ajax` and promise
This file contains 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
////////////////////////// | |
// backbone fetch method | |
////////////////////////// | |
// set up fetch & callbacks | |
myCollection.fetch( options ) | |
.done( this.successHandler.call( this ) ) | |
.fail( this.errorHandler.call( this ) ); | |
////////////////////////// | |
// unit test | |
////////////////////////// | |
// now we need to test that successHandler get called when the fetch is successful, | |
// and errorHandler get called when it is not | |
it( "fetch is successful, successHandler get called", function() { | |
var d = new $.Deferred(), | |
stub = sandbox.stub( $, "ajax" ).returns( d.promise() ); | |
// resolve the promise: | |
d.resolve( { data: "bar" } ); | |
sandbox.stub( myCollection, "successHandler" ); | |
myCollection.fetch(); | |
expect( myCollection.successHandler ).to.have.been.calledWith( { data: "bar" } ); | |
}); | |
it( "fetch failed, errorHandler get called", function() { | |
var d = new $.Deferred(), | |
stub = sandbox.stub( $, "ajax" ).returns( d.promise() ); | |
// reject the promise: | |
d.reject( "foo1", "foo2", "foo3" ); | |
sandbox.stub( myCollection, "errorHandler" ); | |
myCollection.fetch(); | |
expect( myCollection.errorHandler ).to.have.been.calledWith( "foo1", "foo2", "foo3" ); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment