【问题标题】:Assistance stubbing a function inside class协助存根类内的函数
【发布时间】:2019-10-11 15:18:13
【问题描述】:

我正在尝试存根 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 和一般的嘲笑,所以我确定我错过了一步或其他什么。有谁知道我哪里出错了?

【问题讨论】:

  • 您可以尝试将范围定义为this.enmapStub 吗?我已经使用过这种全局对象并且它有效。这样,您就不需要在全局范围内定义它。
  • 我这样做了,它对测试结果没有影响,仍然没有调用存根。

标签: javascript testing sinon


【解决方案1】:

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

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

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

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

【讨论】:

    猜你喜欢
    • 2016-12-26
    • 1970-01-01
    • 2021-07-15
    • 1970-01-01
    • 2011-11-29
    • 2020-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多