Created
March 2, 2020 22:10
-
-
Save JosePedroDias/2ffff6b701014a6d84cc4ff146e87af0 to your computer and use it in GitHub Desktop.
spy and spyOnObject
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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