【问题标题】:Mocha.js and sinon spy in Backbone.jsBackbone.js 中的 Mocha.js 和 sinon spy
【发布时间】:2014-09-08 05:59:19
【问题描述】:

我有一个假人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'

有什么帮助吗?

【问题讨论】:

  • 对不起,我不明白它总是给出错误还是只有当你不改变模型属性时?
  • 更改模型标题时,正常调用render方法。但是期望会产生上述错误
  • 无论如何,我在这里发现了类似的问题:stackoverflow.com/questions/8441612/…

标签: unit-testing backbone.js mocha.js sinon spy


【解决方案1】:

实际上,当视图初始化时,它会与它绑定渲染函数。因此,当我们尝试将该渲染函数与 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;
   });

}

【讨论】:

    猜你喜欢
    • 2020-10-21
    • 1970-01-01
    • 2019-09-11
    • 2017-09-19
    • 1970-01-01
    • 2015-11-26
    • 2014-05-20
    • 2016-11-04
    相关资源
    最近更新 更多