Ingro
Ingro

Reputation: 2841

Qunit + Sinon to test Backbone's model events

These days I'm trying to put up some tests for my first serious Backbone app. I had no problem so far with normal test but now I'm stuck trying to setting up an async test.

Basically my server API return a page with a 500 HTTP code error if I try to save a model with invalid attributes and I want to check if this trigger the right "error" state in Backbone.

I've tried to set-up the test in this way:

asyncTest("Test save Model function", function(){
        expect(1);

        var user = new User({});

        var err_spy = this.spy();
        user.on('error',err_spy);         

        user.save(user,{error:function(){
            start();
            equal( err_spy.callCount, 1, "Callback 'error' called once");

        }});

    });

The problem is that the error callback of the save function overrides the one in the model, so the only way to trigger it would be to do it manually:

user.trigger("error");

I don't think it is a right way to test because in my production environment there is no error callback for model's save function, but on the other hand I don't know how to tell Qunit to wait the ajax response to evaluate the test assertion.

Can someone suggest me a way to make it work? Thank you!

Upvotes: 1

Views: 1105

Answers (1)

Greg Ross
Greg Ross

Reputation: 3498

Something like this should do the trick. I'm going from memory here, but the sinon fake server should allow you to immediately return the 500 error state and subsequently invoke the spied-on function. You might need to tweak the server.respondWith(...) call.

asyncTest("Test save Model function", function(){
            expect(1);

            var user = new User({});

            // Set up a fake 500 response.
            var server = sinon.fakeServer.create();
            server.respondWith(500, {}, "");

            // Create the error callback.
            var err_callback = function(){};

            var err_spy = sinon.spy(err_callback);         

            user.save(user, {error: err_callback});

            server.respond();

            equal( err_spy.callCount, 1, "Callback 'error' called once");

            server.restore();

        });

Upvotes: 1

Related Questions