| 8 | type Listener = (ev: { data?: string | undefined; code?: number | undefined; reason?: string | undefined }) => void; |
| 9 | |
| 10 | export class MockWebSocket implements WsLike { |
| 11 | static OPEN = 1; |
| 12 | static CLOSED = 3; |
| 13 | |
| 14 | readyState: number = 0; |
| 15 | sent: string[] = []; |
| 16 | url: string; |
| 17 | private listeners: Record<EventType, Listener[]> = { |
| 18 | open: [], |
| 19 | close: [], |
| 20 | error: [], |
| 21 | message: [], |
| 22 | }; |
| 23 | |
| 24 | constructor(url: string) { |
| 25 | this.url = url; |
| 26 | } |
| 27 | |
| 28 | addEventListener(type: EventType, fn: Listener): void { |
| 29 | this.listeners[type].push(fn); |
| 30 | } |
| 31 | |
| 32 | removeEventListener(type: EventType, fn: Listener): void { |
| 33 | this.listeners[type] = this.listeners[type].filter((l) => l !== fn); |
| 34 | } |
| 35 | |
| 36 | send(data: string): void { |
| 37 | this.sent.push(data); |
| 38 | } |
| 39 | |
| 40 | close(code?: number, reason?: string): void { |
| 41 | this.readyState = MockWebSocket.CLOSED; |
| 42 | const ev: { code?: number; reason?: string } = {}; |
| 43 | if (code !== undefined) ev.code = code; |
| 44 | if (reason !== undefined) ev.reason = reason; |
| 45 | this.dispatch('close', ev); |
| 46 | } |
| 47 | |
| 48 | // Test helpers. |
| 49 | acceptOpen(): void { |
| 50 | this.readyState = MockWebSocket.OPEN; |
| 51 | this.dispatch('open', {}); |
| 52 | } |
| 53 | acceptMessage(data: string): void { |
| 54 | this.dispatch('message', { data }); |
| 55 | } |
| 56 | acceptError(): void { |
| 57 | this.dispatch('error', {}); |
| 58 | } |
| 59 | acceptClose(code = 1000, reason = ''): void { |
| 60 | this.readyState = MockWebSocket.CLOSED; |
| 61 | this.dispatch('close', { code, reason }); |
| 62 | } |
| 63 | |
| 64 | private dispatch(type: EventType, ev: { data?: string | undefined; code?: number | undefined; reason?: string | undefined }): void { |
| 65 | for (const l of this.listeners[type].slice()) l(ev); |
| 66 | } |
| 67 | } |
nothing calls this directly
no outgoing calls
no test coverage detected