I'm writing some unit tests and I'd like to simulate a connection loss (ECONNRESET) on a net.Socket instance as part of one of the tests.
What would be the best way to go about doing this?
Thanks
I'm writing some unit tests and I'd like to simulate a connection loss (ECONNRESET) on a net.Socket instance as part of one of the tests.
What would be the best way to go about doing this?
Thanks
The way I went for in the end was as follows:
client.end();
client.emit('error', new Error('ECONNRESET'));
was all I needed for the purposes of the test
There is a bit more short-hand solution existing for such cases:
socket.destroy(new Error('ECONNRESET'))
According to socket.destroy([exception])
docs:
If exception is specified, an 'error' event will be emitted and any listeners for that event will receive exception as an argument.
Also, there is a subtle difference between end
(it is possible the server will still send some data) and destroy
(ensures that no more I/O activity happens on this socket). For ECONNRESET
the latter would be the best choice as this code generally means abrupt peer disconnection and will error on subsequent writes.