59 lines
2.3 KiB
TypeScript
59 lines
2.3 KiB
TypeScript
import { describe, expect, test } from "vitest";
|
|
import { createUseTranslate, isIcuMessage, type ReactI18nextLike } from "./useTranslate.js";
|
|
|
|
// We stub the `react-i18next` surface — running the actual React renderer is
|
|
// out of scope here. The hook is a thin layer of glue logic so a stub gives us
|
|
// > 99 % of the value at < 1 % of the setup cost.
|
|
|
|
function makeDeps(translations: Record<string, string>, language: string): ReactI18nextLike {
|
|
return {
|
|
useTranslation: () => ({
|
|
t: (key: string, values?: Record<string, unknown>) => {
|
|
const raw = translations[key] ?? key;
|
|
if (!values) return raw;
|
|
// mimic i18next's basic `{{name}}` interpolation so non-ICU messages
|
|
// still substitute values as callers expect.
|
|
return raw.replace(/\{\{(\w+)\}\}/g, (_, name) => String(values[name] ?? `{{${name}}}`));
|
|
},
|
|
i18n: { language },
|
|
}),
|
|
};
|
|
}
|
|
|
|
describe("isIcuMessage", () => {
|
|
test("detects plural and select messages", () => {
|
|
expect(isIcuMessage("{count, plural, one {# item} other {# items}}")).toBe(true);
|
|
expect(isIcuMessage("{role, select, admin {Admin} other {Guest}}")).toBe(true);
|
|
expect(isIcuMessage("Hello {{name}}")).toBe(false);
|
|
expect(isIcuMessage("Plain string")).toBe(false);
|
|
});
|
|
});
|
|
|
|
describe("createUseTranslate", () => {
|
|
test("routes ICU plurals through intl-messageformat", () => {
|
|
const deps = makeDeps(
|
|
{ itemsSelected: "{count, plural, =0 {Nothing selected} one {# item selected} other {# items selected}}" },
|
|
"en-US",
|
|
);
|
|
const useTranslate = createUseTranslate(deps);
|
|
const t = useTranslate();
|
|
expect(t("itemsSelected", { count: 0 })).toBe("Nothing selected");
|
|
expect(t("itemsSelected", { count: 1 })).toBe("1 item selected");
|
|
expect(t("itemsSelected", { count: 5 })).toBe("5 items selected");
|
|
});
|
|
|
|
test("falls through to i18next for non-ICU messages", () => {
|
|
const deps = makeDeps({ greet: "Hello {{name}}" }, "en-US");
|
|
const useTranslate = createUseTranslate(deps);
|
|
const t = useTranslate();
|
|
expect(t("greet", { name: "Ada" })).toBe("Hello Ada");
|
|
});
|
|
|
|
test("exposes the active language", () => {
|
|
const deps = makeDeps({ greet: "Moin" }, "de-DE");
|
|
const useTranslate = createUseTranslate(deps);
|
|
const t = useTranslate();
|
|
expect(t.language).toBe("de-DE");
|
|
});
|
|
});
|