sinon 没有正确恢复存根原型方法?

sinon not properly restoring stubbed prototype method?

看来 sinon 可能没有正确恢复存根原型。在我将其报告为错误之前,有人可以告诉我我做错了什么吗?

这失败了:

以下代码似乎正确存根 net.Socket.prototype.connect,但没有正确恢复它:后续测试 -- 与此代码无关,但依赖于 net.Socket -- 开始失败:

it('passes host and port to the net.Socket().connect()', sinon.test(function() {
  var stub = sinon.stub(net.Socket.prototype, 'connect');
  var host = '11.22.33.44';
  var port = 1234;
  var il = new InstrumentLink(host, port);
  expect(stub).to.have.been.calledWith(host, port);
}));

请注意,我正在使用 'wrapped function' sinon.test(function() ...) 来创建和恢复沙箱。

这个有效:

另一方面,下面的代码正确地恢复了存根,我的测试套件的其余部分继续 运行:

var stub;
beforeEach(function() {
  stub = sinon.stub(net.Socket.prototype, 'connect');
});
afterEach(function() {
  stub.restore();
});

it('passes host and port to the net.Socket().connect()', function() {
  stub = sinon.stub(net.Socket.prototype, 'connect');
  var host = '11.22.33.44';
  var port = 1234;
  var il = new InstrumentLink(host, port);
  expect(stub).to.have.been.calledWith(host, port);
});

问题:

这是我的错误还是驾驶舱错误?我更喜欢包装函数方法而不是显式 beforeEachafterEach,所以让它工作会很好。

sinon.js 文档 (http://sinonjs.org/docs/#sandbox) 指出:

so if you don’t want to manually restore(), you have to use this.spy() instead of sinon.spy() (and stub, mock).

这可能有助于解决您的问题。

除此之外,请允许我提一下,我通常使用这样的 sinon 沙盒:

var sinon = require('sinon').sandbox.create();

这让我可以做一个一般的

  afterEach(function () {
    sinon.restore();
  });

不需要维护对我所有存根的引用并单独恢复它们。