1'use strict';
2
3// Test that the `'timeout'` event is emitted exactly once if the `timeout`
4// option and `request.setTimeout()` are used together.
5
6const { expectsError, mustCall } = require('../common');
7const { strictEqual } = require('assert');
8const { createServer, get } = require('http');
9
10const server = createServer(() => {
11  // Never respond.
12});
13
14server.listen(0, mustCall(() => {
15  const req = get({
16    port: server.address().port,
17    timeout: 2000,
18  });
19
20  req.setTimeout(1000);
21
22  req.on('socket', mustCall((socket) => {
23    strictEqual(socket.timeout, 2000);
24
25    socket.on('connect', mustCall(() => {
26      strictEqual(socket.timeout, 1000);
27
28      // Reschedule the timer to not wait 1 sec and make the test finish faster.
29      socket.setTimeout(10);
30      strictEqual(socket.timeout, 10);
31    }));
32  }));
33
34  req.on('error', expectsError({
35    name: 'Error',
36    code: 'ECONNRESET',
37    message: 'socket hang up'
38  }));
39
40  req.on('close', mustCall(() => {
41    strictEqual(req.destroyed, true);
42    server.close();
43  }));
44
45  req.on('timeout', mustCall(() => {
46    strictEqual(req.socket.listenerCount('timeout'), 1);
47    req.destroy();
48  }));
49}));
50