Sunday 30 August 2020

The best way to assert that there is a server is running on a specified port.

I'm familiarizing myself with the net module by writing a simple ftp server, and I've been trying to write a test that will assert that the server has established a tcp connection on the specified port.Here is my first pass:const getConnection = (port, cb) => { return new Promise((resolve, reject) => { const connection = Net.createConnection({ port }, cb); connection.on('error', (err) => reject(err)); resolve(connection); }); }; it('establishes a TCP connection on the specified port', async () => { let connected = false; const port = 8080; const cb = () => { connected = true; }; const server = new FtpSrv({ port }); await server.start(); const connection = await getConnection(port, cb); await sleep(100); expect(connected).to.equal(true); connection.destroy(); server._netServer.close(); }); There's a couple of things that I don't like with this solution:Mixing of promises and callbacksHaving to sleep for a specified time so that the "connection" event can be emitted and my callback can resolve to result in the reassignment of the connected variable.​Here is my second pass:it('establishes a TCP connection on the specified port', async () => { const port = 8080; const server = new FtpSrv({ port }); await server.start(); const { stdout } = await exec(`lsof -i TCP:${port} | grep node`); // figured I could run some regex against stdout connection.destroy(); server._netServer.close(); }); While I like that this is less code and simpler, it seems a bit hacky.

Submitted August 31, 2020 at 12:45AM by la_li_lu_le_lo-rp

No comments:

Post a Comment