From 605c6d5392ee18bcfc5c0d0869d0c740c2581d4f Mon Sep 17 00:00:00 2001 From: Mike Schmid Date: Wed, 24 Jul 2024 14:26:53 +0200 Subject: [PATCH] refactor: improve port allocations in tests (#190) Co-authored-by: mike --- tests/utils/server.ts | 24 ++++++++---------------- 1 file changed, 8 insertions(+), 16 deletions(-) diff --git a/tests/utils/server.ts b/tests/utils/server.ts index 9ac616e..ad72650 100644 --- a/tests/utils/server.ts +++ b/tests/utils/server.ts @@ -8,31 +8,23 @@ import { getKnex } from './database/knex'; import { ADMIN_ID, setupSeed } from './database/seed'; import { models, permissions } from './models'; -const MIN_PORT = 49152; -const MAX_PORT = 65535; - export const withServer = async ( cb: ( request: (document: RequestDocument | TypedQueryDocumentNode, ...variablesAndRequestHeaders: any) => Promise, knex: Knex ) => Promise ) => { - // eslint-disable-next-line prefer-const let handler: RequestListener; - let port: number; const server = createServer((req, res) => handler(req, res)); - // eslint-disable-next-line no-constant-condition - while (true) { - try { - port = Math.floor(Math.random() * (MAX_PORT - MIN_PORT + 1)) + MIN_PORT; - await new Promise((res, rej) => server.listen(port, res).once('error', rej)); - break; - } catch (e) { - console.warn(`Wait did we really get a port collision? Craaaaazy.`); - console.warn(e); - } - } + const port = await new Promise((res, rej) => + server + .listen() // Listen on a random free port (assigned by the OS) + .once('listening', function () { + res(this.address().port); + }) + .once('error', rej) + ); const rootKnex = getKnex(); const dbName = `test_${port}`;