MCPcopy
hub / github.com/coder/mux / MockWebSocket

Class MockWebSocket

src/browser/contexts/API.test.tsx:7–53  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

5
6// Mock WebSocket that we can control
7class MockWebSocket {
8 static instances: MockWebSocket[] = [];
9 url: string;
10 readyState = 0; // CONNECTING
11 eventListeners = new Map<string, Array<(event?: unknown) => void>>();
12
13 constructor(url: string) {
14 this.url = url;
15 MockWebSocket.instances.push(this);
16 }
17
18 addEventListener(event: string, handler: (event?: unknown) => void) {
19 const handlers = this.eventListeners.get(event) ?? [];
20 handlers.push(handler);
21 this.eventListeners.set(event, handlers);
22 }
23
24 close() {
25 this.readyState = 3; // CLOSED
26 }
27
28 // Test helpers
29 simulateOpen() {
30 this.readyState = 1; // OPEN
31 this.eventListeners.get("open")?.forEach((h) => h());
32 }
33
34 simulateClose(code: number) {
35 this.readyState = 3;
36 this.eventListeners.get("close")?.forEach((h) => h({ code }));
37 }
38
39 simulateError() {
40 this.eventListeners.get("error")?.forEach((h) => h());
41 }
42 simulateMessage(data: unknown = "data") {
43 this.eventListeners.get("message")?.forEach((h) => h({ data }));
44 }
45
46 static reset() {
47 MockWebSocket.instances = [];
48 }
49
50 static lastInstance(): MockWebSocket | undefined {
51 return MockWebSocket.instances[MockWebSocket.instances.length - 1];
52 }
53}
54
55function createOrpcPongResponseFrame(id: number): string {
56 return JSON.stringify({ i: id, p: { b: "pong" } });

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected