Files
clean-architecture-frontend…/tests/component/ui-primitives.test.tsx
DongHyeonka 7a9856bb29 fix(design-system): Alert와 Toast가 tone을 아이콘과 숨은 이름으로도 알린다
Alert와 Toast는 tone을 색으로만 나타내서, 제목이 중립이면 경고와 정보가
갈리지 않는다.

두 primitive가 제목 앞에 tone마다 다른 장식 아이콘과 숨은 tone 이름을
그린다. 둘이 같이 쓰는 StatusTone은 배럴에 내보내지 않는다. 호출자가
제목에 상태를 쓰게 문서로만 적는 안은 강제할 수단이 없어 버렸다.

위험: 두 primitive의 텍스트가 tone 이름으로 시작한다. 글자 전체를 견주는
시험과 제목에 같은 낱말을 넣은 제품은 고쳐야 한다. 실제 스크린 리더와
forced-colors에서는 보지 않았다.

검증: 고치기 전 10개 실패, 고친 뒤 18개 통과. tone 아이콘 둘을
맞바꾼 것까지 변이 5개 모두 실패한다.
골든 1장은 성공 Alert 제목 줄의 아이콘 차이만 받았다.

Refs: DES-FE-0002
2026-11-22 23:37:48 +09:00

210 lines
7.1 KiB
TypeScript

