【问题标题】:sinon: when stubs restored?sinon:stubs什么时候恢复?
【发布时间】:2017-08-23 14:26:41
【问题描述】:

我正在使用 sinon 1.17.6。以下是我的代码:

  it('should', sinon.test(function(/*done*/) {
      const stubtoBeStubbedFunction = this.stub(this.myObj, 'toBeStubbedFunction');
      const instance = {
        id: 'instanceId',
        tCount: 3,
      };
      console.log('0 toBeStubbedFunction', this.myObj.toBeStubbedFunction);
      return this.myObj.toBeTestedFunction(instance)
        .then(() => {
          console.log('3 toBeStubbedFunction', this.myObj.toBeStubbedFunction);
          expect(stubtoBeStubbedFunction.calledOnce).to.be.true();
          // done();
        });
  }));


MyClass.prototype.toBeTestedFunction = function toBeTestedFunction(input) {
  const metaData = {};
  this.log.debug('toBeTestedFunction');
  if (input.tCount === 0) {
    console.log('1', this.toBeStubbedFunction);
    return bluebird.resolve((this.toBeStubbedFunction(metaData)));
  }

  return this.myClient.getData(input.id)
    .bind(this)
    .then(function _on(res) {
      if (res) {
        console.log('2', this.toBeStubbedFunction);
        this.toBeStubbedFunction(metaData);
      }
    })
    .catch(function _onError(err) {
      throw new VError(err, 'toBeTestedFunctionError');
    });
};

console.log 输出:

0 toBeStubbedFunction toBeStubbedFunction
2 function toBeStubbedFunction(meta) {
  // real implementation
}
3 toBeStubbedFunction function toBeStubbedFunction(meta) {
  // real implementation
}

似乎在测试运行期间,已恢复存根函数。我认为sinon.test() 应该在返回的承诺解决或捕获后恢复存根(存根应该在console.log('2', this.toBeStubbedFunction); 运行后恢复)。 为什么?我使用done 来解决我的问题。但是有更好的解决方案吗?我可能会错误地使用mochasinon

欢迎任何 cmets。谢谢

【问题讨论】:

    标签: javascript promise mocha.js sinon


    【解决方案1】:

    Sinon 1.x 提供的sinon.test 方法完全忽略了测试返回的promise,这意味着它不会在重置它创建的沙箱之前等待promise 解决。

    Sinon 2.x 从 Sinon 中删除了 sinon.test,并将其作为自己的独立 sinon-test package 旋转。最初和Sinon 1.x提供的sinon.test方法有同样的问题,但问题是reported and resolved

    sinon-test 的对等依赖项当前将 Sinon 的最低版本设置为 2.x,因此您至少必须升级 Sinon 并将sinon-test 添加到您的测试套件中才能支持 Promise 并使用测试包装器提供sinon-test

    或者您可以放弃包装器并编写自己的 before/beforeEachafter/afterEach 钩子来为您创建和重置沙箱。我已经使用 Sinon 很多年了(肯定是从 1.x 系列开始,甚至可能更早),而这一直是我所做的。我什至不知道sinon.test,直到我看到你几天前提出的另一个问题。

    【讨论】:

      猜你喜欢
      • 2016-01-06
      • 1970-01-01
      • 2014-04-29
      • 2010-09-11
      • 1970-01-01
      • 2013-10-19
      • 2011-09-28
      • 2010-09-18
      • 2010-09-25
      相关资源
      最近更新 更多