【问题标题】:sinon not properly restoring stubbed prototype method?sinon 没有正确恢复存根原型方法?
【发布时间】:2016-09-21 03:51:33
【问题描述】:

看来 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);
}));

请注意,我使用的是“包装函数”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);
});

问题:

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

【问题讨论】:

    标签: javascript node.js mocha.js sinon


    【解决方案1】:

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

    所以如果你不想手动restore(),你必须使用this.spy()而不是sinon.spy()(和stub,mock)。

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

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

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

    这让我可以做一个通用的

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

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

    【讨论】:

    • 公平地说,@robertklep 给出的答案是第一位的,它解决了我的问题。但你的答案是正确的,而且更有帮助。
    • 谢谢!老实说,我看了他的回答,没看懂,自己解决了问题,写了答案,才发现他说的也一样……
    猜你喜欢
    • 1970-01-01
    • 2017-04-27
    • 2018-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-02
    • 2016-01-29
    • 1970-01-01
    相关资源
    最近更新 更多