Files
clean-architecture-frontend…/tests/component/locale-platform.test.tsx
T
DongHyeonka ade1fc4a71 fix(i18n): 제품이 화면 언어를 자기 파일에서 선언한다
문제: 지원 locale 목록, 언어 대체, 글 방향, 문구 표, 셸의 언어
선택지가 템플릿 파일 다섯 곳에 손으로 적혀 있다. 한 언어 제품은 가짜
en-US 문구를 만들거나 템플릿 파일을 고쳐야 하고, 운영 셸 메뉴에
Pseudo·RTL 시험 locale이 보인다(0929/08-01).

고른 방법(1101 결정 (가), 템플릿이 확장 지점을 연다):
- 제품 소유 src/contracts/product-contracts.ts에 PRODUCT_LOCALES
  (기본 ko-KR, en-US)와 DEV_LOCALES(기본 en-XA, ar-EG)를 둔다.
- message-contract가 둘에서 SUPPORTED_LOCALES, 언어 대체(같은 언어의
  첫 선언 locale, 없으면 첫 제품 locale), 글 방향(RTL 언어 집합),
  DEFAULT_LOCALE을 만든다. 시험 locale은 en-US 문구를, en-US가 없으면 첫
  제품 locale 문구를 보인다.
- catalog.ts는 선언한 제품 locale마다 문구 표 하나를 둔다. en-US 표는
  en-US를 선언했을 때만 모든 키를 요구한다.
- 셸 언어 선택지는 선언에서 나오고, locale이 하나면 선택을 그리지 않는다.
  템플릿 문구에 없는 locale은 Intl.DisplayNames의 자기 이름으로 적는다.
버린 대안: 운영 환경(APP_ENV)에서 시험 locale을 자동으로 숨기기 —
presentation이 실행 환경을 읽는 포트가 없고, e2e가 production 빌드로
시험 locale을 고른다. 제품이 DEV_LOCALES를 비우는 쪽이 명시적이다.

위험·한계: ko-KR은 다른 표를 대조하는 원본이라 남겨야 한다. 템플릿에
없는 언어를 선언하면 그 문구 표가 catalog.ts에 있어야 한다(타입 오류로
알린다). 시험 locale을 빼는 것은 제품이 DEV_LOCALES를 비울 때다.

검증: desktop 결과는 PR 본문.

Refs: 0929/08-01
2026-11-13 21:16:40 +09:00

234 lines
7.4 KiB
TypeScript

