cluster1
cluster1

Reputation: 5674

Understanding Sinon Spies: What happens when a spy-wrapped method is called?

When I wrap the method of a class into a Sinon-spy like this:

sinon.spy(myObject, "myMethod")

What happens within the spy?

I guess the spy-object has a reference which points to "myObject.myMethod".

What happens when the method becomes call?

I know that the spy logs information about the invocation like times of invocations, the used parameter etc.

But does the myMethod really become invoked?

I mean: Passes the spy object the invocation further? Does the spy-object act as proxy? Or does it only log the information?

Upvotes: 0

Views: 252

Answers (1)

Yury Fedorov
Yury Fedorov

Reputation: 14928

From a simple test it seems that sinon spy does call the original method:

it('does a thing', function() {
    const el = {};
    el.thing = function() { console.log('thing'); }
    sinon.spy(el, 'thing');
    el.thing();
    console.log(el.thing.called);
});

// prints:
// thing
// true

It also seems like that from the docs:

sinon.spy(object, "method") creates a spy that wraps the existing function object.method. The spy will behave exactly like the original method (including when used as a constructor), but you will have access to data about all calls.

Upvotes: 2

Related Questions