vignette/apps/web/e2e/support.ts
2026-06-27 17:22:38 +09:00

176 lines
5.5 KiB
TypeScript

import { promises as fs } from "node:fs";
import path from "node:path";
import { expect, type Page } from "@playwright/test";
export interface E2EPersona {
code: string;
display_name: string;
source: string;
degraded: boolean;
}
export async function useRealApi(_page: Page) {
// Intentionally empty. E2E should exercise the local API through the Vite
// proxy instead of replacing app data with browser-side route fixtures.
}
function sleep(ms: number) {
return new Promise<void>((resolve) => {
setTimeout(resolve, ms);
});
}
export async function withGlobalEngineConfigLock<T>(
label: string,
action: () => Promise<T>,
): Promise<T> {
const dir = path.join(process.cwd(), "node_modules", ".tmp");
const lockPath = path.join(dir, "engine-config.lock");
const startedAt = Date.now();
await fs.mkdir(dir, { recursive: true });
while (true) {
try {
const handle = await fs.open(lockPath, "wx");
try {
await handle.writeFile(`${process.pid} ${label} ${new Date().toISOString()}`);
return await action();
} finally {
await handle.close().catch(() => undefined);
await fs.unlink(lockPath).catch(() => undefined);
}
} catch (err) {
const code =
typeof err === "object" && err !== null && "code" in err
? String((err as { code?: unknown }).code)
: "";
if (code !== "EEXIST") throw err;
const stat = await fs.stat(lockPath).catch(() => null);
if (stat && Date.now() - stat.mtimeMs > 60_000) {
await fs.unlink(lockPath).catch(() => undefined);
continue;
}
if (Date.now() - startedAt > 30_000) {
throw new Error(`Timed out waiting for engine config lock: ${label}`);
}
await sleep(100);
}
}
}
export async function signInAsLearner(page: Page) {
const res = await page.request.post("/api/auth/dev-login", {
data: {
email: "learner@hs.ac.kr",
role: "learner",
display_name: "E2E Learner",
},
});
expect(res.ok(), await res.text()).toBeTruthy();
const consent = await page.request.post("/api/auth/consent", {
data: { accepted: true },
});
expect(consent.ok(), await consent.text()).toBeTruthy();
}
export async function signInAsTeacher(page: Page) {
const res = await page.request.post("/api/auth/dev-login", {
data: {
email: "teacher@hs.ac.kr",
role: "teacher",
display_name: "E2E Teacher",
},
});
expect(res.ok(), await res.text()).toBeTruthy();
}
export async function fetchAvailablePersonas(page: Page): Promise<E2EPersona[]> {
const res = await page.request.get("/api/personas");
expect(res.ok(), await res.text()).toBeTruthy();
const personas = (await res.json()) as E2EPersona[];
const usable = personas.filter((persona) => persona.source === "database" && !persona.degraded);
expect(usable.length, `Expected at least one database persona: ${JSON.stringify(personas)}`).toBeGreaterThan(0);
return usable;
}
export async function fetchAvailablePersona(page: Page, index = 0): Promise<E2EPersona> {
const personas = await fetchAvailablePersonas(page);
return personas[index] ?? personas[0];
}
export async function expectNoHorizontalOverflow(page: Page) {
await expect
.poll(async () => {
try {
return await page.evaluate(() => {
const doc = document.documentElement;
return Math.ceil(doc.scrollWidth - doc.clientWidth);
});
} catch (err) {
if (isNavigationRace(err)) return Number.MAX_SAFE_INTEGER;
throw err;
}
})
.toBeLessThanOrEqual(1);
const overflow = await page.evaluate(() => {
const doc = document.documentElement;
const viewportWidth = doc.clientWidth;
const delta = Math.ceil(doc.scrollWidth - viewportWidth);
const offenders = Array.from(document.querySelectorAll<HTMLElement>("body *"))
.map((el) => {
const rect = el.getBoundingClientRect();
const style = window.getComputedStyle(el);
return {
tag: el.tagName.toLowerCase(),
className: String(el.className || ""),
text: (el.textContent ?? "").replace(/\s+/g, " ").trim().slice(0, 80),
left: Math.floor(rect.left),
right: Math.ceil(rect.right),
width: Math.ceil(rect.width),
visible:
style.display !== "none" &&
style.visibility !== "hidden" &&
Number(style.opacity) !== 0 &&
rect.width > 0 &&
rect.height > 0,
};
})
.filter((item) => item.visible && (item.left < -1 || item.right > viewportWidth + 1))
.slice(0, 8);
return { delta, viewportWidth, offenders };
});
expect(
overflow.delta,
`Horizontal overflow ${overflow.delta}px at ${overflow.viewportWidth}px viewport. Offenders: ${JSON.stringify(
overflow.offenders,
)}`,
).toBeLessThanOrEqual(1);
}
export async function expectNoDocumentOverflow(page: Page) {
await expect
.poll(async () => {
try {
return await page.evaluate(() => {
const doc = document.documentElement;
return {
x: Math.ceil(doc.scrollWidth - doc.clientWidth),
y: Math.ceil(doc.scrollHeight - doc.clientHeight),
};
});
} catch (err) {
if (isNavigationRace(err)) return { x: Number.MAX_SAFE_INTEGER, y: Number.MAX_SAFE_INTEGER };
throw err;
}
})
.toEqual({ x: 0, y: 0 });
}
function isNavigationRace(err: unknown) {
return err instanceof Error && /Execution context was destroyed|most likely because of a navigation/i.test(err.message);
}