2014-07-17 23 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; 
    }); 

}