Skip to content
File

Blob: tests/setup/client.ts

typescript89 lines
1import { afterEach, vi } from "vitest";
2 
3export const fetchMock = vi.fn<typeof fetch>();
4export const confirmMock = vi.fn(() => true);
5export const clipboardWriteTextMock = vi.fn<(text: string) => Promise<void>>().mockResolvedValue(undefined);
6 
7type WebSocketReadyState = WebSocket["readyState"];
8 
9export class MockWebSocket extends EventTarget implements WebSocket {
10 static readonly CONNECTING: WebSocket["CONNECTING"] = 0;
11 static readonly OPEN: WebSocket["OPEN"] = 1;
12 static readonly CLOSING: WebSocket["CLOSING"] = 2;
13 static readonly CLOSED: WebSocket["CLOSED"] = 3;
14 
15 binaryType: BinaryType = "blob";
16 bufferedAmount = 0;
17 extensions = "";
18 onclose: ((this: WebSocket, event: CloseEvent) => unknown) | null = null;
19 onerror: ((this: WebSocket, event: Event) => unknown) | null = null;
20 onmessage: ((this: WebSocket, event: MessageEvent<unknown>) => unknown) | null = null;
21 onopen: ((this: WebSocket, event: Event) => unknown) | null = null;
22 protocol = "";
23 readonly url: string;
24 private currentReadyState: WebSocketReadyState = MockWebSocket.CONNECTING;
25 
26 readonly CONNECTING = MockWebSocket.CONNECTING;
27 readonly OPEN = MockWebSocket.OPEN;
28 readonly CLOSING = MockWebSocket.CLOSING;
29 readonly CLOSED = MockWebSocket.CLOSED;
30 
31 get readyState(): WebSocketReadyState {
32 return this.currentReadyState;
33 }
34 
35 send = vi.fn<(data: string | ArrayBufferLike | Blob | ArrayBufferView) => void>();
36 accept(_options?: WebSocketAcceptOptions) {}
37 serializeAttachment(_attachment: unknown) {}
38 deserializeAttachment() {
39 return null;
40 }
41 close = vi.fn<(code?: number, reason?: string) => void>(() => {
42 this.currentReadyState = MockWebSocket.CLOSED;
43 const event = new CloseEvent("close");
44 this.dispatchEvent(event);
45 this.onclose?.call(this, event);
46 });
47 
48 constructor(url: string | URL, _protocols?: string | string[]) {
49 super();
50 this.url = String(url);
51 }
52 
53 open() {
54 this.currentReadyState = MockWebSocket.OPEN;
55 const event = new Event("open");
56 this.dispatchEvent(event);
57 this.onopen?.call(this, event);
58 }
59 
60 receive(data: string) {
61 const event = new MessageEvent("message", { data });
62 this.dispatchEvent(event);
63 this.onmessage?.call(this, event);
64 }
65}
66 
67vi.stubGlobal("fetch", fetchMock);
68vi.stubGlobal("confirm", confirmMock);
69vi.stubGlobal("WebSocket", MockWebSocket);
70 
71Object.defineProperty(globalThis.navigator, "clipboard", {
72 configurable: true,
73 value: {
74 writeText: clipboardWriteTextMock,
75 },
76});
77 
78afterEach(() => {
79 fetchMock.mockReset();
80 confirmMock.mockReset();
81 confirmMock.mockReturnValue(true);
82 clipboardWriteTextMock.mockReset();
83 clipboardWriteTextMock.mockResolvedValue(undefined);
84 window.localStorage.clear();
85 window.sessionStorage.clear();
86 document.head.innerHTML = "";
87 document.body.innerHTML = "";
88});