|
| 1 | +import { test } from "node:test" |
| 2 | +import assert from "node:assert/strict" |
| 3 | + |
| 4 | +// localize() reads the browser.i18n namespace through the browser shim, which |
| 5 | +// resolves from globalThis at import time; install a mock before importing. |
| 6 | +// |
| 7 | +// Contract: the mock MUST be installed before the dynamic import() below — |
| 8 | +// keep it dynamic, do not turn it into a static import (those are hoisted and |
| 9 | +// would run before the mock is set). The mock is left on globalThis without |
| 10 | +// teardown; that is safe because `node --test` runs each test file in its own |
| 11 | +// process, so it cannot leak into other test files. Both assumptions break |
| 12 | +// under an in-process runner (e.g. --test-isolation=none). |
| 13 | +globalThis.browser = { |
| 14 | + i18n: { getMessage: (key) => (key === "greeting" ? "Hello" : `<${key}>`) }, |
| 15 | +} |
| 16 | +const { localize } = await import("../i18n.js") |
| 17 | + |
| 18 | +// a minimal element stand-in exposing just textContent |
| 19 | +function element(textContent) { |
| 20 | + return { textContent } |
| 21 | +} |
| 22 | + |
| 23 | +// a fake root whose querySelectorAll("[i18n]") returns the given elements |
| 24 | +function root(elements) { |
| 25 | + return { querySelectorAll: () => elements } |
| 26 | +} |
| 27 | + |
| 28 | +test("localize replaces a __MSG_<key>__ placeholder with its translation", () => { |
| 29 | + const el = element("__MSG_greeting__") |
| 30 | + localize(root([el])) |
| 31 | + assert.equal(el.textContent, "Hello") |
| 32 | +}) |
| 33 | + |
| 34 | +test("localize replaces every placeholder across the tagged elements", () => { |
| 35 | + const a = element("__MSG_greeting__") |
| 36 | + const b = element("prefix __MSG_missing__ suffix") |
| 37 | + localize(root([a, b])) |
| 38 | + assert.equal(a.textContent, "Hello") |
| 39 | + assert.equal(b.textContent, "prefix <missing> suffix") |
| 40 | +}) |
| 41 | + |
| 42 | +test("localize leaves text without a placeholder untouched", () => { |
| 43 | + const el = element("plain text") |
| 44 | + localize(root([el])) |
| 45 | + // unchanged (and reference identity of the string is irrelevant, value is) |
| 46 | + assert.equal(el.textContent, "plain text") |
| 47 | +}) |
0 commit comments