1

I have been using sinon for very long time and it worked perfectly. But now we are started to use Q promises, looks like things are breaking with sinon spies.

For example:

var spy = sandbox.spy(someApi,"callFn")
// success: return a promise fulfilled with `5`:
someStub.withArgs("foo").returns(Q.resolve(5));

I could able to do this, which in turn resolves the promise. I could able to see that the then block of promise is executing by adding an console.log statement:

promise.then(function(){
  console.log("comes here") // <---- gets printed
  someApi.callFn() // <--- spies on this are failing
})

Even though the callFnis called, spy still says callCount is 0. I'm really not sure, why sinon wasn't able to spy an function which is called inside the promise then block.

Am I missing something here? Kindly let me know in order to fix my problem.

batman
  • 3,565
  • 5
  • 20
  • 41
  • First of all to have promise support in sinon you would use https://www.npmjs.com/package/sinon-as-promised. And are you writing unit tests for Node.js or front-end platform? – Kirill Slatin Jun 17 '15 at 04:13
  • @KirillSlatin: Front end platform – batman Jun 17 '15 at 04:25
  • @KirillSlatin: Thanks, but I'm using `Q` promises, standalone, not angular! – batman Jun 17 '15 at 04:30
  • *When* does it say that the `callCount` is `0`? After that log statement was executed? Don't forget that the `then` callback is asynchronous. – Bergi Jun 17 '15 at 05:31
  • @Bergi: after the `then` block, if I do: `console.log(spy.callCount)` it says `0`. – batman Jun 17 '15 at 05:34
  • @batman: Yes, that's expected. It's [***asynchronous***](http://stackoverflow.com/q/23667086/1048572)! Right after the `.then(…)` block the handler has only been installed, but not yet executed. – Bergi Jun 17 '15 at 05:36
  • @Bergi: So how should I handle this in the test cases? – batman Jun 17 '15 at 05:51
  • @batman: You'll need to write asynchronous test cases. Depends on your testing platform how to do that exactly. – Bergi Jun 17 '15 at 05:57

0 Answers0