Search code examples
javascriptsinonspy

how to spy on a function


I am trying to spy on a global function e.g.

function foo() {

}

but the below test is failing, how to do that

    var spy = sinon.spy(foo);
    foo();
    expect(spy.callCount).to.equal(1);

** EDIT **

If I do it like below then it works

    var spy = sinon.spy(window, "foo");
    foo();
    expect(spy.callCount).to.equal(1);

So whats the difference


Solution

  • Using var spy = sinon.spy(foo); doesn't wrap the function foo as you might think. It actually returns a spy that contains the wrapped function.

    Using var spy = sinon.spy(window, "foo"); actually wraps the foo method. Internally, window["foo"] = <wrapped function> is being done, thus replacing your the function referenced by foo to the wrapped function.

    For var spy = sinon.spy(foo); to work you must not call foo() instead you need to call spy()

    function foo() {
    
    }
    
    console.log('BEGIN sinon.spy(foo)');
    var spy = sinon.spy(foo);
    spy();
    foo(); // called foo, but no effect on callCount
    foo(); // called foo, but no effect on callCount
    foo(); // called foo, but no effect on callCount
    console.log('Call Count:', spy.callCount);
    
    console.log('BEGIN sinon.spy(window, \'foo\')');
    var spy = sinon.spy(window, 'foo');
    spy();
    foo(); 
    foo(); 
    foo();
    console.log('Call Count:', spy.callCount);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/sinon.js/1.15.4/sinon.min.js"></script>