cjohansen/Sinon.JS — pull request #302 by janjongboom (2013-06-28 14:26:37+00:00)
Title: Add onInvocation helper that fires on spy invocation

This is a usecase when testing web workers. Because of their nature it's only possible to communicate through `postMessage` calls and `onmessage` handlers. This creates an asynchronous workflow that is currently not being covered by sinon. For example: I'm testing the worker, which will send a message back after running to completion. The action is kicked off via a `postMessage`. Currently you'd write code like this:

```javascript
var worker = /* bla */;
worker.onmessage = sinon.stub();
worker.postMessage('something');
var iv = setInterval(function() {
if (worker.onmessage.called) {
clearInterval(iv);
// do assertions
}
}, 20);
```

A nice addition would be to have a callback fire when a method gets invoked.

In this PR I have changed the `callCount` field on spy into a ES5 get/set method, then adding a helper method on the `sinon` object that can hook into the setter to fire a callback function whenever the callCount of this object changes. This way the code doesn't need to rely on setInterval, but can be written like:

```javascript
var worker = /* bla */;
worker.onmessage = sinon.stub();
worker.postMessage('something');
sinon.onInvocation(worker.onmessage, function() {
// do assertions
});
```

*I'm aware this breaks in some browsers at the moment, but I first want to hear a yay/nay before putting more work into it*