Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
spy and spyOnObject
function spy(fn, prot = fn.prototype) {
function proxy() {
const args = Array.prototype.slice.call(arguments);
proxy.calls.push(args);
proxy.called = true;
return fn.apply(this, args);
}
proxy.prototype = prot;
proxy.calls = [];
proxy.called = false;
return proxy;
}
function spyOnObject(o) {
const o2 = {};
for (let k in o) {
const v = o[k];
o2[k] = (typeof v === 'function') ? spy(v, o.prototype) : v;
}
return o2;
}
/// EXAMPLE USAGES:
/*
function soma(a, b) { return a + b; }
const soma2 = spy(soma);
console.log( soma2(2, 3) );
console.log( soma2(25, 11) );
*/
/*
const o = {
count: 0,
soma: function(a, b) { return a + b; },
add1: function() { return ++this.count; }
};
const o2 = spyOnObject(o);
o2.soma(2, 3);
o2.add1();
o2.add1();
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.