javascript - 用 sinon stub 一个原型(prototype)方法

标签 javascript prototype mocha.js sinon stubs

假设我有以下方法:

Controller.prototype.refresh = function () {
  console.log('refreshing');
}

Controller.prototype.delete = function (object) {
  var self = this;
  object.delete({id: object.id}, function () {
    self.refresh();
  });
}

现在在我的(mocha)测试中:

beforeEach(function () {
  var controller = new Controller();
  var proto = controller.__proto__;
  var object = {id: 1, delete: function (options, callback) { callback (); };
  sinon.stub(proto, 'refresh', function {console.log('refreshing stub')});
  controller.delete(object);
});

it('doesnt work', function () {
  expect(object.delete.callCount).to.equal(1);
  expect(proto.refresh.callCount).to.equal(1);
});

但是,这会将“refreshing”打印到控制台。有没有办法使用 sinon 来 stub 实时原型(prototype)?

最佳答案

我会这样做:

describe('test', function() {
  before(function() {
    // stub the prototype's `refresh` method
    sinon.stub(Controller.prototype, 'refresh');
    this.object = {
      id: 1,
      delete: function (options, callback) { callback (); }
    };
    // spy on the object's `delete` method
    sinon.spy(this.object, 'delete');
  });

  beforeEach(function () {
    // do your thing ...
    this.controller = new Controller();
    this.controller.delete(this.object);
  });

  after(function() {
    // restore stubs/spies after I'm done
    Controller.prototype.refresh.restore();
    this.object.delete.restore();
  });

  it('doesnt work', function () {
    expect(this.object.delete.callCount).to.equal(1);
    expect(this.controller.refresh.callCount).to.equal(1);
  });
});

关于javascript - 用 sinon stub 一个原型(prototype)方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27484502/

相关文章:

javascript - 以下语句的函数将存储在该函数的原型(prototype)中的何处

javascript - 带有原型(prototype)的 Object.create()

javascript - 将监听器添加到对象原型(prototype)

unit-testing - 流水应该在哪里放置单元测试?

node.js - 未找到 Mocha 测试 : "0 passing"

javascript - 我的 .done() Mocha 测试出了什么问题?

javascript - JQuery 添加选择不起作用

php - 寻找用于JS或PHP的简单Oauth实现

javascript - 如何遍历 html 元素并使用 javascript/jQuery 获取组合时间?

javascript - 如何从谷歌地图获取纬度和经度边界 x y 和缩放参数