Files
clean-architecture-frontend…/tests/e2e/accessibility.spec.ts
T
DongHyeonka 757d1c736b fix(a11y)!: 실패 화면으로만 검사한 라우트를 a11y.json에서 통과로 세지 않는다
문제
접근성 e2e는 보호 라우트의 목록 조회에 빈 목록을 답한다. 자원 하나를
읽는 상세 라우트(참조 기능의 상세, 생성기 --with-create의 상세)는
일반 답이 없어 실패 화면에서 axe를 돌린다. 그런데
scripts/write-a11y-report.ts는 설치된 라우트 전체를 scope에 넣고
automatedStatus "passed"를 쓴다. 화면 내용은 한 번도 검사하지 않은
라우트가 통과로 보고된다. annotation은 test 결과에만 남는다.

고른 방법과 버린 대안
- scripts/lib/a11y-data-state.ts(새 파일): 라우트 test가 끝날 때
  자기 상태를 artifacts/tests/a11y-data-state/<ROUTE_ID>.json에 남긴다.
  실패 화면으로만 봤으면 이유를 쓰고, 아니면 지운다. 그래서 라우트마다
  마지막 실행이 정한다. 세 엔진이 같은 파일을 쓰므로 임시 파일에 쓰고
  rename한다.
- tests/e2e/accessibility.spec.ts: 위 기록을 남긴다(공개 라우트와
  데이터 상태로 본 라우트는 지운다).
- a11y.json schemaVersion 2: scope에는 자기 상태로 검사한 라우트만,
  notChecked에는 실패 화면으로만 본 라우트와 이유를 넣는다. 둘을
  합치면 설치된 라우트 레지스트리와 같아야 한다(schema가 본다).
- 상세 라우트를 실제 데이터 상태로 검사하는 안은 버렸다. 출력
  validator에서 유효한 값을 일반적으로 만들 수 없고, 기능마다 견본
  응답을 받는 자리를 새로 열어야 한다.
- annotation을 Playwright JSON reporter로 읽는 안은 버렸다. test:a11y
  스크립트의 reporter와 산출물 경로를 바꿔야 하고, 경로는 다른 작업
  (12-04)이 바꾸는 중이다.
- 매뉴얼(docs/manual/reference/create-feature.md)에 상세 라우트가
  notChecked로 적히고 수동 검토가 맡는다고 적는다.

위험·한계
- a11y.json 모양이 바뀐다(schemaVersion 1 → 2, scope 의미, 새 필드).
  템플릿 안의 소비자는 ci-artifact-validator 하나이고 같이 바꿨다.
- 템플릿 상태에서도 참조 기능의 상세 라우트가 notChecked로 나온다.
  지금까지 실제로 검사하지 않던 것이 드러나는 것이다.
- 기록 디렉터리는 artifacts/tests 아래 고정 경로다. 12-04가 산출물
  경로를 실행마다 나누면 이 경로도 따라가야 한다.
- 라우트 test가 돌지 않은 실행에서는 그 라우트의 지난 기록이 남는다.
  지난 기록이 "검사 안 함"이면 덜 주장하는 쪽이라 위험하지 않다.

검증
- desktop batch에서 확인:
  node scripts/run-vitest.ts run tests/unit/a11y-report.test.ts
  corepack pnpm test:a11y (세 엔진) 뒤 artifacts/tests/a11y.json의
  notChecked에 REFERENCE_RESOURCE_DETAIL이 있고 scope에 없어야 한다.
- RED: 부모 커밋에는 scripts/lib/a11y-data-state.ts가 없어 새 unit
  test 파일 전체가 실패한다.

Refs: 1103/11-01
BREAKING CHANGE: artifacts/tests/a11y.json이 schemaVersion 2가 된다. scope는 실패 화면으로만 본 라우트를 빼고, 그 라우트는 새 notChecked 배열에 { routeId, reason }으로 들어간다. scope를 설치된 라우트 전체로 읽던 도구는 scope와 notChecked를 합쳐 읽는다.
2026-11-06 01:05:22 +09:00

150 lines
6.4 KiB
TypeScript

