Javascript 协助在类中存根函数

Javascript 协助在类中存根函数,javascript,testing,sinon,Javascript,Testing,Sinon,我正在尝试stub Enmap的set方法。这是我的函数(在我的队列类中): 这就是我到目前为止所做的: var enmapStub; beforeEach(() => { enmapStub = sinon.stub(new enmap(), 'set'); }); afterEach(() => { enmapStub.restore(); }); 然后在我的测试中使用它: describe('#save', () => { it

我正在尝试stub Enmap的set方法。这是我的函数(在我的
队列
类中):

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

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和mocking,所以我肯定我错过了一步什么的。有人知道我哪里出错了吗?

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

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

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

将原型而不是Enmap实例存根工作得更好

能否尝试将范围定义为this.enmapStub?我曾经使用过这种全局对象,它确实有效。这样,您就不需要全局地定义它了。我这样做了,它对测试结果没有影响,仍然没有调用存根。
this.enmapStub;
beforeEach(() => {
  this.enmapStub = sinon.stub(enmap.prototype, 'set');
});

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