From 087215c4fd580d1376f904ab1cfc7a295729ede3 Mon Sep 17 00:00:00 2001 From: Tibo De Peuter Date: Thu, 17 Apr 2025 11:57:58 +0200 Subject: [PATCH] refactor(frontend): waitForEndpoint ipv loop --- frontend/tests/setup-backend.ts | 21 ++++++++++++--------- 1 file changed, 12 insertions(+), 9 deletions(-) diff --git a/frontend/tests/setup-backend.ts b/frontend/tests/setup-backend.ts index 6acf7aa4..9c5d5d05 100644 --- a/frontend/tests/setup-backend.ts +++ b/frontend/tests/setup-backend.ts @@ -3,6 +3,17 @@ import { ChildProcess } from 'node:child_process'; let backendProcess: ChildProcess; +async function waitForEndpoint(url: string, delay = 1000): Promise { + try { + await fetch(url); + } catch { + // Endpoint is not ready yet + await new Promise((resolve) => setTimeout(resolve, delay)); + // Retry + await waitForEndpoint(url, delay); + } +} + export async function setup(): Promise { // Spin up the database spawn('docker', ['compose', 'up', 'db', '--detach'], { @@ -16,15 +27,7 @@ export async function setup(): Promise { }); // Wait until you can curl the backend - let backendReady = false; - while (!backendReady) { - try { - await fetch('http://localhost:3000/api') - backendReady = true; - } catch (_) { - // Ignore the error - } - } + await waitForEndpoint('http://localhost:3000/api'); } export async function teardown(): Promise {