2014-07-17 20 views
1

兴农间谍,我有一个虚拟Backbone.ModelMocha.js和Backbone.js的

App.Models.Note = Backbone.Model.extend({ 
     default: { 
      title: '' 
     } 
); 

和我的模型像下面这样的Backbone.View

App.Views.NoteView = Backbone.View.extend({ 

    template: ..., 

    initialize: function() { 
     this.listenTo(this.model, "change", this.render); 
     this.render(); 
    }, 

    render: function() { 
     this.$el.html(this.template({ 
      title: this.model.get("title") 
     })); 
     return this; 
    } 
    }); 

为了进行测试,我使用mocha.js + chai + sinon,并且我有以下测试

describe("App.Views.NoteView", function() { 
     beforeEach(function() { 
     this.view = new App.Views.NoteView({ 
       el: this.$fixture, 
       model: new App.Models.Note() 
     }); 
     } 

     afterEach(function() { 
      this.view.model.destroy(); 
     }); 

     it("my try 1", function() { 
      var mySpy1 = sinon.spy(this.view, "render"); 

      this.view.model.set({ 
       title: "a new Title" 
      }); 

      expect(this.view.render).to.have.been.calledOnce; 
     }); 
} 

我试图测试的是如何间谍render方法:当我更改模型属性时,将调用render方法。然而,即使渲染正常执行,测试给我错误

'expected render to be called once but was called 0 times' 

任何帮助吗?

+0

抱歉,不知道我理解它总是给错误或只有当你不更改模型的属性? – Quince

+0

当更改模型标题时,渲染方法正常调用。然而,无论如何,期望产生的错误高于 – geo

+0

,我在这里发现了类似的问题:http://stackoverflow.com/questions/8441612/why-is-this-sinon-spy-not-being-called-when-i-run-此测试?RQ = 1 – geo

回答

0

其实当视图初始化时,它会绑定渲染函数。因此,当我们尝试将该渲染函数与间谍绑定时,它不允许。为此,我们必须在视图初始化之前绑定间谍。

试试这个:

var mySpy1 = null; 
    describe("App.Views.NoteView", function() { 
    beforeEach(function() { 
    mySpy1 = sinon.spy(App.Views.NoteView.prototype, "render"); 
    this.view = new App.Views.NoteView({ 
      el: this.$fixture, 
      model: new App.Models.Note() 
    }); 
    } 

    afterEach(function() { 
     this.view.model.destroy(); 
     //Restore 
     App.Views.NoteView.prototype.render.restore(); 
    }); 

    it("my try 1", function() { 
     this.view.model.set({ 
      title: "a new Title" 
     }); 

     expect(mySpy1.called).to.be.true; 
    }); 

}