-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcopy-text.test.ts
More file actions
50 lines (42 loc) · 1.45 KB
/
Copy pathcopy-text.test.ts
File metadata and controls
50 lines (42 loc) · 1.45 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
47
48
49
50
// @vitest-environment jsdom
import { describe, expect, it, vi } from "vitest";
import { copyText } from "./copy-text";
function copyDocument(execCommand: (command: string) => boolean) {
return {
body: document.body,
createElement: document.createElement.bind(document),
execCommand,
};
}
describe("copyText", () => {
it("falls back to a selected textarea without Clipboard API", async () => {
const execCommand = vi.fn(() => true);
const copied = await copyText("trace", {
document: copyDocument(execCommand),
});
expect(copied).toBe(true);
expect(execCommand).toHaveBeenCalledWith("copy");
expect(document.querySelector("textarea")).toBeNull();
});
it("falls back after Clipboard API rejects", async () => {
const clipboard = {
writeText: vi.fn(async () => {
throw new Error("not allowed");
}),
};
const execCommand = vi.fn(() => true);
await expect(copyText("trace", {
clipboard,
document: copyDocument(execCommand),
})).resolves.toBe(true);
expect(clipboard.writeText).toHaveBeenCalledWith("trace");
expect(execCommand).toHaveBeenCalledWith("copy");
});
it("reports failure and removes its textarea when both paths fail", async () => {
const execCommand = vi.fn(() => false);
await expect(copyText("trace", {
document: copyDocument(execCommand),
})).resolves.toBe(false);
expect(document.querySelector("textarea")).toBeNull();
});
});