2๐
TL;DR: It is simply impossible.
In short, you want to spy over a particular method. The only way to reliably spy/stub in JavaScript is using ES Proxy. But proxy is like a wrapper around a method. If this function is part of object which you are exporting, then Proxy would have worked. But that is not the case. Also, you need to call the proxied function and not the original one directly. Another way is to use JavaScript [Decorators][2] but they are not yet standard and useful in the class/method context only.
But, as a workaround, you can modify the function without changing the semantics and wrapping it into observable. The idea is to create a global Subject and call it from the alertUser()
:
window.messageQueue = new Subject();
alertUser(msg){
this.appendToPElement(msg);
// This is non-destructive.
window.messageQueue.next(msg);
}
// Usage
window.messageQueue.subscribe(() => { /* next */});
1๐
Just guessing here, but maybe a Proxy could be helpful.
const handler = {
apply: function(target, thisArg, argumentsList) {
obs.next(true);
return target(argumentsList);
}
};
function observeFn(fn) {
return new Proxy(fn, handler);
}
Then you could just wrap your original function like this: observeFn(alertUser)
and obs
should notify any call to that function.