(reqOptions, payload, waitBeforeDestroy)
| 12 | * @see https://github.com/fastify/fastify/issues/4959 |
| 13 | */ |
| 14 | function runBadClientCall (reqOptions, payload, waitBeforeDestroy) { |
| 15 | let innerResolve, innerReject |
| 16 | const promise = new Promise((resolve, reject) => { |
| 17 | innerResolve = resolve |
| 18 | innerReject = reject |
| 19 | }) |
| 20 | |
| 21 | const postData = JSON.stringify(payload) |
| 22 | |
| 23 | const req = http.request({ |
| 24 | ...reqOptions, |
| 25 | headers: { |
| 26 | 'Content-Type': 'application/json', |
| 27 | 'Content-Length': Buffer.byteLength(postData) |
| 28 | } |
| 29 | }, () => { |
| 30 | innerReject(new Error('Request should have failed')) |
| 31 | }) |
| 32 | |
| 33 | // Kill the socket after the request has been fully written. |
| 34 | // Destroying it on `connect` can race before any bytes are sent, making the |
| 35 | // server-side assertions (hooks/handler) non-deterministic. |
| 36 | // |
| 37 | // To keep the test deterministic, we optionally wait for a server-side signal |
| 38 | // (e.g. onSend entered) before aborting the client. |
| 39 | let socket |
| 40 | req.on('socket', (s) => { socket = s }) |
| 41 | req.on('finish', () => { |
| 42 | if (waitBeforeDestroy && typeof waitBeforeDestroy.then === 'function') { |
| 43 | Promise.race([ |
| 44 | waitBeforeDestroy, |
| 45 | new Promise(resolve => setTimeout(resolve, 200)) |
| 46 | ]).then(() => { |
| 47 | if (socket) socket.destroy() |
| 48 | }, innerResolve) |
| 49 | return |
| 50 | } |
| 51 | setTimeout(() => { socket.destroy() }, 0) |
| 52 | }) |
| 53 | req.on('error', innerResolve) |
| 54 | req.write(postData) |
| 55 | req.end() |
| 56 | |
| 57 | return promise |
| 58 | } |
| 59 | |
| 60 | test('should handle a socket error', async (t) => { |
| 61 | t.plan(4) |
no test coverage detected