import AxeBuilder from "@axe-core/playwright";
import { recordA11yDataState } from "../../scripts/lib/a11y-data-state.ts";
import { expect, test, type Page } from "../support/browser/strict-browser-test.ts";
import { ROUTE_REGISTRY } from "../../src/features/installed-feature-contracts.ts";
import { COMPOSED_CONTRACT_CONTRIBUTIONS } from "../../src/features/loaded-feature-runtimes.ts";
import type { RouteDefinition } from "../../src/contracts/routes.ts";
import { KO_MESSAGES } from "../../src/presentation/i18n/catalog.ts";
import {
answerInstalledApiRequest,
type InstalledApiAnswer,
} from "./support/installed-api-answers.ts";
const WCAG_TAGS = ["wcag2a", "wcag2aa", "wcag21a", "wcag21aa"];
const SIGN_IN_TITLE = KO_MESSAGES["route.auth.required.title"];
const CATALOG = KO_MESSAGES as Readonly<Record<string, string>>;
async function blockingViolations(page: Page) {
const results = await new AxeBuilder({ page }).withTags(WCAG_TAGS).analyze();
return results.violations.filter((violation) =>
["critical", "serious"].includes(violation.impact ?? ""),
);
}
// 08-05/11-02. The app shell draws `main` before the route chunk arrives, so
// axe waits for the route's own h1. A public route's h1 is its catalog title.
// A protected route is scanned after the demo sign-in, never on the sign-in
// prompt; the feature's own spec pins its exact headings and states.
// Widened: without an installed feature every route is public, and the
// `session-required` branch must still typecheck (sample removal).
const ROUTES: readonly RouteDefinition[] = Object.values(ROUTE_REGISTRY);
// 1103/16-03. Every path parameter gets one value: a feature with its own
// parameter names needs no edit here.
const PATH_PARAMETER_VALUE = "a11y-1";
const API_ORIGIN = "http://localhost:8080";
for (const definition of ROUTES) {
const route =
definition.path === "*"
? "/not-found"
: definition.path.replace(/:[A-Za-z][A-Za-z0-9_]*/gu, PATH_PARAMETER_VALUE);
test(`@a11y ${route} has no critical or serious axe violations`, async ({
page,
}) => {
const heading = page.getByRole("heading", { level: 1 });
if (definition.access === "session-required") {
// 1103/11-01. Feature data is not this spec's subject: a list read gets
// an empty list in the frame its descriptor declares, so the page is
// scanned in its empty state, not on a response-shape error.
const answers: InstalledApiAnswer[] = [];
await page.route(`${API_ORIGIN}/**`, (request) => {
const answer = answerInstalledApiRequest(
COMPOSED_CONTRACT_CONTRIBUTIONS,
request.request().method(),
new URL(request.request().url()).pathname,
);
answers.push(answer);
return answer.kind === "unanswerable"
? request.fulfill({ status: 501, body: answer.reason ?? answer.request })
: request.fulfill({ json: answer.body });
});
await page.goto(route);
await expect(heading).toHaveText(SIGN_IN_TITLE);
await page.getByRole("button", { name: "로그인 시작" }).click();
await expect(heading).toBeVisible();
await expect(heading).not.toHaveText(SIGN_IN_TITLE);
await expect(page.locator("[aria-busy='true']")).toHaveCount(0);
expect(
answers.filter((answer) => answer.kind === "unanswerable"),
"requests no installed list or single-resource read answers",
).toEqual([]);
const singleResourceReads = answers.flatMap((answer) =>
answer.kind === "single-resource" ? [answer.operationId] : [],
);
if (singleResourceReads.length === 0) {
// A shape the page does not read fails here, before axe passes it.
await expect(page.getByRole("alert")).toHaveCount(0);
await recordA11yDataState(definition.routeId, null);
} else {
// No generic body answers a read of one resource: a detail page is
// scanned in its failure state. 1103/11-01. a11y.json then lists it
// under `notChecked`, not as passed.
const reason = `scanned on its failure state only: ${singleResourceReads.join(", ")} reads one resource`;
test.info().annotations.push({ type: "a11y-data-state", description: reason });
await recordA11yDataState(definition.routeId, reason);
}
} else {
await page.goto(route);
const title = CATALOG[`route.${definition.routeId}.title`];
await expect(heading).toHaveText(title ?? definition.title);
await recordA11yDataState(definition.routeId, null);
}
expect(await blockingViolations(page)).toEqual([]);
});
}
test("@a11y keyboard reaches the primary route action with visible focus", async ({
page,
}) => {
await page.goto("/");
const action = page.getByRole("link", { name: "플랫폼 구성 보기" });
await expect(action).toBeVisible();
await page.keyboard.press("Tab");
await expect(action).toBeFocused();
await expect(action).toHaveCSS("outline-style", "solid");
});
// 08-09. axe's skip-link rule is best-practice, outside WCAG_TAGS, so the only
// way past the header and sidebar (WCAG 2.4.1) needs its own check.
test("@a11y skip link moves keyboard focus into main", async ({ page }) => {
await page.goto("/examples/ui");
await expect(page.getByRole("heading", { level: 1 })).toBeFocused();
const skipLink = page.getByRole("link", { name: "본문으로 건너뛰기" });
await skipLink.focus();
await expect(skipLink).toBeFocused();
await page.keyboard.press("Enter");
await expect
.poll(() =>
page.evaluate(
() => document.querySelector("main")?.contains(document.activeElement) ?? false,
),
)
.toBe(true);
});
test("@a11y reduced-motion policy disables long animation", async ({ page }) => {
await page.emulateMedia({ reducedMotion: "reduce" });
await page.goto("/");
const duration = await page
.locator("body")
.evaluate((body) => getComputedStyle(body).animationDuration);
expect(["0s", "0.00001s", "1e-05s"]).toContain(duration);
});
test("@a11y opened design-system dialog has no blocking violations", async ({
page,
}) => {
await page.goto("/examples/ui");
await page.getByRole("button", { name: "모달 열기" }).click();
const results = await new AxeBuilder({ page })
.include(".ui-dialog")
.withTags(WCAG_TAGS)
.analyze();
expect(
results.violations.filter((violation) =>
["critical", "serious"].includes(violation.impact ?? ""),
),
).toEqual([]);
});