// @vitest-environment jsdom
import { render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { useEffect, useState } from "react";
import { describe, expect, it, vi } from "vitest";
import { Alert } from "../../src/presentation/components/ui/alert.ts";
import { Badge } from "../../src/presentation/components/ui/badge.ts";
import { Button } from "../../src/presentation/components/ui/button.ts";
import { Card } from "../../src/presentation/components/ui/card.ts";
import { Dialog } from "../../src/presentation/components/ui/dialog.ts";
import { TextField } from "../../src/presentation/components/ui/text-field.ts";
import {
ErrorIcon,
InfoIcon,
SuccessIcon,
ToastProvider,
useToast,
WarningIcon,
} from "../../src/presentation/design-system/index.ts";
describe("domain-neutral UI primitives", () => {
it("connects field help and validation errors to the input", () => {
render(
<TextField
label="이름"
description="표시할 이름입니다."
error="이름을 입력해 주세요."
required
/>,
);
const field = screen.getByRole("textbox", { name: "이름" });
expect(field).toBeRequired();
expect(field).toHaveAccessibleDescription(
"표시할 이름입니다. 이름을 입력해 주세요.",
);
expect(field).toHaveAttribute("aria-invalid", "true");
});
it("exposes semantic variants without changing native button behavior", async () => {
const user = userEvent.setup();
const onClick = vi.fn();
render(
<>
<Button variant="danger" onClick={onClick}>
제거
</Button>
<Button disabled>사용 불가</Button>
</>,
);
await user.click(screen.getByRole("button", { name: "제거" }));
expect(onClick).toHaveBeenCalledOnce();
expect(screen.getByRole("button", { name: "제거" })).toHaveClass(
"ui-button--danger",
);
expect(screen.getByRole("button", { name: "사용 불가" })).toBeDisabled();
});
it("labels cards, alerts, and badges with visible content", async () => {
const user = userEvent.setup();
const dismiss = vi.fn();
render(
<Card title="상태 카드" footer={<Badge variant="success">준비됨</Badge>}>
<Alert title="저장됨" variant="success" onDismiss={dismiss}>
안전하게 반영했습니다.
</Alert>
</Card>,
);
expect(screen.getByRole("article", { name: "상태 카드" })).toBeVisible();
expect(screen.getByRole("status")).toHaveTextContent(
"저장됨안전하게 반영했습니다.",
);
expect(screen.getByText("준비됨")).toHaveClass("ui-badge--success");
await user.click(screen.getByRole("button", { name: "저장됨 알림 닫기" }));
expect(dismiss).toHaveBeenCalledOnce();
});
it("closes a modal and restores focus to its trigger", async () => {
const user = userEvent.setup();
function DialogHarness() {
const [open, setOpen] = useState(false);
return (
<>
<Button onClick={() => setOpen(true)}>모달 열기</Button>
<Dialog
open={open}
onClose={() => setOpen(false)}
title="연동 확인"
actions={<Button onClick={() => setOpen(false)}>확인</Button>}
>
안전한 설명
</Dialog>
</>
);
}
render(<DialogHarness />);
const trigger = screen.getByRole("button", { name: "모달 열기" });
await user.click(trigger);
expect(screen.getByRole("dialog", { name: "연동 확인" })).toHaveAttribute(
"open",
);
await user.click(screen.getByRole("button", { name: "확인" }));
await waitFor(() => expect(trigger).toHaveFocus());
expect(screen.getByRole("dialog", { hidden: true })).not.toHaveAttribute(
"open",
);
});
});
// DES-FE-0002. The colour is not the only carrier of a tone: the primitive
// draws an icon and says the tone, whatever words the caller put in the title.
describe("Alert and Toast tone without colour", () => {
const TITLE = "업로드 한도";
const TONES = [
["info", "정보"],
["success", "성공"],
["warning", "경고"],
["danger", "위험"],
] as const;
type Tone = (typeof TONES)[number][0];
const ICONS = {
info: InfoIcon,
success: SuccessIcon,
warning: WarningIcon,
danger: ErrorIcon,
} as const;
function PushToast({ tone }: Readonly<{ tone?: Tone }>) {
const { push } = useToast();
useEffect(() => push({ id: "tone", title: TITLE, tone }), [push, tone]);
return null;
}
async function renderToast(tone?: Tone) {
render(
<ToastProvider>
<PushToast tone={tone} />
</ToastProvider>,
);
return (await screen.findByText(TITLE)).closest("article")!;
}
function toneIcons(surface: HTMLElement) {
return [...surface.querySelectorAll('svg[aria-hidden="true"]')].filter(
(icon) => !icon.closest("button"),
);
}
// What assistive technology reads: the text less what is hidden from it and
// less the close button, which has a name of its own.
function readText(surface: HTMLElement) {
const copy = surface.cloneNode(true) as HTMLElement;
for (const unread of copy.querySelectorAll('[aria-hidden="true"], button')) unread.remove();
return copy.textContent;
}
// Soft, so that a run names both missing halves.
function expectTone(surface: HTMLElement, label: string) {
const icons = toneIcons(surface);
expect.soft(icons, "a decorative tone icon outside the close button").toHaveLength(1);
expect.soft(readText(surface), "the tone in the accessible text").toBe(`${label} ${TITLE}`);
if (icons[0]) {
expect(icons[0].compareDocumentPosition(screen.getByText(TITLE))).toBe(
Node.DOCUMENT_POSITION_FOLLOWING,
);
expect(screen.getByText(label)).toHaveClass("visually-hidden");
}
}
it.each(TONES)("marks a %s Alert with an icon and the label %s", (variant, label) => {
render(<Alert onDismiss={vi.fn()} title={TITLE} variant={variant} />);
expectTone(screen.getByRole(variant === "danger" ? "alert" : "status"), label);
});
it.each(TONES)("marks a %s Toast with an icon and the label %s", async (tone, label) => {
expectTone(await renderToast(tone), label);
});
it("marks a Toast pushed without a tone as info", async () => {
expectTone(await renderToast(), "정보");
});
// Four shapes and four labels still hold when two icons trade places.
it.each(TONES)("draws the %s icon for that tone", (variant) => {
const Icon = ICONS[variant];
const expected = render(<Icon />).container.querySelector("svg")!.innerHTML;
const { container } = render(<Alert title={TITLE} variant={variant} />);
expect(toneIcons(container).map((icon) => icon.innerHTML)).toEqual([expected]);
});
it("gives each tone an icon of its own shape", () => {
const { container } = render(
<>
{TONES.map(([variant]) => (
<Alert key={variant} title={TITLE} variant={variant} />
))}
</>,
);
expect(new Set(toneIcons(container).map((icon) => icon.innerHTML)).size).toBe(TONES.length);
});
});