Sinon.js,只存根一个方法一次



我想知道 sinon.js 中是否有可能只存根一次方法?

例如:

sinon.stub(module, 'randomFunction', 'returnValue/function');

在我的测试中,这个模块.randomFunction在同一测试中被多次调用,但我只希望存根触发一次,然后恢复它,以便函数恢复其正常行为。

模拟真实代码:

myModule.putItem(item, function (err, data) {
  if (err) {
    // do stuff
    return callback();
  } else {
    // do other stuff
    return callback(null, data);
  }
});

第一次我想触发错误,其他时候我只想让它继续真正的流程。

这在西农可能吗?

亲切问候

吉 米

编辑:我发布了我根据@Grimurd的答案为我的问题找到的解决方案

是的,这是可能的。假设您使用摩卡作为测试框架。

describe('some tests', function() {    
    afterEach(function() {
        sinon.restore();
    })
    it('is a test with a stub', function() {
        // This gets restored after each test.
        sinon.stub(module, 'randomFunction', 'returnValue/function');
    })
})

查看 sinon 沙盒 API 了解更多信息。

更新

为了回答您的实际问题,

describe('some tests', function() {
    afterEach(function() {
        sinon.restore();
    })
    it('is a test with a stub', function() {
        // This gets restored after each test.
        sinon.stub(module, 'randomFunction')
            .onFirstCall().returns('foo')
            .onSecondCall().returns('bar')
            .onThirdCall().returns('foobar');
    })
})

记录在 http://sinonjs.org/docs/搜索 stub.onCall(n)

更新 2:由于 v5 sinon 现在默认创建沙盒,因此不再需要显式创建沙盒。有关详细信息,请参阅从 v4 到 v5 的迁移指南

解决方案:

sandbox.stub(module, 'putItem')
  .onFirstCall().yields('ERROR')
  .onSecondCall().yields(null, item)

根据@grimurd的回答,我设法让它与"产量"一起工作。Yields 触发它在原始方法签名中找到的第一个回调函数。

所以在第一个电话中,我基本上说callback('error'),在第二个电话中,我说callback(null, item)

不知何故,我确实想知道回调是否比生成;)更好的方法名称

感谢您的回答!

其他答案似乎忽略了问题的关键部分:"我只希望存根触发一次,然后恢复它,以便函数恢复其正常行为"。

以下将给定方法存根一次,然后恢复到以前的行为:

let stub = sandbox.stub(module, 'method')
    .onFirstCall().returns(1)
    .onSecondCall().callsFake((...args) => {
        stub.restore();
        return module.method(...args);
    });

IMO 有一种更简单的方法来实现预期的行为。从文档中:

stub.callThrough(); 导致在没有任何条件存根匹配时调用包装到存根中的原始方法。

因此,一个真实的例子是:

let stub = sandbox.stub(module, 'method')
  .onSecondCall().returns('whatever');
stub.callThrough();

请注意,原始方法也将在第一次调用时执行。

最新更新