From a07b0bae8d6c7358274cd3129f276dda9389cff6 Mon Sep 17 00:00:00 2001 From: Paul Melnikow Date: Sun, 3 Feb 2019 11:35:20 -0500 Subject: [PATCH] fix(socket): When Socket#setTimeout gets a callback, should still emit Ref #1404 --- lib/socket.js | 12 ++++-------- tests/test_socketdelay.js | 15 +++++++++++++++ 2 files changed, 19 insertions(+), 8 deletions(-) diff --git a/lib/socket.js b/lib/socket.js index 34911ad0f..159b56d4d 100644 --- a/lib/socket.js +++ b/lib/socket.js @@ -38,7 +38,9 @@ util.inherits(Socket, EventEmitter) Socket.prototype.setTimeout = function setTimeout(timeoutMs, fn) { this.timeoutMs = timeoutMs - this.timeoutFunction = fn + if (fn) { + this.once('timeout', fn) + } } Socket.prototype.applyDelay = function applyDelay(delayMs) { @@ -46,13 +48,7 @@ Socket.prototype.applyDelay = function applyDelay(delayMs) { if (this.timeoutMs && this.totalDelayMs > this.timeoutMs) { debug('socket timeout') - // TODO-coverage: Rewrite this so it always emits. In `setTimeout()`, if a - // timeout function is passed, register it using `this.once('timeout')`. - if (this.timeoutFunction) { - this.timeoutFunction() - } else { - this.emit('timeout') - } + this.emit('timeout') } } diff --git a/tests/test_socketdelay.js b/tests/test_socketdelay.js index 70209f7cf..d2099639c 100644 --- a/tests/test_socketdelay.js +++ b/tests/test_socketdelay.js @@ -95,3 +95,18 @@ test('calling socketDelay not emit a timeout if not idle for long enough', t => req.end() }) + +test('Socket#setTimeout adds callback as a one-time listener for parity with a real socket', t => { + nock('http://example.test') + .get('/') + .socketDelay(100) + .reply(200, '') + + const onTimeout = () => { + t.end() + } + + http.get('http://example.test').on('socket', socket => { + socket.setTimeout(50, onTimeout) + }) +})