【问题标题】:Testing Backbone View when collections fetch success callback calls render当集合获取成功回调调用渲染时测试主干视图
【发布时间】:2013-04-04 15:28:32
【问题描述】:

我正在使用 Jasmine 和 Sinon 测试我的 Backbone 应用程序,但遇到了一些麻烦。我正在尝试测试初始化​​视图时是否调用了渲染

我有以下观点:

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

    ...

我的测试

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

问题是在我的 fetch 的成功回调执行之前调用了 expect()。解决此问题的最佳方法是什么?

【问题讨论】:

  • 你为什么不在你的渲染方法中加入类似 alert 或 console.log 的东西?
  • 我正在编写一个自动化测试套件。将来我想关注测试驱动开发。

标签: testing backbone.js jasmine backbone-views sinon


【解决方案1】:

所以这里的问题是你测试了两件事,视图和集合。您应该存根集合并仅测试视图:

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

监视您要测试的课程也不是一个好主意。在您的情况下,您应该测试在调用 this.renderItem 后视图的 innerHTMl 是否已按预期更改

【讨论】:

  • 感谢您的回答和建议,非常有帮助!我意识到这完全是另一个问题,但是如果我的 renderItem 方法然后实例化一个新视图,我该如何存根呢?我正在使用requirejs。再次感谢。
  • 请您在一个新问题中提出这个问题。
猜你喜欢
  • 1970-01-01
  • 2012-07-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多