Open History to see the last commit
1import { afterEach, describe, expect, it, vi } from "vite-plus/test";
2
3import { COMPOSER_CONTEXT_CLIPBOARD_MIME } from "@t3tools/shared/composerContextClipboard";
4
5import { writeTextToClipboard } from "./useCopyToClipboard";
6
7describe("writeTextToClipboard", () => {
8 it("reserves plain text even when an extra flavor attempts to replace it", async () => {
9 const write = vi.fn().mockResolvedValue(undefined);
10 vi.stubGlobal("window", {});
11 vi.stubGlobal("navigator", { clipboard: { write, writeText: vi.fn() } });
12 vi.stubGlobal(
13 "ClipboardItem",
14 class {
15 constructor(readonly data: Record<string, Blob>) {}
16 },
17 );
18 await expect(
19 writeTextToClipboard("original", undefined, {
20 "text/plain": "replacement",
21 "text/html": "<b>original</b>",
22 }),
23 ).resolves.toBe(true);
24 const items = write.mock.calls[0]![0] as Array<{ data: Record<string, Blob> }>;
25 expect(await items[0]!.data["text/plain"]!.text()).toBe("original");
26 });
27 it("reports a rejected HTML copy without silently copying only plain text", async () => {
28 const writeText = vi.fn().mockResolvedValue(undefined);
29 vi.stubGlobal("window", {});
30 vi.stubGlobal("navigator", {
31 clipboard: { write: vi.fn().mockRejectedValue(new Error("denied")), writeText },
32 });
33 vi.stubGlobal(
34 "ClipboardItem",
35 class {
36 constructor(readonly data: Record<string, Blob>) {}
37 },
38 );
39 await expect(
40 writeTextToClipboard(
41 "<table></table>",
42 undefined,
43 { "text/html": "<table></table>" },
44 { requireHtml: true },
45 ),
46 ).rejects.toMatchObject({ _tag: "ClipboardWriteError" });
47 expect(writeText).not.toHaveBeenCalled();
48 await expect(writeTextToClipboard("plain")).resolves.toBe(true);
49 expect(writeText).toHaveBeenCalledWith("plain");
50 });
51 afterEach(() => {
52 vi.unstubAllGlobals();
53 });
54
55 it("keeps caller-built rich HTML when attaching a context fragment", async () => {
56 const write = vi.fn().mockResolvedValue(undefined);
57 vi.stubGlobal("window", {});
58 vi.stubGlobal("navigator", { clipboard: { write, writeText: vi.fn() } });
59 vi.stubGlobal(
60 "ClipboardItem",
61 class {
62 constructor(readonly data: Record<string, Blob>) {}
63 },
64 );
65 const fragment = JSON.stringify({ version: 1, source: {}, records: [] });
66 const rich = "<p><strong>Message</strong></p>";
67
68 await expect(
69 writeTextToClipboard("Message", undefined, {
70 [COMPOSER_CONTEXT_CLIPBOARD_MIME]: fragment,
71 "text/html": rich,
72 }),
73 ).resolves.toBe(true);
74
75 const items = write.mock.calls[0]![0] as Array<{ data: Record<string, Blob> }>;
76 const html = await items[0]!.data["text/html"]!.text();
77 expect(html).toContain(rich);
78 expect(html).toContain("data-t3-context-fragment=");
79 });
80});