diff --git a/test/inflight-and-close.js b/test/inflight-and-close.js index 3e0a532bb9c..8f5672332a5 100644 --- a/test/inflight-and-close.js +++ b/test/inflight-and-close.js @@ -1,9 +1,10 @@ 'use strict' const { tspl } = require('@matteo.collina/tspl') -const { test } = require('node:test') +const { test, after } = require('node:test') const { request } = require('..') const http = require('node:http') +const { once } = require('node:events') test('inflight and close', async (t) => { t = tspl(t, { plan: 3 }) @@ -12,26 +13,33 @@ test('inflight and close', async (t) => { res.writeHead(200) res.end('Response body') res.socket.end() // Close the connection immediately with every response - }).listen(0, '127.0.0.1', function () { - const url = `http://127.0.0.1:${this.address().port}` - request(url) - .then(({ statusCode, headers, body }) => { - t.ok(true, 'first response') - body.resume() - body.on('close', function () { - t.ok(true, 'first body closed') - }) - return request(url) - .then(({ statusCode, headers, body }) => { - t.ok(true, 'second response') - body.resume() - body.on('close', function () { - server.close() - }) - }) - }).catch((err) => { - t.ifError(err) - }) }) + + after(() => server.close()) + + server.listen(0, '127.0.0.1') + await once(server, 'listening') + + const url = `http://127.0.0.1:${server.address().port}` + + const first = await request(url) + t.ok(true, 'first response') + + const firstBodyClosed = once(first.body, 'close').then(() => { + t.ok(true, 'first body closed') + }) + first.body.resume() + + const second = await request(url) + t.ok(true, 'second response') + + const secondBodyClosed = once(second.body, 'close') + second.body.resume() + + await Promise.all([ + firstBodyClosed, + secondBodyClosed + ]) + await t.completed })