2

According to documentation of sinon.js, I can do like this: var spy = sinon.spy(myFunc);, but it doesn't work. Here is my effort:

var sinon = require("sinon");

describe('check bar calling', function(){
  it('should call bar once', function() {
    var barSpy = sinon.spy(bar);

    foo("aaa");

    barSpy.restore();
    sinon.assert.calledOnce(barSpy);
  });
});

function foo(arg) {
  console.log("Hello from foo " + arg);
  bar(arg);
}

function bar(arg) {
  console.log("Hellof from bar " + arg);
}
dm03514
  • 54,664
  • 18
  • 108
  • 145
Rostislav Shtanko
  • 704
  • 2
  • 9
  • 30
  • Possible duplicate of [Verifying function call and inspecting arguments using sinon spies](https://stackoverflow.com/questions/29800733/verifying-function-call-and-inspecting-arguments-using-sinon-spies) – try-catch-finally Jul 05 '17 at 05:30

1 Answers1

3

Sinon wraps the call it doesn't patch all references. The return value is a wrapped function, that you can make assertions on. It records all calls made to it, and not the function that it wraps. Modifying foo so that the caller provides a function allows the spy to be injected in, and allows for calls to be made on the spy.

var sinon = require("sinon");

describe('check bar calling', function(){
  it('should call bar once', function() {
    var barSpy = sinon.spy(bar);

    foo("aaa", barSpy);

    barSpy.restore();
    sinon.assert.calledOnce(barSpy);
  });
});

function foo(arg, barFn) {
  console.log("Hello from foo " + arg);
  barFn(arg);
}

function bar(arg) {
  console.log("Hellof from bar " + arg);
}
dm03514
  • 54,664
  • 18
  • 108
  • 145