Skip to content

Commit

Permalink
Add test for placeholders in translations (#3387)
Browse files Browse the repository at this point in the history
  • Loading branch information
HalvorHaugan authored Nov 22, 2024
1 parent eb3f830 commit 293fade
Showing 1 changed file with 44 additions and 12 deletions.
56 changes: 44 additions & 12 deletions @navikt/core/react/src/util/i18n/locales.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,22 +5,54 @@ import en from "./locales/en";
import nb from "./locales/nb";
import nn from "./locales/nn";

function checkValues(obj: Translations | Record<string, string>) {
Object.entries(obj).forEach(([key, value]) => {
if (key === "dateLocale") {
return;
}
if (typeof value === "object") {
checkValues(value);
} else {
expect(value).toBeTypeOf("string");
expect(value).not.toBe("");
}
});
type NestedObject = Record<string, string | Record<string, string>>;

function checkValues(obj: Translations | NestedObject) {
Object.entries(obj).forEach(
([key, value]: [string, string | NestedObject]) => {
if (key === "dateLocale") {
return;
}
if (typeof value === "object") {
checkValues(value);
} else {
expect(value).toBeTypeOf("string");
expect(value).not.toBe("");
}
},
);
}

function checkTranslationPlaceholders(
baseTranslations: Translations | NestedObject, // Translations to check against
translations: Translations | NestedObject, // Translations to check
) {
Object.entries(baseTranslations).forEach(
([key, baseVal]: [string, string | NestedObject]) => {
if (key === "dateLocale") {
return;
}
if (typeof baseVal === "object") {
checkTranslationPlaceholders(baseVal, translations[key]);
} else {
const correctPlaceholders = baseVal.match(/{[^}]*}/g) || [];
const transPlaceholders = translations[key].match(/{[^}]*}/g) || [];
expect(
transPlaceholders.sort(),
`Wrong placeholders in "${translations[key]}" (key=${key})`,
).toEqual(correctPlaceholders.sort());
}
},
);
}

describe("Locale", () => {
test("NB should have no empty strings", () => checkValues(nb));
test("NN should have no empty strings", () => checkValues(nn));
test("EN should have no empty strings", () => checkValues(en));

test("NN should have the same placeholders as NB", () =>
checkTranslationPlaceholders(nb, nn));
test("EN should have the same placeholders as NB", () =>
checkTranslationPlaceholders(nb, en));
});

0 comments on commit 293fade

Please sign in to comment.