import { describe, expect, test } from "vitest"; import { createUseTranslate, type ReactI18nextLike } from "./useTranslate.js"; // Coverage gap: the resilience paths of the translator returned by // `createUseTranslate` — the ICU catch-and-fallback (lines 58-59), the // `icu: false` opt-out, and the non-string coercion of a raw `t()` result. function makeStubDeps(translations: Record, language: string): ReactI18nextLike { return { useTranslation: () => ({ // `t` is typed to return string; we deliberately allow non-string values // through the stub to exercise the defensive coercion branch. t: ((key: string) => translations[key] ?? key) as (key: string, options?: Record) => string, i18n: { language }, }), }; } describe("createUseTranslate — ICU fallback", () => { test("ships the raw message instead of crashing when ICU parsing fails", () => { // The message is detected as ICU (matches the plural pattern) but is // structurally invalid (no `other` clause), so `formatIcu` throws. The // translator must fall through and return the source string. const malformed = "{count, plural, one {# item}}"; const deps = makeStubDeps({ broken: malformed }, "en-US"); const t = createUseTranslate(deps)(); expect(t("broken", { count: 1 })).toBe(malformed); }); }); describe("createUseTranslate — icu opt-out", () => { test("bypasses the ICU formatter entirely when icu:false", () => { // With ICU disabled, even a well-formed ICU message is returned verbatim // from i18next rather than being rendered. const icuMessage = "{count, plural, one {# item} other {# items}}"; const deps = makeStubDeps({ items: icuMessage }, "en-US"); const t = createUseTranslate(deps, { icu: false })(); expect(t("items", { count: 5 })).toBe(icuMessage); }); }); describe("createUseTranslate — non-string coercion", () => { test("coerces a non-string t() result to a string", () => { // i18next can return non-strings (e.g. with returnObjects); the translator // contract is `=> string`, so the value must be stringified. const deps = makeStubDeps({ count: 42 }, "en-US"); const t = createUseTranslate(deps)(); expect(t("count")).toBe("42"); }); });