Skip to content

Instantly share code, notes, and snippets.

@jli168
Created April 14, 2016 10:55
Show Gist options
  • Save jli168/f53fd3b298dd080135b98a10afa507ec to your computer and use it in GitHub Desktop.
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
//////////////////////////
// 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