首页 > 解决方案 > 协助存根类内的函数

问题描述

我正在尝试存根 Enmap 的 set 方法。这是我的功能(在我的Queue课堂内):

// save queue for persistence
  save() {
    enmap.set('queue', this._queue);
}

这是我到目前为止所做的:

var enmapStub;
  beforeEach(() => {
    enmapStub = sinon.stub(new enmap(), 'set');
  });

  afterEach(() => {
    enmapStub.restore();
  });

然后在我的测试中使用它:

describe('#save', () => {
    it("calls enmap.set", () => {
      new Queue({ queueName: 'test', queue: [1,2,3] }).save();
      expect(enmapStub).to.have.been.calledOnce;
    });
  });

测试失败是因为没有调用 enmapStub?

sinon一般都是使用和嘲笑的新手,所以我确定我错过了一步或其他东西。有谁知道我哪里出错了?

标签: javascripttestingsinon

解决方案


我确定了这个问题,因为我想模拟另一个类 ( Enmap) 的 set 方法,所以我需要像这样对 Enmap 的原型进行存根:

this.enmapStub;
beforeEach(() => {
  this.enmapStub = sinon.stub(enmap.prototype, 'set');
});

afterEach(() => {
  this.enmapStub.restore();
});

存根原型而不是 Enmap 的实例效果更好。


推荐阅读