Files
clean-architecture-frontend…/tests/e2e/generated-feature.spec.ts
T
DongHyeonka 63ba523519 fix(form): 저장 뒤 이동과 마운트 판정을 폼이 맡고 다시 로그인 안내를 먼저 그린다
앞 커밋(1112/01-01) 뒤 확인 리뷰가 완료 기준의 남은 셋과 결함 둘을 찾았다.

- 생성 작성 페이지에 마운트 표시(useRef)와 저장 뒤 이동이 남았다. 저장이
  끝나면 페이지가 폼보다 먼저, 폼이 pending인 동안 상세로 옮겼다. 다시
  마운트한 폼에서 재전송이 성공하면 사용자가 돌아와 입력한, 보낸 적 없는
  값을 이탈 확인 없이 버렸다(1112/01-02 영향).
- 폼이 재전송 결과로 결과 불명을 다시 판정했다(resendLeftUnknown).
  코디네이터와 401에서 갈린다. 코디네이터는 결과 불명을 쥐고 폼은 다시
  로그인으로 가는데, FormSaveFeedback이 결과 불명을 먼저 그려 다시 로그인
  안내를 가렸다(D-2 위반).
- 지난 세 결함(1105/08-02·08-04, 1106/08-02)의 시험이 생성 페이지 시험에만
  있었다.

고른 방법: useAppForm에 onSaved를 더한다(추가만). 폼이 결과를 보이고
pending을 끈 뒤, 마운트된 동안만 부른다. confirmUnknownEffect(then)도
마운트된 동안만 then을 부른다. resendUnknownEffect의 then 인자와
FormSaveFeedback의 onResent는 지운다(앞 커밋에서 생겨 아직 내보낸 적이
없다). 재전송 뒤 결과 불명인지는 코디네이터의 새 holdsUnknownEffect로
묻는다. mutation 없이 쓰는 폼(이미 생성한 페이지)은 물을 곳이 없어 같은
거절 표(isRefusedOnEveryAttempt)로 본다. FormSaveFeedback은 다시 로그인
실패를 결과 불명보다 먼저 그린다. 생성 페이지는 mutation.submit을 그대로
넘기고 onSaved와 onConfirmed에서 옮기기만 한다. VD-04 머리 칸에 넣었던
문장은 보완 절로 옮긴다(머리 칸의 백틱 낱말을 문서 검사가 경로로 본다).
페이지가 FormSaveFeedback을 늘 넘기므로, 할 말이 없는 피드백 칸은 자리를
차지하지 않는다(templates.css, 빈 칸이 그리드 간격을 한 줄 더했다).

위험·한계: 저장 뒤 이동이 폼이 결과를 그린 뒤로 한 번 늦어진다. 다시
마운트한 폼에 보내지 않은 값이 있으면 이동이 이탈 확인을 띄운다(의도).

검증: form-foundation 새 시험 일곱과 create-feature 생성 페이지 시험
(RED·GREEN, 막기·다른 저장·충돌 안내 변이 셋), 생성 기능 e2e의 피드백 칸 간격 시험은 desktop에서 돌려 PR
본문에 적는다.

Refs: 1112/01-01, 1112/01-02, 1105/08-02, 1105/08-04, 1106/08-02, 1112/04-02
2026-11-13 00:03:42 +09:00

390 lines
15 KiB
TypeScript

