import { describe, it, expect, vi, beforeEach } from "vitest"; // The global vitest.setup mock of lib/server/i18n stands in for other suites; this one needs the real module. vi.unmock("@/app/lib/server/i18n"); // localise-admin-shell: server components and generateMetadata translate through the request locale, // resolved exactly as RootLayout always has (enabled runtime locales only). const cookieValue = vi.hoisted(() => ({ value: undefined as string | undefined })); const acceptLanguage = vi.hoisted(() => ({ value: null as string | null })); vi.mock("next/headers", () => ({ cookies: async () => ({ get: (name: string) => name === "bb_locale" && cookieValue.value ? { value: cookieValue.value } : undefined, }), headers: async () => ({ get: (name: string) => (name === "accept-language" ? acceptLanguage.value : null) }), })); const catalog = vi.hoisted(() => ({ fn: vi.fn() })); vi.mock("./messages", () => ({ loadMessageCatalog: catalog.fn })); const runtimeLocales = vi.hoisted(() => ({ fn: vi.fn() })); vi.mock("./locales", () => ({ loadRuntimeLocales: runtimeLocales.fn })); import { getServerT, requestLocale } from "./i18n"; const LOCALES = [ { code: "en_US", label: "English" }, { code: "zh_CN", label: "简体中文" }, { code: "ms_MY", label: "Bahasa Melayu", enabled: false }, ]; beforeEach(() => { cookieValue.value = undefined; acceptLanguage.value = null; runtimeLocales.fn.mockReset().mockResolvedValue(LOCALES); catalog.fn.mockReset().mockResolvedValue({}); }); describe("requestLocale", () => { it("honours a bb_locale cookie naming an enabled locale, and returns every locale for the editor", async () => { cookieValue.value = "zh_CN"; expect(await requestLocale()).toEqual({ locale: "zh_CN", locales: LOCALES }); }); it("ignores a cookie naming a disabled locale and falls back to Accept-Language", async () => { cookieValue.value = "ms_MY"; acceptLanguage.value = "zh-CN,zh;q=0.9"; expect((await requestLocale()).locale).toBe("zh_CN"); }); it("defaults to en_US with no cookie and no Accept-Language", async () => { expect((await requestLocale()).locale).toBe("en_US"); }); }); describe("getServerT", () => { it("loads the request locale's catalog and interpolates params", async () => { cookieValue.value = "zh_CN"; catalog.fn.mockResolvedValue({ Greeting: "你好,{name}" }); const t = await getServerT(); expect(catalog.fn).toHaveBeenCalledWith("zh_CN"); expect(t("Greeting", { name: "Ann" })).toBe("你好,Ann"); }); it("falls back to the English default, then to the code", async () => { const t = await getServerT(); expect(t("Logout")).toBe("Logout"); expect(t("NoSuchCode")).toBe("NoSuchCode"); }); });