Files
clean-architecture-frontend…/tests/e2e/reference-save.spec.ts
DongHyeonka 2d5d41f85d fix(forms): 필드 오류가 아닌 저장 실패 뒤 키보드 포커스를 실패 상태로 옮긴다 (1103/08-02)
문제
참조 폼 페이지는 저장 중과 결과 불명 동안 저장 버튼에 disabled를 준다.
포커스가 있던 버튼이 꺼지면 브라우저가 포커스를 body로 내려놓는다. 폼은 필드
오류일 때만 포커스를 옮겼으므로, 키보드로 저장했다가 결과 불명(500)이나 429를
받으면 세 엔진 모두 포커스가 body로 떨어졌다. 복구 버튼은 폼 위 feedback
자리에 있어 셸 머리말부터 다시 지나야 닿았다.

고른 방법
- useAppForm이 feedbackId를 내고, 필드 오류·성공이 아닌 결과(결과 불명,
  재인증, 권한 없음, 다시 시도, 사용 불가, 충돌)로 끝나면 렌더 뒤 그 요소에
  포커스를 준다. FormPage(StandardPage)는 feedbackId를 받으면 feedback 자리를
  id + tabIndex=-1인 포커스 대상으로 만든다. 페이지마다 포커스 코드를 복사하지
  않게 하려고 hook과 템플릿에 두었다.
- 참조 폼의 저장 버튼은 저장 중에 disabled 대신 Button의 pending(aria-busy)을
  쓴다. 중복 제출은 지금처럼 폼(submitForm)과 onSubmit 가드가 막는다. 결과
  불명 동안에는 여전히 꺼진다(08-01 범위). 그때는 위의 포커스 이동이 받는다.
- 첫 행동 버튼 대신 feedback 자리 전체를 포커스한 이유: 실패 종류마다 버튼
  구성이 다르고, Tab 한 번에 첫 복구 버튼에 닿는다.
매뉴얼 02 6절 FormPage에 feedbackId와 pending을 적었다.

위험·한계
- 스크린 리더가 포커스된 feedback 자리를 어떻게 읽는지는 확인하지 않았다.
- 파생 폼 페이지는 feedbackId를 넘겨야 이 동작을 얻는다.
- "deduplicates create" 테스트의 저장 중 단언을 disabled에서 aria-busy와
  포커스 유지로 바꿨다. 한 번만 호출되는 단언은 그대로다.

검증
- RED: reference-page.test.tsx 새 2행(결과 불명, 429)이 수정 전 실패. e2e
  reference-save.spec.ts 새 2건이 수정 전 소스에서 chromium·firefox·webkit
  6건 모두 실패(feedback 자리 focused 아님).
- 수정 후 reference-save·reference-form e2e 3엔진 45건 통과(heavy lock,
  CHOKIDAR_USEPOLLING=1). tests/component·tests/features 60 files / 368
  tests 통과. check:types, eslint, check:design-system, check:i18n,
  verify:documentation 통과.

Refs: docs/reviews/2026-11-03-maturity-review/08-presentation.md 08-02
2026-11-04 20:42:32 +09:00

175 lines
5.8 KiB
TypeScript

import type { Page, Route } from "@playwright/test";
import { expect, test } from "../support/browser/strict-browser-test.ts";
const CREATE_URL = "http://localhost:8080/api/reference-resources";
type CreateCall = Readonly<{ name: unknown; idempotencyKey: string | null }>;
async function openForm(page: Page) {
await page.route(`${CREATE_URL}?*`, (route) => route.fulfill({ json: [] }));
await page.goto("/examples/reference-resources/new");
await page.getByRole("button", { name: "로그인 시작" }).click();
await expect(
page.getByRole("heading", { name: "Reference resource 만들기" }),
).toBeVisible();
}
/** Answers each POST with the next responder and records what was sent. */
async function routeCreate(
page: Page,
responders: readonly ((route: Route) => Promise<void>)[],
): Promise<CreateCall[]> {
const calls: CreateCall[] = [];
await page.route(CREATE_URL, 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;
}
/**
* 1103/08-02. Saves from the keyboard and checks where focus lands: in the
* failure status above the form, one Tab away from its first action, not on
* the body after the page disabled the save button.
*/
async function saveFromKeyboard(page: Page, expectedFirstAction: string) {
await page
.getByRole("textbox", { name: /새 항목 이름/ })
.fill("Saved in the browser");
await page.getByRole("button", { name: "저장" }).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: expectedFirstAction }),
).toBeFocused();
}
const created = (route: Route) =>
route.fulfill({
status: 201,
json: {
id: "browser-created",
name: "Saved in the browser",
createdAt: "2026-07-26T00:00:00.000Z",
},
});
test("saves a new reference resource through the production command path", async ({
page,
}) => {
await openForm(page);
const calls = await routeCreate(page, [created]);
await page
.getByRole("textbox", { name: /새 항목 이름/ })
.fill("Saved in the browser");
await page.getByRole("button", { name: "저장" }).click();
await expect(page.getByRole("status")).toHaveText("저장했습니다.");
expect(calls).toHaveLength(1);
expect(calls[0]?.name).toBe("Saved in the browser");
expect(calls[0]?.idempotencyKey).toBeTruthy();
});
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:\/api\/reference-resources:net::ERR_ABORTED$/u,
});
test("keeps the input and saves on retry", async ({ page }) => {
await openForm(page);
const calls = await routeCreate(page, [
(route) =>
route.fulfill({
status: 429,
headers: { "retry-after": "1" },
json: { title: "Too many requests" },
}),
created,
]);
const name = page.getByRole("textbox", { name: /새 항목 이름/ });
await name.fill("Saved in the browser");
await page.getByRole("button", { name: "저장" }).click();
await expect(
page.getByText("요청이 많습니다. 잠시 후 다시 시도해 주세요."),
).toBeVisible();
await expect(name).toHaveValue("Saved in the browser");
await page.getByRole("button", { name: "다시 시도" }).click();
await expect(page.getByRole("status")).toHaveText("저장했습니다.");
expect(calls.map((call) => call.name)).toEqual([
"Saved in the browser",
"Saved in the browser",
]);
});
test("keeps keyboard focus in the failure status", async ({ page }) => {
await openForm(page);
await routeCreate(page, [
(route) =>
route.fulfill({
status: 429,
headers: { "retry-after": "1" },
json: { title: "Too many requests" },
}),
]);
await saveFromKeyboard(page, "다시 시도");
});
});
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,
});
// 0929/08-04. The case a user most wants to report shows the id support
// can find in the server logs.
test("shows the request id the server echoed", async ({ page }) => {
await openForm(page);
await routeCreate(page, [
(route) =>
route.fulfill({
status: 500,
headers: {
"x-correlation-id": "corr-save-500",
"access-control-expose-headers": "x-correlation-id",
},
json: { title: "Internal error" },
}),
]);
await page
.getByRole("textbox", { name: /새 항목 이름/ })
.fill("Saved in the browser");
await page.getByRole("button", { name: "저장" }).click();
await expect(page.getByText("변경 결과를 확인할 수 없습니다.")).toBeVisible();
await expect(page.getByText("지원 참조: corr-save-500")).toBeVisible();
});
test("keeps keyboard focus in the unknown-result status", async ({ page }) => {
await openForm(page);
await routeCreate(page, [
(route) => route.fulfill({ status: 500, json: { title: "Internal error" } }),
]);
await saveFromKeyboard(page, "변경됨으로 확인");
});
});