From 4f04cfb6978539e58b16148200dd73c9fed6f379 Mon Sep 17 00:00:00 2001 From: Adam Antal Date: Tue, 2 Jan 2024 14:57:52 +0100 Subject: [PATCH 1/2] Don't throw a missing translation error for empty strings --- src/core/utils/text.tsx | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/core/utils/text.tsx b/src/core/utils/text.tsx index fb7e8bc57d..9f14ed4d58 100644 --- a/src/core/utils/text.tsx +++ b/src/core/utils/text.tsx @@ -105,13 +105,15 @@ const processTexts = (texts: string[], placeholders: Placeholders) => ); export const useText = (): UseTextFunction => { - const { data } = useSelector((state: RootState) => state.text); + const { data } = useSelector<{ data: Record }>( + (state: RootState) => state.text + ); return (key: string, { placeholders, count } = { count: 0 }) => { if (!data) { throw new Error(`The translation store is broken.`); } - if (!data[key]) { + if (data[key] === undefined) { throw new Error(`The translation for ${key} is not defined.`); } const textDefinition = constructTextDefinitionFromRawTextTextEntry( From 98c26842fbe6117d8e6a7d77a9c8a42328ddf7a9 Mon Sep 17 00:00:00 2001 From: Adam Antal Date: Tue, 2 Jan 2024 14:58:22 +0100 Subject: [PATCH 2/2] Write a unit test for useText translations where the string is empty --- src/tests/unit/text.test.tsx | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/src/tests/unit/text.test.tsx b/src/tests/unit/text.test.tsx index af0768d4e9..0ecae2c569 100644 --- a/src/tests/unit/text.test.tsx +++ b/src/tests/unit/text.test.tsx @@ -15,7 +15,8 @@ const store = configureStore({ data: { simpleText: "This is a @simple test", placeholdersText: `{"type":"simple","text":["This is a text with a @placeholder embedded. Does it work? @result it does!"]}`, - pluralText: `{"type":"plural","text":["You have 1 material on the waiting list","You have @count materials on the waiting list"]}` + pluralText: `{"type":"plural","text":["You have 1 material on the waiting list","You have @count materials on the waiting list"]}`, + emptyStringText: "" } } } @@ -88,3 +89,15 @@ test("Should throw an error if the text definition is not found", () => { ); }); }); + +test("Shouldn't throw an error if the text is an empty string", () => { + const { result } = renderHook(() => useText(), { wrapper: Wrapper }); + // We name it t, because that is how we normally use it in the code. + const t = result.current; + + act(() => { + // This test would be failing if an error was thrown for empty strings. + // That's why we don't need to define anything else here to know that it works. + t("emptyStringText"); + }); +});