sinon: 存根什么时候恢复?

sinon: when stubs restored?

我正在使用 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
}

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

欢迎任何评论。谢谢

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

Sinon 2.x removed sinon.test from Sinon and spun it as its own separate sinon-test package. It initially had the same problem as the sinon.test method provided by Sinon 1.x but the problem was reported and resolved.

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

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