协助在类内部插入函数

问题描述 投票:0回答:1

我正在尝试对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和嘲笑,所以我确定我错过了某个步骤。有人知道我哪里出了问题吗?

javascript testing sinon
1个回答
0
投票

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

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

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

使用原型代替Enmap实例效果更好。

© www.soinside.com 2019 - 2024. All rights reserved.