Calling original function from Sinon.js Stub

johnkchiu picture johnkchiu · Mar 28, 2014 · Viewed 11.9k times · Source

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?

Answer

psquared picture psquared · Mar 28, 2014

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