55 lines
2.0 KiB
TypeScript
55 lines
2.0 KiB
TypeScript
import { test, expect } from "bun:test";
|
|
import { I18N_RUNTIME, resolveI18n, makeT, resolveLang, translateHtml } from "../src/index.ts";
|
|
|
|
const i18n = resolveI18n(
|
|
{
|
|
en: { hi: "Hi {name}", nav: { home: "Home" }, ph: "Email" },
|
|
es: { hi: "Hola {name}", nav: { home: "Inicio" } },
|
|
},
|
|
{ default: "en" },
|
|
);
|
|
|
|
test("makeT interpolates params and nested keys", () => {
|
|
const t = makeT(i18n, "es");
|
|
expect(t("hi", { name: "Ana" })).toBe("Hola Ana");
|
|
expect(t("nav.home")).toBe("Inicio");
|
|
});
|
|
|
|
test("makeT falls back to default language, then the key", () => {
|
|
const t = makeT(i18n, "es");
|
|
expect(t("ph")).toBe("Email"); // missing in es → en
|
|
expect(t("nope")).toBe("nope"); // missing everywhere → key
|
|
});
|
|
|
|
test("resolveLang: cookie → Accept-Language → default", () => {
|
|
expect(resolveLang(i18n, "es", null)).toBe("es");
|
|
expect(resolveLang(i18n, undefined, "fr,es;q=0.8")).toBe("es");
|
|
expect(resolveLang(i18n, "xx", "de")).toBe("en"); // invalid cookie + unsupported header
|
|
});
|
|
|
|
test("language changes use the shared browser cookie helper", () => {
|
|
expect(I18N_RUNTIME).toContain('window.wrnCookies.set(cookieName, lang, "language", cookie)');
|
|
});
|
|
|
|
test("translateHtml resolves data-t text and t:attr attributes", () => {
|
|
const t = makeT(i18n, "en");
|
|
const out = translateHtml('<input t:placeholder="ph"><span data-t="nav.home"></span>', t);
|
|
expect(out).toContain('placeholder="Email"');
|
|
expect(out).toContain('<span data-t="nav.home">Home</span>');
|
|
});
|
|
|
|
test("translateHtml is a no-op without markers", () => {
|
|
const t = makeT(i18n, "en");
|
|
expect(translateHtml("<p>plain</p>", t)).toBe("<p>plain</p>");
|
|
});
|
|
|
|
test("translateHtml preserves authored fallback text when a key is unavailable", () => {
|
|
const t = (key: string) => key;
|
|
expect(translateHtml('<h1 data-t="missing.title">Readable fallback</h1>', t)).toBe(
|
|
'<h1 data-t="missing.title">Readable fallback</h1>',
|
|
);
|
|
expect(translateHtml('<input t:placeholder="missing.placeholder" />', t)).toBe(
|
|
'<input placeholder="" />',
|
|
);
|
|
});
|