title: Spying on a prototype method in Sinon.js
body: <p>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: <a href="https://stackoverflow.com/questions/21072016/stubbing-a-class-method-with-sinon-js">Stubbing a class method with Sinon.js</a> or <a href="https://stackoverflow.com/questions/49866123/sinon-spy-on-tostring-method">sinon - spy on toString method</a>, but it just doesn't work for me.</p>
  <p><strong>Prerequisites</strong></p>
  <p>I'm using http.d.ts <a href="https://github.com/nodejs/node/blob/master/lib/_http_outgoing.js" rel="nofollow noreferrer">https://github.com/nodejs/node/blob/master/lib/_http_outgoing.js</a> to write data back from an async API call through an <code>OutgoingMessage</code> object:</p>
  <p><code>class OutgoingMessage extends stream.Writable</code></p>
  <p>There is a prototype method <code>end</code> in <code>OutgoingMessage</code>:</p>
  <p><code>OutgoingMessage.prototype.end = function end(chunk, encoding, callback) {</code></p>
  <p>My API function is called like this:</p>
  <pre><code>Get = async (req:IncomingMessage,res:OutgoingMessage):Promise&lt;void&gt; =&gt; {...
      ...
      res.end(data)
      ...
  }
  </code></pre>
  <p><strong>My tests</strong></p>
  <p>In my test I'm calling the <code>Get</code> method. My <code>IncomingMessage</code> determines what I expect to be in the <code>OutgoingMessage</code>.</p>
  <pre><code>it(&quot;should call end with the correct value&quot;, async function(){ 
      ...
      let outgoingMessageSpy = sinon.spy(OutgoingMessage.prototype,&quot;end&quot;);
      let anOutgoingMessage = &lt;OutgoingMessage&gt;{};
      ...
      expect(outgoingMessageSpy.calledOnce).to.be.true();
  }
  </code></pre>
  <p>Debugging the test case I see how <code>end</code> is being called but apparently I have not set up my spy the right way as my expectation fails, <code>calledOnce</code> is <code>false</code>. Inspecting the object I see that <code>calledCount</code> is <code>0</code>.</p>
  <p>I'm doing basically the same (it appears to me) when I do</p>
  <pre><code>const toStringSpy = sinon.spy(Number.prototype, &quot;toString&quot;);
  expect(toStringSpy.calledWith(2)).to.be.true;
  </code></pre>
  <p>and that works. I do notice, though, that VS Code highlights the keyword <code>prototype</code> differently for <code>Number.prototype</code> and <code>OutgoingMessage.prototype</code>. Is that of relevance? On mouse-over is says <code>NumberConstructor.prototype</code> but only <code>OutgoingMessage.prototype</code>..</p>
  <p><strong>Questions</strong></p>
  <p>How to set up the spy correctly to pick up the call to the prototype method <code>end</code>?</p>