Files
jobtrackingapp/job-tracker-ui/src/dialog-text.test.tsx
T

147 lines
8.5 KiB
TypeScript

import React from "react";
import "@testing-library/jest-dom";
import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import { ConfirmProvider } from "./confirm";
import { PromptProvider } from "./prompt";
import { useDialogActions } from "./dialogs";
import { I18nProvider } from "./i18n/I18nProvider";
import { resolveDialogText, type DialogText } from "./dialogText";
import { translations } from "./i18n/translations";
type Copy = { title: DialogText; message: DialogText; confirmLabel: DialogText; cancelLabel: DialogText };
type Kind = "confirm" | "prompt";
const userText = 'Søknad 東京 🧑‍💻 <img src=x onerror=alert(1)> & {count}';
const metadata: Copy = {
title: { key: "attachmentsTitle", params: { count: 0 } },
message: { key: "attachmentsDeleteConfirm", params: { name: userText } },
confirmLabel: { key: "confirm" },
cancelLabel: { key: "cancel" },
};
const copyByLanguage = {
en: { title: "Attachments (0)", message: `Delete attachment "${userText}"?`, confirm: "Confirm", cancel: "Cancel" },
nb: { title: "Vedlegg (0)", message: `Slette vedlegget "${userText}"?`, confirm: "Bekreft", cancel: "Avbryt" },
};
function Caller({ kind, copy, result }: { kind: Kind; copy: Copy; result: (value: boolean | string | null) => void }) {
const { confirmAction, promptForValue } = useDialogActions();
return <button onClick={() => {
if (kind === "confirm") void confirmAction(copy.message, { ...copy, destructive: true }).then(result);
else void promptForValue(copy.message, "Original draft", copy).then(result);
}}>Open</button>;
}
function mount(kind: Kind, copy: Copy, result: (value: boolean | string | null) => void, localized = true) {
const providers = <ConfirmProvider><PromptProvider><Caller kind={kind} copy={copy} result={result} /></PromptProvider></ConfirmProvider>;
render(localized ? <I18nProvider>{providers}</I18nProvider> : providers);
const opener = screen.getByRole("button", { name: "Open" });
opener.focus();
fireEvent.click(opener);
}
afterEach(() => localStorage.removeItem("uiLanguage"));
test.each([
["confirm", "en", "nb", true], ["confirm", "nb", "en", false],
["prompt", "en", "nb", true], ["prompt", "nb", "en", false],
] as const)("pending %s resolves metadata from %s to %s and settles once", async (kind, from, to, accepted) => {
localStorage.setItem("uiLanguage", from);
const result = jest.fn();
mount(kind, metadata, result);
const dialog = await screen.findByRole("dialog", { name: copyByLanguage[from].title });
expect(dialog).toHaveAccessibleDescription(copyByLanguage[from].message);
expect(within(dialog).getByRole("button", { name: copyByLanguage[from].confirm })).toBeVisible();
expect(within(dialog).getByRole("button", { name: copyByLanguage[from].cancel })).toBeVisible();
const input = kind === "prompt" ? within(dialog).getByRole("textbox") as HTMLInputElement : null;
if (input) {
await waitFor(() => expect(input).toHaveFocus());
fireEvent.change(input, { target: { value: userText } });
input.setSelectionRange(2, 7);
expect(input).toHaveAttribute("maxlength", "180");
expect(input).toHaveAccessibleDescription(`${userText.length}/180`);
} else {
expect(within(dialog).getByRole("button", { name: copyByLanguage[from].cancel })).toHaveFocus();
}
await act(async () => window.dispatchEvent(new StorageEvent("storage", { key: "uiLanguage", newValue: to })));
expect(screen.getByRole("dialog", { name: copyByLanguage[to].title })).toBe(dialog);
expect(dialog).toHaveAccessibleDescription(copyByLanguage[to].message);
expect(dialog.querySelector("img")).toBeNull();
if (input) {
expect(within(dialog).getByRole("textbox", { name: copyByLanguage[to].message })).toBe(input);
expect(input).toHaveValue(userText);
expect(input).toHaveFocus();
expect([input.selectionStart, input.selectionEnd]).toEqual([2, 7]);
}
expect(result).not.toHaveBeenCalled();
const action = within(dialog).getByRole("button", { name: copyByLanguage[to][accepted ? "confirm" : "cancel"] });
fireEvent.click(action); fireEvent.click(action);
await waitFor(() => expect(result).toHaveBeenCalledTimes(1));
expect(result).toHaveBeenCalledWith(kind === "confirm" ? accepted : accepted ? userText : null);
await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());
expect(screen.getByRole("button", { name: "Open" })).toHaveFocus();
});
test.each(["confirm", "prompt"] as const)("%s metadata falls back to interpolated English without I18n context", async kind => {
localStorage.setItem("uiLanguage", "nb");
const result = jest.fn();
mount(kind, metadata, result, false);
const dialog = await screen.findByRole("dialog", { name: "Attachments (0)" });
expect(dialog).toHaveAccessibleDescription(`Delete attachment "${userText}"?`);
expect(dialog.querySelector("img")).toBeNull();
fireEvent.click(within(dialog).getByRole("button", { name: "Cancel" }));
await waitFor(() => expect(result).toHaveBeenCalledTimes(1));
expect(result).toHaveBeenCalledWith(kind === "confirm" ? false : null);
});
test.each([
["confirm", ""], ["prompt", ""],
["confirm", "confirmAction"], ["prompt", "enterValue"],
] as const)("%s leaves literal %j verbatim during locale changes", async (kind, literal) => {
localStorage.setItem("uiLanguage", "en");
const result = jest.fn();
mount(kind, { title: literal, message: literal, confirmLabel: literal, cancelLabel: literal }, result);
const dialog = await screen.findByRole("dialog");
await act(async () => window.dispatchEvent(new StorageEvent("storage", { key: "uiLanguage", newValue: "nb" })));
expect(within(dialog).getByRole("heading").textContent).toBe(literal);
expect(document.getElementById(dialog.getAttribute("aria-describedby")!)?.textContent).toBe(literal);
expect(within(dialog).getAllByRole("button").map(button => button.textContent)).toEqual([literal, literal]);
expect(result).not.toHaveBeenCalled();
fireEvent.keyDown(dialog, { key: "Escape" });
await waitFor(() => expect(result).toHaveBeenCalledTimes(1));
expect(result).toHaveBeenCalledWith(kind === "confirm" ? false : null);
});
test.each([
["confirm", "en", "nb"], ["confirm", "nb", "en"],
["prompt", "en", "nb"], ["prompt", "nb", "en"],
] as const)("fallback parameter in pending %s follows %s to %s", async (kind, from, to) => {
localStorage.setItem("uiLanguage", from);
const result = jest.fn();
mount(kind, { ...metadata, message: { key: "jobTableMoveOneConfirm", params: { title: userText, company: { key: "jobTableCompany" } } } }, result);
const dialog = await screen.findByRole("dialog");
expect(dialog).toHaveAccessibleDescription(translations[from].jobTableMoveOneConfirm.replace("{title}", userText).replace("{company}", translations[from].jobTableCompany));
const input = kind === "prompt" ? within(dialog).getByRole("textbox") : null;
if (input) fireEvent.change(input, { target: { value: userText } });
await act(async () => window.dispatchEvent(new StorageEvent("storage", { key: "uiLanguage", newValue: to })));
expect(screen.getByRole("dialog")).toBe(dialog);
expect(dialog).toHaveAccessibleDescription(translations[to].jobTableMoveOneConfirm.replace("{title}", userText).replace("{company}", translations[to].jobTableCompany));
expect(dialog.querySelector("img")).toBeNull();
if (input) expect(input).toHaveValue(userText);
expect(result).not.toHaveBeenCalled();
fireEvent.click(within(dialog).getByRole("button", { name: translations[to].cancel }));
await waitFor(() => expect(result).toHaveBeenCalledTimes(1));
expect(result).toHaveBeenCalledWith(kind === "confirm" ? false : null);
});
test.each(["confirm", "prompt"] as const)("fallback parameter in %s resolves English without context", async kind => {
const result = jest.fn();
mount(kind, { ...metadata, message: { key: "cvDashboardDeleteMessage", params: { name: { key: "cvDashboardThisCv" } } } }, result, false);
const dialog = await screen.findByRole("dialog");
expect(dialog).toHaveAccessibleDescription(translations.en.cvDashboardDeleteMessage.replace("{name}", translations.en.cvDashboardThisCv));
fireEvent.click(within(dialog).getByRole("button", { name: "Cancel" }));
await waitFor(() => expect(result).toHaveBeenCalledTimes(1));
});
test.each(["", 0, "jobTableCompany", userText])("fallback parameter preserves primitive %j verbatim", value => {
expect(resolveDialogText({ key: "jobTableMoveOneConfirm", params: { title: value, company: { key: "jobTableCompany" } } })).toBe(translations.en.jobTableMoveOneConfirm.replace("{title}", String(value)).replace("{company}", translations.en.jobTableCompany));
});