Files
HealthLog/e2e/insights-generate.spec.ts
T
Marc-André Bombeck a23ee61184 test(e2e): route cleanup happens by construction, not per spec
A spec that arms `page.route(...)` in a `beforeEach` and never drops the
handler races its own teardown. The context closes, an async handler is
still awaiting, its next call rejects with "Test ended.", and Playwright
attributes that to the test that had just passed. With `retries: 2` plus
`failOnFlakyTests`, which spec bites is a matter of timing.

`e2e/setup/test.ts` re-exports Playwright's `test` extended with an auto
fixture that unroutes every page and the context after each test, and
clears the page event listeners a spec subscribes to; `expect` rides
along so a spec needs one import. Auto means a spec author cannot forget
it and does not have to know it exists. Every spec now takes `test` from
there, and `e2e-route-cleanup-guard.test.ts` keeps the import boundary
closed with an allowlist that carries its reason.

The per-file `afterEach` on the cycle spec goes away — leaving both would
read as not trusting the fixture.

Not covered: a page inside a context a spec builds itself. Only
`share-documents.spec.ts` does that, and it owns those contexts.
2026-07-25 23:02:03 +02:00

111 lines
3.7 KiB
TypeScript

import { expect, test } from "./setup/test";
import { STORAGE_STATE_PATH } from "./setup/global-setup";
/**
* Insights generation flow — `/settings/ai` exposes a "Regenerate
* insights" button that POSTs `/api/insights/generate` and re-renders
* the AI-generated text in the surrounding cards.
*
* The real endpoint hits an AI provider (OpenAI / Codex) which we can't
* call from CI. We mock it with the schema documented in
* `src/app/api/insights/generate/route.ts`:
*
* { data: { insights: { changed, stable, drivers, nextSteps,
* confidence, limitations }, cached: false }, error: null }
*
* We then confirm the success message lands AND a query invalidation
* fires on the insight-fetching endpoints (we re-mock those to assert
* they're touched after the regenerate call).
*/
test.describe("insights generation flow (mocked)", () => {
test.use({ storageState: STORAGE_STATE_PATH });
test("regenerate button updates insight cards", async ({ page }) => {
// Settings endpoint — return "connected" so the regenerate button
// is rendered (the section gates it on hasProvider).
await page.route("**/api/insights/settings", (route) =>
route.fulfill({
status: 200,
contentType: "application/json",
body: JSON.stringify({
data: {
codexStatus: "connected",
codexConnectedAt: new Date().toISOString(),
hasAdminKey: false,
codexOauthConfigured: true,
privacyMode: "aggregated",
lastInsightAt: new Date().toISOString(),
},
error: null,
}),
}),
);
await page.route("**/api/user/ai-provider", (route) =>
route.fulfill({
status: 200,
contentType: "application/json",
body: JSON.stringify({
data: {
provider: null,
model: null,
baseUrl: null,
hasAnthropicKey: false,
anthropicKeyPreview: null,
hasLocalKey: false,
hasOpenaiKey: false,
openaiKeyPreview: null,
},
error: null,
}),
}),
);
let generateCalls = 0;
await page.route("**/api/insights/generate", (route) => {
generateCalls += 1;
return route.fulfill({
status: 200,
contentType: "application/json",
body: JSON.stringify({
data: {
insights: {
changed:
"Blood-pressure averages dropped by 4/2 mmHg over the last 30 days.",
stable: "Pulse and weight unchanged within natural variance.",
drivers:
"Likely driven by improved medication compliance (88% vs 72% prior).",
nextSteps:
"Continue current routine; revisit BMI target in 30 days.",
confidence: "mittel",
limitations:
"Sample size for systolic readings remains below 60.",
},
cached: false,
},
error: null,
}),
});
});
await page.goto("/settings/ai", { waitUntil: "domcontentloaded" });
const regenerateBtn = page.getByRole("button", {
name: /regenerate (insights|reports)|insights aktualisieren|neu erstellen|berichte/i,
});
await expect(regenerateBtn).toBeVisible({ timeout: 10_000 });
await regenerateBtn.click();
// The settings page surfaces an inline alert after the mutation
// completes. The exact copy comes from i18n, so match permissively.
await expect(
page.getByText(
/reports? regenerated|insight.*regenerated|berichte.*aktualisiert|generated successfully|erfolgreich/i,
),
).toBeVisible({ timeout: 10_000 });
expect(generateCalls).toBeGreaterThanOrEqual(1);
});
});