69 lines
2.2 KiB
TypeScript
69 lines
2.2 KiB
TypeScript
import { beforeEach, describe, expect, it, vi } from "vitest";
|
|
|
|
const custom = vi.fn();
|
|
vi.mock("sonner", () => ({ toast: { custom: (...args: unknown[]) => custom(...args) } }));
|
|
vi.mock("react", async (importOriginal) => {
|
|
const actual = await importOriginal<typeof import("react")>();
|
|
return {
|
|
...actual,
|
|
useCallback: <T extends (...args: never[]) => unknown>(callback: T) => callback,
|
|
useRef: <T,>(value: T) => ({ current: value }),
|
|
};
|
|
});
|
|
vi.mock("react-i18next", () => ({
|
|
useTranslation: () => ({ t: (key: string) => key }),
|
|
}));
|
|
vi.mock("~/components/notifications/SaveToast", () => ({
|
|
SaveToast: () => null,
|
|
}));
|
|
|
|
import { useCopyToast } from "./use-copy-toast";
|
|
|
|
function lastToastProps(): { variant: string; title: string; description?: string } {
|
|
const factory = custom.mock.lastCall?.[0] as () => React.ReactElement;
|
|
return factory().props as { variant: string; title: string; description?: string };
|
|
}
|
|
|
|
beforeEach(() => {
|
|
custom.mockClear();
|
|
Object.defineProperty(globalThis, "navigator", {
|
|
configurable: true,
|
|
value: { clipboard: { writeText: vi.fn().mockResolvedValue(undefined) } },
|
|
});
|
|
});
|
|
|
|
describe("useCopyToast", () => {
|
|
it("reports success only after the clipboard write resolves", async () => {
|
|
const copyText = useCopyToast();
|
|
|
|
expect(await copyText("value")).toBe(true);
|
|
|
|
expect(navigator.clipboard.writeText).toHaveBeenCalledWith("value");
|
|
expect(lastToastProps()).toMatchObject({
|
|
variant: "success",
|
|
title: "shared.copyToast.successTitle",
|
|
});
|
|
});
|
|
|
|
it("supports a value-specific success headline", async () => {
|
|
const copyText = useCopyToast();
|
|
|
|
await copyText("https://example.test", { successKey: "settings.forms.toast.linkCopied" });
|
|
|
|
expect(lastToastProps().title).toBe("settings.forms.toast.linkCopied");
|
|
});
|
|
|
|
it("reports a clipboard failure with a recovery hint", async () => {
|
|
vi.mocked(navigator.clipboard.writeText).mockRejectedValueOnce(new Error("denied"));
|
|
const copyText = useCopyToast();
|
|
|
|
expect(await copyText("value")).toBe(false);
|
|
|
|
expect(lastToastProps()).toMatchObject({
|
|
variant: "error",
|
|
title: "shared.copyToast.errorTitle",
|
|
description: "shared.copyToast.errorDescription",
|
|
});
|
|
});
|
|
});
|