使用sinon存根原型方法

亚伯拉罕·P

假设我有以下方法:

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

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

现在在我的(摩卡咖啡)测试中:

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

但是,这会将“刷新”打印到控制台。有没有一种方法可以使用sinon存入实时原型?

JME

这就是我要做的:

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

sinon无法正确恢复存根原型方法?

来自分类Dev

sinon无法正确恢复存根原型方法?

来自分类Dev

使用Sinon存根get方法

来自分类Dev

如何使用Sinon存根jQuery方法?

来自分类Dev

存根使用Sinon进行回调的方法

来自分类Dev

如何使用Sinon存根jQuery方法?

来自分类Dev

如何使用 sinon 存根对象方法?

来自分类Dev

如何使用Sinon.js存根动态对象方法?

来自分类Dev

在回调中使用方法的Sinon加密存根

来自分类Dev

在使用chai和sinon的方法中存根诺言

来自分类Dev

如何使用 sinon 在被测函数中存根类方法?

来自分类Dev

sinon:如何存根实例方法

来自分类Dev

用Sinon存根React组件方法

来自分类Dev

sinon.stub不存根原始方法

来自分类Dev

在sinon存根中替换多种方法

来自分类Dev

sinon 存根在 then 调用 promise 中执行的方法

来自分类Dev

使用Sinon沙箱还原间谍/存根功能

来自分类Dev

在Mocha中使用sinon创建请求存根

来自分类Dev

使用sinon存根主干listenTo回调

来自分类Dev

使用Sinon存根pg-promise

来自分类Dev

如何使用sinon存根非对象函数

来自分类Dev

无法使用Mocha / Sinon模拟/存根函数

来自分类Dev

使用Sinon对猫鼬模型进行存根

来自分类Dev

在NodeJS中使用Mocha和Sinon存根ES6类方法

来自分类Dev

如何使用Sinon在单元测试中对猫鼬模型方法进行存根

来自分类Dev

如何使用sinon.js在nodejs中存根全局依赖项的新实例方法

来自分类Dev

在NodeJS中使用Mocha和Sinon存根ES6类方法

来自分类Dev

Sinon-如何对要测试的方法调用的方法存根

来自分类Dev

使用sinon使用必需的参数声明特定的存根调用