With sinon, I'm trying to spy on a prototype method. It looks so simple in online howtos etc. I tried many websites and SO posts like this: Stubbing a class method with Sinon.js or sinon - spy on toString method, but it just doesn't work for me.
Prerequisites
I'm using http.d.ts https://github.com/nodejs/node/blob/master/lib/_http_outgoing.js to write data back from an async API call through an OutgoingMessage
object:
class OutgoingMessage extends stream.Writable
There is a prototype method end
in OutgoingMessage
:
OutgoingMessage.prototype.end = function end(chunk, encoding, callback) {
My API function is called like this:
Get = async (req:IncomingMessage,res:OutgoingMessage):Promise<void> => {...
...
res.end(data)
...
}
My tests
In my test I'm calling the Get
method. My IncomingMessage
determines what I expect to be in the OutgoingMessage
.
it("should call end with the correct value", async function(){
...
let outgoingMessageSpy = sinon.spy(OutgoingMessage.prototype,"end");
let anOutgoingMessage = <OutgoingMessage>{};
...
expect(outgoingMessageSpy.calledOnce).to.be.true();
}
Debugging the test case I see how end
is being called but apparently I have not set up my spy the right way as my expectation fails, calledOnce
is false
. Inspecting the object I see that calledCount
is 0
.
I'm doing basically the same (it appears to me) when I do
const toStringSpy = sinon.spy(Number.prototype, "toString");
expect(toStringSpy.calledWith(2)).to.be.true;
and that works. I do notice, though, that VS Code highlights the keyword prototype
differently for Number.prototype
and OutgoingMessage.prototype
. Is that of relevance? On mouse-over is says NumberConstructor.prototype
but only OutgoingMessage.prototype
..
Questions
How to set up the spy correctly to pick up the call to the prototype method end
?