2

How to test if an anonymous function was passed as parameter in a spy function of sinon.js? Imagine a function like that.

function myFunction(){
    //do stuff
    otherobj.anotherFunc({myobj: 'value'}, function(){ console.log('test'); });
}

I created a spy in my test setup for otherobj.anotherFunc and could easily test if my spy was called with the first argument (an js object).

But i have some problems when i tried to test if the second argument, a callback is equal to another function.

ok(myDependencySpy.called, "dependency was called!");   //this is OK!
deepEqual(myDependencySpy.args[0][0], {myobj: 'value'});  //this is OK!
deepEqual(myDependencySpy.args[0][1], function(){ console.log('test'); });  //this FAIL =[

Is there a way to test that?

jplindgren
  • 298
  • 3
  • 10
  • Possible duplicate of http://stackoverflow.com/questions/7108922/qunit-test-error-with-equal-and-deepequal Have a look at this https://forum.jquery.com/topic/why-deepequal-is-not-working-in-this-test#14737000002953407 – Jan Jun 28 '15 at 23:24
  • Are you actually trying to test that the function code is _exactly the same_ as what you are expecting? That seems like a very brittle test to me. I would suggest that what you care most about is that the function gets called correctly when appropriate, etc. – GregL Jun 28 '15 at 23:44
  • @Jan the info in the link you provided was really valuable to me (thank you =]). But i think is not exactly the case here. They are trying to test equality in between two objects, while i´m trying to compare two functions, well, wrost than that, i'm trying to compare anonymous functions! – jplindgren Jun 29 '15 at 00:53
  • Ah ok they're testing constructors... But I agree with @GregL , what you really should be testing is that it gets called at the correct time and/or performs the correct actions. – Jan Jun 29 '15 at 00:57
  • @GregL, actually i´m trying to test if a expected callback function was passed as argument to another one. That dependecy i am calling is external to my code, actually is a function in a chrome.storage api. So my choice was to test if i call that dependency and with the right arguments using a spy. – jplindgren Jun 29 '15 at 00:59
  • Could you not do that by spying on the `chrome.storage` API function you are testing, and verify it gets called? – GregL Jun 29 '15 at 05:09
  • @GregL this is exactly what i am doing at `ok(myDependencySpy.called, "dependency was called!");`. But i'm going further, i tried to verify if my chrome.storage (actually my spy) was called and with what arguments was called. But as i said before, one of arguments was a anonymous function. Later, i discovered that was the problem, if i use a named function, i can verify if my function was passed as parameter! – jplindgren Jun 30 '15 at 22:57

0 Answers0