Calling original function from Sinon.js Stub

爷,独闯天下 提交于 2019-12-09 07:51:38

问题


I'm trying to intercept a call with Sinon.js so I can do some logging and then execute the original call. I don't see a way to do this with sinon.spy(), but I think I can do it with sinon.stub().

I provided a custom function:

sinon.stub(servicecore.ServiceWrapper.prototype, '_invoke', function(method, name, body, headers, callback) {
    console.log('---- ServiceWrapper._invoke called! ----');

// How do I call the original function?

});

The problem I have is executing the original function, so my application behaves the same. Any idea?


回答1:


You could use a closure. For example:

var obj = {
    foo: function () {
        console.log('foo');
    }
};

var stub = (function () {
    var originalFoo = obj.foo;
    return sinon.stub(obj, 'foo', function () {
        console.log('stub');
        originalFoo();
    });
}());

JSFiddle




回答2:


Sinon stores a reference to the original function in the wrappedMethod property of the stub. This can be called in the fake method.

sinon.stub(Array.prototype, 'sort').callsFake(
  function () {
    console.log(`sorting array ${this}`);
    return Array.prototype.sort.wrappedMethod.apply(this, arguments);
  }
);

const array = ['C', 'A', 'B'].sort();
console.log(`sorted array is ${array}`);
<script src="https://cdnjs.cloudflare.com/ajax/libs/sinon.js/7.3.2/sinon.min.js"></script>

And so the OP's code would be:

sinon.stub(servicecore.ServiceWrapper.prototype, '_invoke').callsFake(function(method, name, body, headers, callback) {
    console.log('---- ServiceWrapper._invoke called! ----');
    return servicecore.ServiceWrapper.prototype._invoke.wrappedMethod.apply(this, arguments);
});


来源:https://stackoverflow.com/questions/22714085/calling-original-function-from-sinon-js-stub

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!