I'm writing a test for a Backbone View to test that the render function is being called after fetching the model. The test is:
beforeEach(function () {
$('body').append('<div class="sidebar"></div>');
profileView = new ProfileView();
});
it('should call the render function after the model has been fetched', function (done) {
profileView.model = new UserModel({md5: 'd7263f0d14d66c349016c5eabd4d2b8c'});
var spy = sinon.spy(profileView, 'render');
profileView.model.fetch({
success: function () {
sinon.assert.called(spy);
done();
}
});
});
I'm using Sinon Spies to attach a spy object to the render function of the profileView view object.
The view is:
var ProfileView = Backbone.View.extend({
el: '.sidebar'
, template: Hogan.compile(ProfileTemplate)
, model: new UserModel()
, initialize: function () {
this.model.bind('change', this.render, this);
this.model.fetch();
}
, render: function () {
$(this.el).html(this.template.render());
console.log("Profile Rendered");
return this;
}
});
After the fetch is called in the test, the change event is firing and the view's render function is getting called, but the Sinon Spy isn't detecting that render is being called and fails.
As an experiment, I tried calling the render function in the test to see if the Spy identified it:
it('should call the render function after the model has been fetched', function (done) {
profileView.model = new UserModel({md5: 'd7263f0d14d66c349016c5eabd4d2b8c'});
var spy = sinon.spy(profileView, 'render');
profileView.render();
profileView.model.fetch({
success: function () {
sinon.assert.called(spy);
done();
}
});
});
The Spy detected the called was made in the case above.
Does anyone know why the Spy isn't identifying the render call in my initial test?
The problem is that during construction of the view, the initialize function binds an event directly to the render function. You cannot intercept this event with a spy because the binding has already happened before you setup your spy (which you do after construction).
The solution is to spy on the prototype before you construct the view. So you will have to move the spy into the beforeEach, or move construction of the view into the test.
To setup the spy:
this.renderSpy = sinon.spy(ProfileView.prototype, 'render');
this.view = new ProfileView();
Then later, to remove the spy:
ProfileView.prototype.render.restore()
This will then spy on 'ordinary' calls to render, as well as the change event from the model.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With