// @vitest-environment jsdom
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { useState } from "react";
import { describe, expect, it } from "vitest";
import { z } from "zod";
import {
Button,
Drawer,
Pagination,
Tabs,
} from "../../src/presentation/design-system/index.ts";
import {
LocaleProvider,
useLocale,
type SupportedLocale,
} from "../../src/presentation/i18n/index.ts";
import {
ErrorSummary,
Form,
FormField,
useAppForm,
} from "../../src/presentation/forms/index.ts";
import { ApplicationProvider } from "../../src/presentation/providers/application-provider.tsx";
import { PreferenceProviders } from "../../src/presentation/providers/preference-providers.tsx";
import { AppRouter } from "../../src/presentation/routes/app-router.tsx";
import { createTestApplication } from "../helpers/create-test-application.ts";
function LocaleHarness() {
const { direction, locale, message, setLocale } = useLocale();
const [drawerOpen, setDrawerOpen] = useState(false);
return (
<>
<label htmlFor="test-locale">{message("shell.locale")}</label>
<select
id="test-locale"
onChange={(event) =>
setLocale(event.currentTarget.value as SupportedLocale)
}
value={locale}
>
<option value="ko-KR">한국어</option>
<option value="en-US">English</option>
<option value="ar-EG">RTL</option>
</select>
<output>{`${locale}:${direction}`}</output>
<Button onClick={() => setDrawerOpen(true)}>
{message("shell.menu")}
</Button>
<Drawer
closeLabel={message("shell.closeMenu")}
onClose={() => setDrawerOpen(false)}
open={drawerOpen}
title={message("shell.menu")}
>
content
</Drawer>
</>
);
}
function LocaleSelect() {
const { locale, message, setLocale } = useLocale();
return (
<>
<label htmlFor="form-locale">{message("shell.locale")}</label>
<select
id="form-locale"
onChange={(event) =>
setLocale(event.currentTarget.value as SupportedLocale)
}
value={locale}
>
<option value="ko-KR">한국어</option>
<option value="en-US">English</option>
</select>
</>
);
}
function ValidatedForm() {
const form = useAppForm({
schema: z.object({ name: z.string().min(2) }).strict(),
defaultValues: { name: "" },
allowedServerFields: ["name"],
mapToCommand: (values) => values,
submit: async () => ({ ok: true as const, value: null }),
});
return (
<Form onSubmit={(event) => void form.submitForm(event)}>
<ErrorSummary
fieldErrors={form.fieldErrors}
formErrors={form.formErrors}
fieldLabels={{ name: "Name" }}
fieldId={form.fieldId}
/>
<FormField {...form.field("name")} label="Name" />
<button type="submit">Submit</button>
</Form>
);
}
describe("locale provider runtime", () => {
// 08-10. A shown error is kept as a message key, not a translated string.
it("re-translates displayed form errors when the locale changes", async () => {
const user = userEvent.setup();
render(
<LocaleProvider>
<LocaleSelect />
<ValidatedForm />
</LocaleProvider>,
);
await user.click(screen.getByRole("button", { name: "Submit" }));
expect(screen.getByRole("alert")).toHaveTextContent(
"입력 내용을 확인해 주세요.Name: 입력값이 너무 짧습니다.",
);
await user.selectOptions(screen.getByLabelText("언어"), "en-US");
expect(screen.getByRole("alert")).toHaveTextContent(
"Review the entered information.Name: This value is too short.",
);
expect(screen.getByRole("textbox", { name: "Name" })).toHaveAccessibleDescription(
"This value is too short.",
);
});
it("switches copy and synchronizes the document language and direction", async () => {
const user = userEvent.setup();
render(
<LocaleProvider>
<LocaleHarness />
</LocaleProvider>,
);
expect(document.documentElement).toHaveAttribute("lang", "ko-KR");
await user.selectOptions(screen.getByLabelText("언어"), "en-US");
expect(screen.getByLabelText("Language")).toHaveValue("en-US");
expect(document.documentElement).toHaveAttribute("lang", "en-US");
expect(document.documentElement).toHaveAttribute("dir", "ltr");
await user.selectOptions(screen.getByLabelText("Language"), "ar-EG");
expect(document.documentElement).toHaveAttribute("lang", "ar-EG");
expect(document.documentElement).toHaveAttribute("dir", "rtl");
await user.click(screen.getByRole("button", { name: "Menu" }));
expect(screen.getByRole("dialog", { name: "Menu" })).toHaveAttribute(
"open",
);
});
it("reverses horizontal tab focus semantics in RTL", async () => {
const user = userEvent.setup();
render(
<LocaleProvider initialLocale={"ar-EG" as string as SupportedLocale}>
<Tabs
activation="manual"
label="sections"
tabs={[
{ id: "one", label: "One", panel: "One panel" },
{ id: "two", label: "Two", panel: "Two panel" },
{ id: "three", label: "Three", panel: "Three panel" },
]}
/>
</LocaleProvider>,
);
const first = screen.getByRole("tab", { name: "One" });
first.focus();
await user.keyboard("{ArrowRight}");
expect(screen.getByRole("tab", { name: "Three" })).toHaveFocus();
await user.keyboard("{ArrowLeft}");
expect(first).toHaveFocus();
});
it("keeps pagination semantics while direction-aware icons remain decorative", () => {
render(
<LocaleProvider initialLocale={"ar-EG" as string as SupportedLocale}>
<Pagination
label="pages"
nextLabel="Next page"
onChange={() => {}}
page={2}
pageCount={3}
pageLabel={(page) => `Page ${page}`}
previousLabel="Previous page"
/>
</LocaleProvider>,
);
expect(
screen.getByRole("button", { name: "Previous page" }),
).toBeEnabled();
expect(screen.getByRole("button", { name: "Next page" })).toBeEnabled();
expect(screen.queryByRole("img")).not.toBeInTheDocument();
});
});
describe("persisted locale preference", () => {
it("stores the chosen locale and starts the next mount from it", async () => {
const user = userEvent.setup();
const stored = new Map<string, unknown>();
const application = createTestApplication({
preferences: {
read: (name) => ({ ok: true as const, value: stored.get(name) }),
write: (name, value) => {
stored.set(name, value);
return { ok: true as const };
},
remove: (name) => {
stored.delete(name);
return { ok: true as const };
},
},
});
const mount = () =>
render(
<ApplicationProvider application={application}>
<PreferenceProviders>
<AppRouter />
</PreferenceProviders>
</ApplicationProvider>,
);
window.history.pushState({}, "", "/missing");
const first = mount();
await user.selectOptions(await screen.findByLabelText("언어"), "en-US");
expect(stored.get("LOCALE")).toBe("en-US");
first.unmount();
mount();
expect(await screen.findByLabelText("Language")).toHaveValue("en-US");
expect(document.documentElement).toHaveAttribute("lang", "en-US");
});
});