1

我有一个假人Backbone.Model

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'

有什么帮助吗?

4

1 回答 1

0

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

尝试这个:

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

}

于 2015-03-06T12:13:57.130 回答