Francium123
Francium123

Reputation: 451

Testing Backbone View when collections fetch success callback calls render

I am using Jasmine and Sinon to test my Backbone application but I am running in to some trouble. I am attempting to test that render gets called when my view is initialized

I have the following View:

var MyView = Backbone.View.extend({
    el: '#myElement',
    initialize : function() {
        var that = this;
        this.collection.fetch({
            error : function() {
                alert("error!");
            },
            success : function() {
                that.render();
            }
        });
    },

    render : function() {
        this.collection.each(this.renderItem);
    }

    ...

My test

it('Should call render when view is instantiated', function(){          
                spyOn(MyView.prototype, 'render');
                var myCollection = new MyCollection();
                this.view = new MyView({collection: myCollection});
                expect(MyView.prototype.render).toHaveBeenCalled();
        });

The problem is that the expect() gets called before the success callback of my fetch has been executed. What is the best way to resolve this?

Upvotes: 1

Views: 2656

Answers (1)

Andreas Köberle
Andreas Köberle

Reputation: 110922

So the problem here is that you test 2 things, the view and the collection. You should stub the collection and just test the view:

sinon.stub(myCollection, 'fetch').yieldsTo('success') // will immediately call the success methode
sinon.stub(myCollection, 'each').callsArg(0) // will immediately call this.renderItem

Also its not a good idea to spy on the class you wanna test. In your case you should test that the innerHTMl of your view has changed as expected after this.renderItem was called

Upvotes: 2

Related Questions