代码之家  ›  专栏  ›  技术社区  ›  Lorraine Bernard

当Backbone.Model更改时,我应该如何检查Backbone.View

  •  0
  • Lorraine Bernard  · 技术社区  · 12 年前

    我正在为一个使用backbone和backbone.marionette通过jasmine的web应用程序编写测试。

    我的问题是:
    1) 当模型发生变化时,我是否应该检查视图,看看视图是否受到影响?
    2) 如果是,正确的方法是什么。例如在以下情况(1)中

    第页:
    我想避免更改模板文件


    (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;
        }
    });
    
    1 回复  |  直到 12 年前
        1
  •  1
  •   Torsten Walter    12 年前

    如果视图侦听模型事件,则可以使用间谍来检查更改模型时是否调用了侦听器。

    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();
        });
    });
    

    当然,如果你有 render 作为听众。

    就我个人而言,我不会在Jasmine中明确检查渲染,因为只有在浏览器中运行测试时,这才有效。例如,如果您将Jasmin用于Maven,那么您就有Rhino,因此没有DOM可供使用。