From 0a484a9470c73f0eaa393cd572c97283a24c2bf1 Mon Sep 17 00:00:00 2001 From: Martin Jonsson Date: Mon, 6 May 2019 16:04:27 +0200 Subject: [PATCH] Fix issue with connectTimeout and add test for it. --- index.js | 6 ++++-- test/index.test.js | 21 ++++++++++++++++----- 2 files changed, 20 insertions(+), 7 deletions(-) diff --git a/index.js b/index.js index 78c48a4..22b9a82 100644 --- a/index.js +++ b/index.js @@ -159,8 +159,10 @@ function createRequest(opts, resolve, reject) { } }, opts.connectTimeout); - req.on('connect', () => { - clearTimeout(connectTimeoutId); + req.on('socket', (socket) => { + socket.on('connect', () => { + clearTimeout(connectTimeoutId); + }); }); } diff --git a/test/index.test.js b/test/index.test.js index 0066064..73449cd 100644 --- a/test/index.test.js +++ b/test/index.test.js @@ -33,9 +33,9 @@ describe('request-prom', () => { .reply(200) .get('/error') .replyWithError('shit') - .get('/slowConnect') - .delay({head: 1000}) - .reply(200) + .get('/slowBody') + .delay({body: 50}) + .reply(200, 'ok') .post('/postFile') .reply(200, (path, body) => { return body.match(/filename="index\.test\.js"/) ? 'OK' : 'FAIL'; @@ -165,11 +165,22 @@ describe('request-prom', () => { describe('connectTimeout', () => { it('rejects on timeout with ConnectionError', (done) => { - req({url: url + '/slowConnect', connectTimeout: 10}) - .catch(ConnectionError, () => { + // can't figure out a better way to test a real connection timeout + req({url: 'http://www.google.com:81', connectTimeout: 10}) + .catch(ConnectionError, (e) => { + e.message.should.equal('Connect timeout occurred when requesting url: http://www.google.com:81'); done(); }); }); + + it('doesnt reject if connect is within time', (done) => { + req({url: url + '/slowBody', connectTimeout: 1}) + .then(() => { + done(); + }) + .catch(done); + + }); }); describe('socketTimeout', () => {