Skip to content

Commit a07b0ba

Browse files
committed
fix(socket): When Socket#setTimeout gets a callback, should still emit
Ref #1404
1 parent 69ba3c3 commit a07b0ba

File tree

2 files changed

+19
-8
lines changed

2 files changed

+19
-8
lines changed

lib/socket.js

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -38,21 +38,17 @@ util.inherits(Socket, EventEmitter)
3838

3939
Socket.prototype.setTimeout = function setTimeout(timeoutMs, fn) {
4040
this.timeoutMs = timeoutMs
41-
this.timeoutFunction = fn
41+
if (fn) {
42+
this.once('timeout', fn)
43+
}
4244
}
4345

4446
Socket.prototype.applyDelay = function applyDelay(delayMs) {
4547
this.totalDelayMs += delayMs
4648

4749
if (this.timeoutMs && this.totalDelayMs > this.timeoutMs) {
4850
debug('socket timeout')
49-
// TODO-coverage: Rewrite this so it always emits. In `setTimeout()`, if a
50-
// timeout function is passed, register it using `this.once('timeout')`.
51-
if (this.timeoutFunction) {
52-
this.timeoutFunction()
53-
} else {
54-
this.emit('timeout')
55-
}
51+
this.emit('timeout')
5652
}
5753
}
5854

tests/test_socketdelay.js

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -95,3 +95,18 @@ test('calling socketDelay not emit a timeout if not idle for long enough', t =>
9595

9696
req.end()
9797
})
98+
99+
test('Socket#setTimeout adds callback as a one-time listener for parity with a real socket', t => {
100+
nock('http://example.test')
101+
.get('/')
102+
.socketDelay(100)
103+
.reply(200, '<html></html>')
104+
105+
const onTimeout = () => {
106+
t.end()
107+
}
108+
109+
http.get('http://example.test').on('socket', socket => {
110+
socket.setTimeout(50, onTimeout)
111+
})
112+
})

0 commit comments

Comments
 (0)