Skip to content

Instantly share code, notes, and snippets.

@logicalparadox
Created December 6, 2011 01:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save logicalparadox/1436234 to your computer and use it in GitHub Desktop.
Save logicalparadox/1436234 to your computer and use it in GitHub Desktop.
Tiny javascript spy for testing.
function Spy (fn) {
if (!fn) fn = function() {};
function proxy() {
var args = Array.prototype.slice.call(arguments);
proxy.calls.push(args);
proxy.called = true;
fn.apply(this, args);
}
proxy.prototype = fn.prototype;
proxy.calls = [];
proxy.called = false;
return proxy;
}
// Usage:
var event_spy = Spy();
// or, if you want a callback
var event_spy = Spy(function (data) {
assert.equal(typeof data, 'object');
});
eventemitter.on('hello', event_spy);
eventemitter.emit('hello', { world: true });
eventemitter.emit('hello', { universe: 'better' });
// Result:
assert.ok(event_spy.called);
assert.equal(event_spy.calls.length, 2);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment