'How to close listening UDP sockets when mocha times-out?

I have some tests which bind to a UDP port, e.g.

describe('the server', function() {
  it('should respond to a udp packet', function(done) {
    const udp = dgram.createSocket('udp4');

    udp.on('error', function(error) {
      console.log(error);
    });

    udp.on('message', function(msg, rinfo) {
      console.log('msg', msg);
      console.log('rinfo', rinfo);
      // TODO: check the reply
      udp.close();
      done();
    });
    udp.bind();

    // send a request
    const bytes = Buffer.from("421a0800117860bc457f0100001a0653455256455222054d54303031", 'hex');
    udp.send(bytes, SERVER_PORT, SERVER_ADDR)
  });
});

When the test completes successfully, that code path can call udp.close() which lets mocha exit.

When a test exceeds mocha's 2 second time-out, I see the error but mocha does not exit as the UDP port is still listening.

Is there some form of callback/event that I can use to close a listening UDP socket when mocha's 2 second time-out fires?



Solution 1:[1]

You can also use mocha --exit which is far simpler than closing the sockets yourself.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 fadedbee