droboticflow/scripts/lib/browser-test-lifecycle.mjs

47 lines
1.4 KiB
JavaScript

// Keep test cleanup bounded without converting cleanup failures into passes.
// owner is the BrowserServer launched by this test, never a shared browser.
export async function closeBrowserFixture({ browser, owner, vite, timeoutMs = 10000 }) {
const errors = [];
async function close(label, operation, force) {
let timer;
try {
await Promise.race([
Promise.resolve().then(operation),
new Promise((_, reject) => {
timer = setTimeout(() => reject(new Error(`${label} cleanup timed out`)), timeoutMs);
}),
]);
} catch (error) {
errors.push(error);
try {
force();
} catch (forceError) {
errors.push(forceError);
}
} finally {
clearTimeout(timer);
}
}
await close(
"browser",
async () => {
// Installed browsers can stall during graceful process shutdown even
// after all assertions pass. This server belongs only to this fixture;
// terminate it before disconnecting the client, never a shared browser.
await owner?.kill();
await browser?.close();
},
() => owner?.process().kill("SIGKILL"),
);
await close(
"vite",
() => vite?.close(),
() => {
vite?.ws?.close();
vite?.httpServer?.closeAllConnections();
void vite?.watcher?.close();
},
);
if (errors.length) throw new AggregateError(errors, errors.map((error) => error.message).join("; "));
}