Skip to content

AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.

fix(frontend): settle each test's open requests before its file tears down (#15962)

Reinier van der Leer5279bacd26b5
diff --git a/autogpt_platform/frontend/src/tests/integrations/vitest.setup.tsx b/autogpt_platform/frontend/src/tests/integrations/vitest.setup.tsx
index 11b08710b3..a031e7213a 100644
--- a/autogpt_platform/frontend/src/tests/integrations/vitest.setup.tsx
+++ b/autogpt_platform/frontend/src/tests/integrations/vitest.setup.tsx
@@ -35,16 +35,51 @@ vi.mock("react", async (importActual) => {
};
});
+// happy-dom aborts a request still open when its file's window is torn down
+// and logs the abort, which Vitest then fails as a late console write.
+const openRequests = new Set<Promise<unknown>>();
+const QUIET_TICKS = 5;
+const MAX_SETTLE_TICKS = 1000;
+const realSetTimeout = globalThis.setTimeout;
+
beforeAll(() => {
mockNextjsModules();
mockAuthRequest(); // If you need user's data - please mock auth actions in your specific test - it sends null user [It's only to avoid cookies() call]
- return server.listen({ onUnhandledRequest: "error" });
+ server.listen({ onUnhandledRequest: "error" });
+ // After listen(): MSW's fetch wrapper answers mocked requests without
+ // calling the fetch it wrapped, so a tracker beneath it sees none.
+ trackOpenRequests();
});
-afterEach(() => {
+afterEach(async () => {
cleanup();
+ await settleOpenRequests();
server.resetHandlers();
// The checkout redirect is page-wide state that outlives a render; a
// redirect left by one test would disable the next test's buttons.
resetCheckoutRedirect();
});
afterAll(() => server.close());
+
+function trackOpenRequests() {
+ const fetch = globalThis.fetch;
+ globalThis.fetch = (...args: Parameters<typeof fetch>) => {
+ const request = fetch(...args);
+ openRequests.add(request);
+ request.then(
+ () => openRequests.delete(request),
+ () => openRequests.delete(request),
+ );
+ return request;
+ };
+}
+
+// cleanup() runs pending mount effects whose requests start a few ticks later,
+// so wait for a quiet spell; bounded, as some tests hold a request open.
+async function settleOpenRequests() {
+ let quiet = 0;
+ for (let tick = 0; tick < MAX_SETTLE_TICKS && quiet < QUIET_TICKS; tick++) {
+ await new Promise((resolve) => realSetTimeout(resolve, 0));
+ quiet = openRequests.size === 0 ? quiet + 1 : 0;
+ }
+ openRequests.clear();
+}