<p>I am mocking some endpoints of the Kubernetes API in a mock server for some integration tests and got stuck in the implementation of the endpoint <code>/apis/batch/v1/watch/namespaces/{namespace}/jobs?watch=true</code> (<a href="https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.19/#job-v1-batch" rel="nofollow noreferrer">doc</a>, need to search for <code>batch/v1/watch</code> in the page). The client uses <a href="https://github.com/kubernetes-client/javascript/blob/master/src/watch.ts#L80-L139" rel="nofollow noreferrer">this</a> method to make a GET request and keep the connection open to receive events related to Job resources. Apparently, it handles a 'socket' event.</p>
<p>I implemented a simple mock endpoint that returns the data I want, but I get this error when the request is made:</p>
<pre class="lang-bash prettyprint-override"><code>Error: socket hang up
    at connResetException (node:internal/errors:691:14)
    at Socket.socketOnEnd (node:_http_client:466:23)
    at Socket.emit (node:events:538:35)
    at endReadableNT (node:internal/streams/readable:1345:12)
    at processTicksAndRejections (node:internal/process/task_queues:83:21)
</code></pre>
<p>How should this mock be implemented? Do I need to return a socket? How should I do that?</p>

notrev
<p>Answering to my own question: after some attempts, all I needed to do was to use <code>res.write()</code> with a string that ends with a line break character, like this:</p>
<pre class="lang-js prettyprint-override"><code>import express from 'express';

const TIME_BETWEEN_EVENTS = 500; // Milliseconds
const app = express();

app.get('/apis/batch/v1/watch/namespaces/:namespace/jobs', (_, res) =&gt; {
  res.writeHead(200, {
    'Content-Type': 'text/event-stream',
    'Cache-Control': 'no-cache',
    Connection: 'keep-alive',
  });

  console.log('Client connected to Jobs watch endpoint');
  let jobEventsSent = 0;

  const interval = setInterval(() =&gt; {
    if (jobEventsSent &lt; 3) {
      console.log('Sending data to Jobs watcher');
      res.write(
        Buffer.from(JSON.stringify({ type: 'ADDED', object: { /* Job Resource */ } }) + '\n'),
      );
      jobEventsSent++;
    } else {
      clearInterval(interval)
    }
  }, TIME_BETWEEN_EVENTS);

  res.socket.on('close', () =&gt; {
    console.log('Client disconnected from Jobs watch endpoint');
    if (interval) clearInterval(interval);
  });
});
</code></pre>
<p>The code above keeps the connection alive event after all the messages have been sent. To close the connection, it is necessary to call <code>res.end()</code>;</p>
