forked from Lilly-Protocol/lily-frontend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclipboard.test.ts
More file actions
46 lines (39 loc) · 1.5 KB
/
Copy pathclipboard.test.ts
File metadata and controls
46 lines (39 loc) · 1.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import { describe, expect, it, vi, beforeEach, afterEach } from "vitest";
import { copyText } from "./clipboard";
describe("copyText", () => {
beforeEach(() => {
Object.assign(navigator, {
clipboard: {
writeText: vi.fn().mockResolvedValue(undefined),
},
});
// jsdom does not implement execCommand; stub it for fallback tests
if (typeof document.execCommand !== "function") {
(document as any).execCommand = vi.fn().mockReturnValue(true);
}
});
afterEach(() => {
vi.restoreAllMocks();
});
it("uses navigator.clipboard when available", async () => {
const result = await copyText("hello");
expect(result).toBe(true);
expect(navigator.clipboard.writeText).toHaveBeenCalledWith("hello");
});
it("falls back to execCommand when clipboard API throws", async () => {
vi.mocked(navigator.clipboard.writeText).mockRejectedValueOnce(new Error("denied"));
const execSpy = vi.spyOn(document, "execCommand").mockReturnValue(true);
const result = await copyText("fallback");
expect(result).toBe(true);
expect(execSpy).toHaveBeenCalledWith("copy");
});
it("returns false when both paths fail", async () => {
vi.mocked(navigator.clipboard.writeText).mockRejectedValueOnce(new Error("denied"));
const execSpy = vi.spyOn(document, "execCommand").mockImplementation(() => {
throw new Error("nope");
});
const result = await copyText("fail");
expect(result).toBe(false);
expect(execSpy).toHaveBeenCalled();
});
});