Skip to content

Commit

Permalink
fix(socket): When Socket#setTimeout gets a callback, should still emit
Browse files Browse the repository at this point in the history
Ref #1404
  • Loading branch information
paulmelnikow committed Feb 4, 2019
1 parent 69ba3c3 commit a07b0ba
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 8 deletions.
12 changes: 4 additions & 8 deletions lib/socket.js
Expand Up @@ -38,21 +38,17 @@ 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) {
this.totalDelayMs += 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')
}
}

Expand Down
15 changes: 15 additions & 0 deletions tests/test_socketdelay.js
Expand Up @@ -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, '<html></html>')

const onTimeout = () => {
t.end()
}

http.get('http://example.test').on('socket', socket => {
socket.setTimeout(50, onTimeout)
})
})

0 comments on commit a07b0ba

Please sign in to comment.