import AxeBuilder from "@axe-core/playwright";
import type { Page, Route } from "@playwright/test";
import { KO_MESSAGES } from "../../src/presentation/i18n/catalog.ts";
import { expect, test } from "../support/browser/strict-browser-test.ts";
import {
prepareFixtureBuilds,
removeFixtureBuilds,
type FixtureBuilds,
} from "./support/fixture-builds.ts";
import {
addGeneratedFeature,
generatedFeature,
routePath,
type GeneratedFeature,
} from "../../scripts/lib/generated-feature.ts";
import { startBuildServer } from "./support/service-worker-builds.ts";
/**
* 2026-11-07. One feature in a real browser: its protected route through the
* local demo sign-in, its list read through the production codec, mapper and
* query cache, its form, and its save through the production command path
* with the idempotency key. These ran on the template's reference sample
* until it was deleted; now they run on the feature `create:feature` writes
* (`--with-create --keyed`), built into a copy of the repository
* (scripts/lib/generated-feature.ts). The API answers are the paired backend's
* Envelope, written out as in the generated feature's own tests.
*/
const META = Object.freeze({ requestId: "req-e2e", traceId: "0af7651916cd43dd8448eb211c80319c" });
const ITEM = Object.freeze({ id: "browser-order", name: "Browser order" });
const WCAG_TAGS = ["wcag2a", "wcag2aa", "wcag21a", "wcag21aa"];
let builds: FixtureBuilds<"a"> | undefined;
let server: Awaited<ReturnType<typeof startBuildServer>> | undefined;
let feature: GeneratedFeature;
test.beforeAll(async () => {
test.setTimeout(300_000);
builds = await prepareFixtureBuilds("generated-feature", [
{ name: "a", edit: addGeneratedFeature },
]);
feature = generatedFeature(builds.root);
server = await startBuildServer({ a: builds.dist.a, b: builds.dist.a });
});
test.afterAll(async () => {
await server?.close();
await removeFixtureBuilds(builds);
});
const words = () => feature.messages["ko-KR"];
const word = (key: string) => {
const value = words()[key];
if (value === undefined) throw new Error(`the generated catalog has no ${key}`);
return value;
};
function envelope(data: unknown) {
return { success: true, data, meta: META };
}
function failure(code: string, retryable: boolean) {
return {
success: false,
error: { code, category: "SYSTEM", message: "backend message", retryable },
meta: META,
};
}
/** Answers the list read and, by id, the item read. */
async function answerReads(page: Page, list: readonly unknown[] = [ITEM]) {
const collection = new URL(feature.api).pathname;
await page.route(
(url) => url.origin === new URL(feature.api).origin && url.pathname.startsWith(collection),
async (route) => {
const request = route.request();
if (request.method() !== "GET") return route.fallback();
const { pathname } = new URL(request.url());
return pathname === collection
? route.fulfill({ json: envelope(list) })
: route.fulfill({ json: envelope({ ...ITEM, id: pathname.slice(collection.length + 1) }) });
},
);
}
type CreateCall = Readonly<{ name: unknown; idempotencyKey: string | null }>;
/** Answers each create with the next responder and records what was sent. */
async function answerCreates(
page: Page,
responders: readonly ((route: Route) => Promise<void>)[],
): Promise<CreateCall[]> {
const calls: CreateCall[] = [];
await page.route(feature.api, async (route) => {
const request = route.request();
if (request.method() !== "POST") return route.fallback();
calls.push({
name: (request.postDataJSON() as { name?: unknown }).name,
idempotencyKey: await request.headerValue("idempotency-key"),
});
const respond = responders[calls.length - 1];
if (!respond) throw new Error(`unexpected create call ${calls.length}`);
await respond(route);
});
return calls;
}
const created = (route: Route) =>
route.fulfill({
status: 201,
headers: { Location: `${feature.api}/${ITEM.id}` },
json: envelope(ITEM),
});
async function signInAt(page: Page, path: string, heading: string) {
if (!server) throw new Error("The generated feature's build is not served.");
await page.goto(`${server.origin}${path}`);
await expect(page.getByRole("heading", { level: 1 })).toHaveText(
KO_MESSAGES["route.auth.required.title"],
);
await page.getByRole("button", { name: KO_MESSAGES["action.signIn"] }).click();
await expect(page.getByRole("heading", { level: 1 })).toHaveText(heading);
}
const openForm = (page: Page) => signInAt(page, routePath(feature.create), word("order.form.title"));
const nameField = (page: Page) =>
page.getByRole("textbox", { name: new RegExp(word("order.form.name"), "u") });
const saveButton = (page: Page) => page.getByRole("button", { name: word("order.form.save") });
async function expectNoBlockingViolations(page: Page) {
const results = await new AxeBuilder({ page }).withTags(WCAG_TAGS).analyze();
expect(
results.violations.filter((violation) =>
["critical", "serious"].includes(violation.impact ?? ""),
),
).toEqual([]);
}
/**
* 1103/08-02. Saves from the keyboard and checks where focus lands: in the
* status above the form, one Tab away from its first action, not on the body
* after the page turned the save button busy.
*/
async function saveFromKeyboard(page: Page, firstAction: string) {
await nameField(page).fill(ITEM.name);
await saveButton(page).focus();
await page.keyboard.press("Enter");
await expect(page.locator(".page-template__feedback")).toBeFocused();
await page.keyboard.press("Tab");
await expect(page.getByRole("button", { name: firstAction })).toBeFocused();
}
test.describe("the route", () => {
test("opens the protected list through the local demo sign-in", async ({ page }) => {
await answerReads(page);
await signInAt(page, routePath(feature.list), word("order.list.title"));
// The closed menu drawer holds a second copy of the status (08-01).
await expect(
page.getByRole("banner").getByText(KO_MESSAGES["shell.session.authenticated"]),
).toBeVisible();
// The answered row went through the production codec, mapper and query cache.
await expect(page.getByRole("link", { name: ITEM.name })).toBeVisible();
});
// 08-04. Feature screens take their words from the catalog.
test("draws its screens without Korean copy in en-US", async ({ page }) => {
await answerReads(page);
await signInAt(page, routePath(feature.list), word("order.list.title"));
await page.getByRole("combobox", { name: "언어" }).first().selectOption("en-US");
const main = page.getByRole("main");
const english = feature.messages["en-US"];
await expect(main.getByRole("heading", { level: 1 })).toHaveText(english["order.list.title"]!);
await expect(main).not.toContainText(/[가-힣]/u);
await main.getByRole("link", { name: english["order.list.create"]! }).click();
await expect(main.getByRole("button", { name: english["order.form.save"]! })).toBeVisible();
await expect(main).not.toContainText(/[가-힣]/u);
});
});
test.describe("the form", () => {
test("focuses the first invalid field when a save fails validation", async ({ page }) => {
await openForm(page);
await saveButton(page).click();
await expect(nameField(page)).toBeFocused();
await expect(nameField(page)).toHaveAttribute("aria-invalid", "true");
await expect(page.getByRole("alert")).toContainText(KO_MESSAGES["form.errorSummary"]);
});
test("asks before leaving unsaved input and stays when writing continues", async ({ page }) => {
await openForm(page);
await nameField(page).fill("Unsaved order");
await page
.getByRole("navigation", { name: KO_MESSAGES["template.breadcrumb"] })
.getByRole("link", { name: word("order.list.title") })
.click();
const dialog = page.getByRole("dialog", { name: KO_MESSAGES["form.unsaved.title"] });
await expect(dialog).toBeVisible();
await dialog.getByRole("button", { name: KO_MESSAGES["action.continueEditing"] }).click();
await expect(dialog).toBeHidden();
await expect(nameField(page)).toHaveValue("Unsaved order");
expect(new URL(page.url()).pathname).toBe(routePath(feature.create));
});
test("keeps the form template within a 320px viewport", async ({ page }) => {
await page.setViewportSize({ width: 320, height: 720 });
await openForm(page);
const viewport = await page.evaluate(() => ({
clientWidth: document.documentElement.clientWidth,
scrollWidth: document.documentElement.scrollWidth,
}));
expect(viewport.scrollWidth).toBeLessThanOrEqual(viewport.clientWidth);
});
// round9 confirm review. The page always hands FormSaveFeedback to the
// template's feedback area; with nothing to say it takes no row, so the
// heading and the fields stay one gap apart.
test("leaves no room for a save feedback area with nothing to say", async ({ page }) => {
await openForm(page);
const spacing = await page.evaluate(() => {
const box = (selector: string) => document.querySelector(selector)?.getBoundingClientRect();
const heading = box(".page-template__heading");
const layout = box(".page-template__layout");
const template = document.querySelector(".page-template");
return heading && layout && template
? { between: layout.top - heading.bottom, rowGap: parseFloat(getComputedStyle(template).rowGap) }
: null;
});
expect(spacing).not.toBeNull();
expect(spacing?.between).toBeCloseTo(spacing?.rowGap ?? 0, 0);
});
});
test.describe("the save", () => {
test("saves through the production command path with an idempotency key", async ({ page }) => {
await answerReads(page);
await openForm(page);
const calls = await answerCreates(page, [created]);
await nameField(page).fill(` ${ITEM.name} `);
await saveButton(page).click();
await expect(page.getByRole("heading", { level: 1 })).toHaveText(ITEM.name);
expect(calls).toEqual([{ name: ITEM.name, idempotencyKey: expect.any(String) }]);
});
test.describe("after a rate-limited save", () => {
// Chromium and WebKit log a 4xx fetch response to the console, and the
// client cancels the 429 body unread, which Chromium reports as aborted.
test.use({
allowedBrowserFailure:
/^console:error:.*status of 429|^requestfailed:POST:\/[^:]*:net::ERR_ABORTED$/u,
});
const rateLimited = (route: Route) =>
route.fulfill({
status: 429,
headers: { "retry-after": "1" },
json: failure("RATE_LIMITED", true),
});
test("keeps the input and saves on retry", async ({ page }) => {
await answerReads(page);
await openForm(page);
const calls = await answerCreates(page, [rateLimited, created]);
await nameField(page).fill(ITEM.name);
await saveButton(page).click();
await expect(page.getByText(KO_MESSAGES["error.rate_limited"])).toBeVisible();
await expect(nameField(page)).toHaveValue(ITEM.name);
await page.getByRole("button", { name: KO_MESSAGES["action.retry"] }).click();
await expect(page.getByRole("heading", { level: 1 })).toHaveText(ITEM.name);
expect(calls.map((call) => call.name)).toEqual([ITEM.name, ITEM.name]);
});
test("keeps keyboard focus in the failure status", async ({ page }) => {
await openForm(page);
await answerCreates(page, [rateLimited]);
await saveFromKeyboard(page, KO_MESSAGES["action.retry"]);
});
});
test.describe("after a save whose result is unknown", () => {
// The browsers log the 500 response to the console.
test.use({ allowedBrowserFailure: /^console:error:.*status of 500/u });
const lost = (route: Route) =>
route.fulfill({
status: 500,
headers: {
"x-correlation-id": "corr-save-500",
"access-control-expose-headers": "x-correlation-id",
},
json: failure("INTERNAL_ERROR", false),
});
// 0929/08-04. The case a user most wants to report shows the id support
// can find in the server logs.
test("shows the result as unknown with the request id support can find", async ({ page }) => {
await openForm(page);
await answerCreates(page, [lost]);
await nameField(page).fill(ITEM.name);
await saveButton(page).click();
await expect(page.getByText(KO_MESSAGES["async.mutationEffectUnknown"])).toBeVisible();
await expect(page.getByText(/^지원 참조: /u)).toBeVisible();
});
test("keeps keyboard focus in the unknown-result status", async ({ page }) => {
await openForm(page);
await answerCreates(page, [lost]);
await saveFromKeyboard(page, KO_MESSAGES["action.confirmMutationApplied"]);
});
test("resends with the same key from the keyboard and opens the item", async ({ page }) => {
await answerReads(page);
await openForm(page);
const calls = await answerCreates(page, [lost, created]);
await saveFromKeyboard(page, KO_MESSAGES["action.confirmMutationApplied"]);
await page.keyboard.press("Tab");
await expect(
page.getByRole("button", { name: KO_MESSAGES["action.resendMutation"] }),
).toBeFocused();
await page.keyboard.press("Enter");
await expect(page.getByRole("heading", { level: 1 })).toHaveText(ITEM.name);
expect(calls).toHaveLength(2);
expect(calls[1]?.idempotencyKey).toBe(calls[0]?.idempotencyKey);
});
// 1105/08-02. Confirming an unknown create opens the list, which shows
// whether the item was saved.
test("opens the list after the user confirms the save from the keyboard", async ({ page }) => {
await answerReads(page);
await openForm(page);
const calls = await answerCreates(page, [lost]);
await saveFromKeyboard(page, KO_MESSAGES["action.confirmMutationApplied"]);
await page.keyboard.press("Enter");
await expect(page.getByRole("heading", { level: 1 })).toHaveText(word("order.list.title"));
await expect(page.getByRole("link", { name: ITEM.name })).toBeVisible();
expect(calls).toHaveLength(1);
});
});
});
// 08-05. The protected screens are scanned signed in and in each state they
// can show. The state must be on screen before axe runs.
test.describe("accessibility", () => {
for (const [state, list, visible] of [
["success", [ITEM], ITEM.name],
["empty", [], KO_MESSAGES["async.empty"]],
// A 200 that breaks the response schema: a 5xx would also log a console
// error, which the strict fixture rejects on its own.
["error", [{ wrong: true }], KO_MESSAGES["error.schema_mismatch"]],
] as const) {
test(`@a11y list ${state} state has no blocking violations`, async ({ page }) => {
await answerReads(page, list);
await signInAt(page, routePath(feature.list), word("order.list.title"));
await expect(page.getByRole("main")).toContainText(visible);
await expectNoBlockingViolations(page);
});
}
test("@a11y detail has no blocking violations", async ({ page }) => {
await answerReads(page);
await signInAt(page, routePath(feature.detail, ITEM.id), ITEM.name);
await expectNoBlockingViolations(page);
});
test("@a11y form with submit errors has no blocking violations", async ({ page }) => {
await openForm(page);
await saveButton(page).click();
await expect(page.getByRole("alert")).toContainText(KO_MESSAGES["form.errorSummary"]);
await expectNoBlockingViolations(page);
});
});