Ad

How To Spy On A Method That Receives Function Arguments?

- 1 answer

if I have a function:

function X() {
  some.external.library.method('X');
}

then I can test it (I'm using mocha + sinon) where I spy on the external library method like this:

var spy = sinon.spy(some.external.library, 'method');
X();
spy.calledWith('X');

...but what if the implementation passes an internally defined function to the method I'm spying on?

function X() {
  function INTERNAL() { ... }
  some.external.library.method(INTERNAL)
}

how do I test for it?

spy.calledWith(...?)
Ad

Answer

You can't assert an actual object without having the access to the expected object. If you don't know what the private function is - you simply can't compare if it's the same thing or not - you'll need to make it public.

However, I think you should consider testing that the callback actually does the stuff you expect it to do. Why do you even care which function was passed as an argument? As long as the function provides desired side effects - you're OK. Checking for calledWith is likely testing the implementation details - not behavior, which itself is likely a bad practice.

You're using a spy, not a stub - which means that your method actually runs - does it call the function? If it does - you can check the results. If it doesn't - you can access that function in a number of ways: spy.firstCall.args[0] / spy.getCall(0).args[0]. If it were a stub, you could configure it to callback automatically, like so: stub.yields(someValue) - this will call the last argument (your INTERNAL function) with someValue.

Ad
source: stackoverflow.com
Ad