websocket.ts 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. export class FakeWebSocket {
  2. static CONNECTING = 0
  3. static OPEN = 1
  4. static CLOSING = 2
  5. static CLOSED = 3
  6. readyState = FakeWebSocket.CONNECTING
  7. closed = false
  8. sent: string[] = []
  9. listeners = new Map<string, Set<(event: { data?: unknown }) => void>>()
  10. constructor(
  11. readonly url: string,
  12. readonly options?: { headers?: Record<string, string> },
  13. ) {}
  14. addEventListener(type: string, listener: (event: { data?: unknown }) => void) {
  15. const current = this.listeners.get(type) ?? new Set<(event: { data?: unknown }) => void>()
  16. current.add(listener)
  17. this.listeners.set(type, current)
  18. }
  19. send(data: string) {
  20. this.sent.push(data)
  21. }
  22. close() {
  23. if (this.readyState === FakeWebSocket.CLOSED) return
  24. this.closed = true
  25. this.readyState = FakeWebSocket.CLOSED
  26. this.emit("close", {})
  27. }
  28. open() {
  29. this.readyState = FakeWebSocket.OPEN
  30. this.emit("open", {})
  31. }
  32. message(data: unknown) {
  33. this.emit("message", { data })
  34. }
  35. emit(type: string, event: { data?: unknown }) {
  36. this.listeners.get(type)?.forEach((listener) => listener(event))
  37. }
  38. }