Lorraine Bernard
Lorraine Bernard

Reputation: 13400

How should I check the Backbone.View when Backbone.Model changes

I am writing tests for a web application using backbone and backbone.marionette through jasmine.

My questions are:
1) should I check the view when something change in the model to see if the view is affected?
2) if yes, what is the proper way…. for example in the following case (1)

P.S.:
I would like to avoid to change the template file


(1)

// template 

<ul class="widget-points-status">
    <li>
        <strong>{{ remaining_points }}</strong>
    </li>
    <li>
        <strong>{{ given_points }}</strong>
    </li>
    <li>
        <strong>{{ received_points }}</strong>
    </li>
</ul>

// My jasmine test could be:

describe('Changing the model:', function () {
    beforeEach(function () {
        app.currentUser.set({
            given_points: 111980,
            received_points: 892378,
            remaining_points: 435412
        });
    });

    it('it should change the points', function () {
        var pointsView = this.view.$el.text().match(/\d{1,}/)[0];
        expect(pointsView).toMatch(app.currentUser.get('given_points'));
        expect(pointsView).toMatch(app.currentUser.get('received_points'));
        expect(pointsView).toMatch(app.currentUser.get('remaining_points'));
    });

});

var pointsView = Backbone.View.extend({

    className: 'widget widget-profile',

    initialize: function () {
        app.currentUser.on('change', this.render, this);
    },

    render: function () {
        this.$el.html(profileTemplate(app.currentUser.toJSON()));

        return this;
    }
});

Upvotes: 0

Views: 218

Answers (1)

Torsten Walter
Torsten Walter

Reputation: 5782

If your view listens to model events, you can use a spy to check if your listener is called when you change the model.

describe("A Backbine View", function() {

    beforeEach(function() {
        spyOn(pointsView, "changePoints");
    });

    it("should listen to model changes", function() {
        app.currentUser.set("points", 2);
        expect(pointsView.changePoints).toHaveBeenCalled();
    });
});

Of course the same concept applies if you have render as the listener.

Personally I wouldn't check the rendering explicitly in Jasmine since this will only ever work if you run the tests in a browser. If you use Jasmin for Maven for example you have Rhino and therefore no DOM to work with.

Upvotes: 1

Related Questions