bittersweetryan
bittersweetryan

Reputation: 3443

Testing Backbone.js Model save using Sinon not calling success callback

I'm testing a Backbone.js app using Jasmine and Sinon. I'm trying to verify that clicking a button click calls the Model's save() method and processes the success callback which adds a message to the view's el element. I'm having trouble getting the sinon server to trigger the Model's success callback.

Heres what my spec's beforeEach looks like (the variables in beforeEach are all is var scoped in the describe function).

beforeEach(function(){
    server = sinon.fakeServer.create(); //create the fake server
    server.respondWith([200, { "Content-Type": "text/html", "Content-Length": 2 }, "OK"]); //fake a 200 response

    loadFixtures('signup_modal.html'); //load the fixture

    element = $("#signupModal");
    specSignUp = new SignUp();
    signUpView = new SignUpView({model : specSignUp, el: $("#signupModal")});
});

And this is what the actual test looks like:

it("Should call send request",function(){

    element.find("#signupButton").trigger('click'); //click the button which should trigger save

    server.respond(); //fake the response which should trigger the callback

    expect(element).toContain("#message");
});

While trying to build the implementation of this I created a simple callback method to show me that the success callback is beign triggered:

sendRequest: function(){
    console.log("saving");
    this.model.save(this.model.toJSON(),{success: function(data){
        console.log("success");
        iris.addMessage(this.$("#messageContainer"),"Thank you");
    }});
}

When I run the test the console shows "saving" but the success callback isn't getting called.

Upvotes: 1

Views: 2510

Answers (1)

bittersweetryan
bittersweetryan

Reputation: 3443

Backbone expects the response text to be valid JSON and was bombing out because of the response "OK" in the server.respondWith() method.

Changing the method to:

server.respondWith([200, {"Content-Type":"text/html","Content-Length":2}, '{"OK":"True"}']);

The success callback was being processed successfully.

Upvotes: 4

Related Questions