Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling original function from Sinon.js Stub

Tags:

sinon

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?

like image 889
johnkchiu Avatar asked Mar 28 '14 13:03

johnkchiu


People also ask

How do I reset my Sinon stub?

var stub = sinon. The original function can be restored by calling object. method. restore(); (or stub. restore(); ).

How do you stub a promise in Sinon?

To stub a promise with sinon and JavaScript, we can return a promise with a stub. import sinon from "sinon"; const sandbox = sinon. sandbox. create(); const promiseResolved = () => sandbox.

What does sandbox stub do?

sandbox.Causes all stubs and mocks created from the sandbox to return promises using a specific Promise library instead of the global one when using stub. rejects or stub. resolves . Returns the stub to allow chaining.


2 Answers

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

like image 66
psquared Avatar answered Oct 20 '22 13:10

psquared


Sinon stores a reference to the original function in the wrappedMethod property of the stub (docs were just recently added in 2020). This can be called in the fake method.

sinon.stub(Array.prototype, 'sort').callsFake(
  // Don't use arrow function => syntax if you need to use 'this' below!
  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);
});
like image 14
GOTO 0 Avatar answered Oct 20 '22 13:10

GOTO 0