Open History to see the last commit
1import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
2import { ClientEventBus } from '../src/client/client'
3β
4// Stub BroadcastChannel since it's not available in test environment
5vi.stubGlobal(
6 'BroadcastChannel',
7 class {
8 postMessage = vi.fn()
9 addEventListener = vi.fn()
10 removeEventListener = vi.fn()
11 close = vi.fn()
12 onmessage: any = null
13 },
14)
15β
16// Track WebSocket and EventSource constructor calls
17const mockWebSocketInstances: Array<any> = []
18const mockEventSourceInstances: Array<any> = []
19β
20function createMockWebSocketClass() {
21 const cls = class MockWebSocket {
22 static OPEN = 1
23 static CLOSED = 3
24 url: string
25 readyState = 1
26 onmessage: any = null
27 onclose: any = null
28 onerror: any = null
29 send = vi.fn()
30 close = vi.fn()
31 constructor(url: string) {
32 this.url = url
33 mockWebSocketInstances.push(this)
34 }
35 }
36 return cls
37}
38β
39function createMockEventSourceClass() {
40 return class MockEventSource {
41 url: string
42 onmessage: any = null
43 close = vi.fn()
44 constructor(url: string) {
45 this.url = url
46 mockEventSourceInstances.push(this)
47 }
48 }
49}
50β
51function createConnectingWebSocketClass() {
52 // Starts in CONNECTING state; tests flip readyState and fire onopen manually.
53 return class ConnectingWebSocket {
54 static CONNECTING = 0
55 static OPEN = 1
56 static CLOSED = 3
57 url: string
58 readyState = 0 // CONNECTING
59 onopen: any = null
60 onmessage: any = null
61 onclose: any = null
62 onerror: any = null
63 send = vi.fn()
64 close = vi.fn()
65 constructor(url: string) {
66 this.url = url
67 mockWebSocketInstances.push(this)
68 }
69 }
70}
71β
72function createThrowingWebSocketClass() {
73 return class ThrowingWebSocket {
74 static OPEN = 1
75 static CLOSED = 3
76 constructor() {
77 throw new Error('WS not available')
78 }
79 }
80}
81β
82describe('ClientEventBus', () => {
83 beforeEach(() => {
84 mockWebSocketInstances.length = 0
85 mockEventSourceInstances.length = 0
86 vi.stubGlobal('WebSocket', createMockWebSocketClass())
87 vi.stubGlobal('EventSource', createMockEventSourceClass())
88 vi.stubGlobal('fetch', vi.fn().mockResolvedValue({}))
89 })
90β
91 afterEach(() => {
92 vi.restoreAllMocks()
93 })
94β
95 describe('constructor defaults', () => {
96 it('should initialize with default values', () => {
97 const bus = new ClientEventBus()
98 bus.start()
99 // Default does not connect to server bus, so no WS/SSE created
100 expect(mockWebSocketInstances.length).toBe(0)
101 expect(mockEventSourceInstances.length).toBe(0)
102 bus.stop()
103 })
104 })
105β
106 describe('connectWebSocket with protocol', () => {
107 it('should use ws:// when protocol is http (default)', () => {
108 const bus = new ClientEventBus({
109 connectToServerBus: true,
110 port: 4206,
111 host: 'localhost',
112 protocol: 'http',
113 })
114 bus.start()
115β
116 expect(mockWebSocketInstances.length).toBe(1)
117 expect(mockWebSocketInstances[0].url).toBe(
118 'ws://localhost:4206/__devtools/ws',
119 )
120 bus.stop()
121 })
122β
123 it('should use wss:// when protocol is https', () => {
124 const bus = new ClientEventBus({
125 connectToServerBus: true,
126 port: 4206,
127 host: 'localhost',
128 protocol: 'https',
129 })
130 bus.start()
131β
132 expect(mockWebSocketInstances.length).toBe(1)
133 expect(mockWebSocketInstances[0].url).toBe(
134 'wss://localhost:4206/__devtools/ws',
135 )
136 bus.stop()
137 })
138β
139 it('should use custom host in WebSocket URL', () => {
140 const bus = new ClientEventBus({
141 connectToServerBus: true,
142 port: 9999,
143 host: 'myhost.local',
144 protocol: 'http',
145 })
146 bus.start()
147β
148 expect(mockWebSocketInstances[0].url).toBe(
149 'ws://myhost.local:9999/__devtools/ws',
150 )
151 bus.stop()
152 })
153β
154 it('should use custom host and https in WebSocket URL', () => {
155 const bus = new ClientEventBus({
156 connectToServerBus: true,
157 port: 443,
158 host: 'secure.example.com',
159 protocol: 'https',
160 })
161 bus.start()
162β
163 expect(mockWebSocketInstances[0].url).toBe(
164 'wss://secure.example.com:443/__devtools/ws',
165 )
166 bus.stop()
167 })
168 })
169β
170 describe('connectSSE with protocol', () => {
171 it('should use http:// when protocol is http', () => {
172 // Make WebSocket constructor throw to force SSE fallback
173 vi.stubGlobal('WebSocket', createThrowingWebSocketClass())
174β
175 const bus = new ClientEventBus({
176 connectToServerBus: true,
177 port: 4206,
178 host: 'localhost',
179 protocol: 'http',
180 })
181 bus.start()
182β
183 expect(mockEventSourceInstances.length).toBe(1)
184 expect(mockEventSourceInstances[0].url).toBe(
185 'http://localhost:4206/__devtools/sse',
186 )
187 bus.stop()
188 })
189β
190 it('should use https:// when protocol is https', () => {
191 vi.stubGlobal('WebSocket', createThrowingWebSocketClass())
192β
193 const bus = new ClientEventBus({
194 connectToServerBus: true,
195 port: 4206,
196 host: 'localhost',
197 protocol: 'https',
198 })
199 bus.start()
200β
201 expect(mockEventSourceInstances.length).toBe(1)
202 expect(mockEventSourceInstances[0].url).toBe(
203 'https://localhost:4206/__devtools/sse',
204 )
205 bus.stop()
206 })
207β
208 it('should use custom host in SSE URL', () => {
209 vi.stubGlobal('WebSocket', createThrowingWebSocketClass())
210β
211 const bus = new ClientEventBus({
212 connectToServerBus: true,
213 port: 8080,
214 host: 'dev.example.com',
215 protocol: 'https',
216 })
217 bus.start()
218β
219 expect(mockEventSourceInstances[0].url).toBe(
220 'https://dev.example.com:8080/__devtools/sse',
221 )
222 bus.stop()
223 })
224 })
225β
226 describe('emitToServer with protocol and host', () => {
227 it('should use correct protocol and host in fetch URL when using SSE fallback', () => {
228 // Make WebSocket constructor throw to force SSE fallback
229 vi.stubGlobal('WebSocket', createThrowingWebSocketClass())
230β
231 const bus = new ClientEventBus({
232 connectToServerBus: true,
233 port: 9999,
234 host: 'myhost',
235 protocol: 'https',
236 })
237 bus.start()
238β
239 // Dispatch an event to trigger emitToServer
240 window.dispatchEvent(
241 new CustomEvent('tanstack-dispatch-event', {
242 detail: {
243 type: 'test-event',
244 payload: { foo: 'bar' },
245 },
246 }),
247 )
248β
249 expect(fetch).toHaveBeenCalledWith(
250 'https://myhost:9999/__devtools/send',
251 expect.objectContaining({
252 method: 'POST',
253 headers: { 'Content-Type': 'application/json' },
254 }),
255 )
256 bus.stop()
257 })
258β
259 it('should use http://localhost by default in fetch URL', () => {
260 vi.stubGlobal('WebSocket', createThrowingWebSocketClass())
261β
262 const bus = new ClientEventBus({
263 connectToServerBus: true,
264 })
265 bus.start()
266β
267 window.dispatchEvent(
268 new CustomEvent('tanstack-dispatch-event', {
269 detail: {
270 type: 'test-event',
271 payload: {},
272 },
273 }),
274 )
275β
276 expect(fetch).toHaveBeenCalledWith(
277 'http://localhost:4206/__devtools/send',
278 expect.objectContaining({
279 method: 'POST',
280 }),
281 )
282 bus.stop()
283 })
284 })
285β
286 describe('emitToServer while WebSocket is connecting', () => {
287 it('should queue events while connecting and flush them once the socket opens', () => {
288 vi.stubGlobal('WebSocket', createConnectingWebSocketClass())
289β
290 const bus = new ClientEventBus({ connectToServerBus: true })
291 bus.start()
292β
293 const socket = mockWebSocketInstances[0]
294 expect(socket.readyState).toBe(0) // CONNECTING
295β
296 // Events emitted while connecting must not be sent yet...
297 window.dispatchEvent(
298 new CustomEvent('tanstack-dispatch-event', {
299 detail: { type: 'queued:event', payload: { n: 1 } },
300 }),
301 )
302 window.dispatchEvent(
303 new CustomEvent('tanstack-dispatch-event', {
304 detail: { type: 'queued:event', payload: { n: 2 } },
305 }),
306 )
307 expect(socket.send).not.toHaveBeenCalled()
308β
309 // ...but flushed in order as soon as the connection opens.
310 socket.readyState = 1 // OPEN
311 socket.onopen?.()
312β
313 expect(socket.send).toHaveBeenCalledTimes(2)
314 expect(socket.send.mock.calls[0][0]).toContain('"n":1')
315 expect(socket.send.mock.calls[1][0]).toContain('"n":2')
316 bus.stop()
317 })
318β
319 it('should send immediately once the socket is open', () => {
320 vi.stubGlobal('WebSocket', createConnectingWebSocketClass())
321β
322 const bus = new ClientEventBus({ connectToServerBus: true })
323 bus.start()
324β
325 const socket = mockWebSocketInstances[0]
326 socket.readyState = 1 // OPEN
327 socket.onopen?.()
328β
329 window.dispatchEvent(
330 new CustomEvent('tanstack-dispatch-event', {
331 detail: { type: 'live:event', payload: {} },
332 }),
333 )
334β
335 expect(socket.send).toHaveBeenCalledTimes(1)
336 bus.stop()
337 })
338β
339 it('should drop queued events if the socket closes before opening', () => {
340 vi.stubGlobal('WebSocket', createConnectingWebSocketClass())
341β
342 const bus = new ClientEventBus({ connectToServerBus: true })
343 bus.start()
344β
345 const socket = mockWebSocketInstances[0]
346 window.dispatchEvent(
347 new CustomEvent('tanstack-dispatch-event', {
348 detail: { type: 'queued:event', payload: {} },
349 }),
350 )
351β
352 // Connection fails before ever opening.
353 socket.readyState = 3 // CLOSED
354 socket.onclose?.()
355β
356 // Re-flushing (e.g. a late open) must not send the dropped events.
357 socket.onopen?.()
358 expect(socket.send).not.toHaveBeenCalled()
359 bus.stop()
360 })
361 })
362β
363 describe('event dispatching', () => {
364 it('should emit events to a subscribed listener', () => {
365 const bus = new ClientEventBus()
366 bus.start()
367 const handler = vi.fn()
368 window.addEventListener('test:event', handler)
369β
370 window.dispatchEvent(
371 new CustomEvent('tanstack-dispatch-event', {
372 detail: {
373 type: 'test:event',
374 payload: { foo: 'bar' },
375 },
376 }),
377 )
378 expect(handler).toHaveBeenCalled()
379 window.removeEventListener('test:event', handler)
380 bus.stop()
381 })
382β
383 it('should emit events to global listeners', () => {
384 const bus = new ClientEventBus()
385 bus.start()
386 const handler = vi.fn()
387 window.addEventListener('tanstack-devtools-global', handler)
388β
389 window.dispatchEvent(
390 new CustomEvent('tanstack-dispatch-event', {
391 detail: {
392 type: 'test:event',
393 payload: { foo: 'bar' },
394 },
395 }),
396 )
397 expect(handler).toHaveBeenCalled()
398 window.removeEventListener('tanstack-devtools-global', handler)
399 bus.stop()
400 })
401 })
402β
403 describe('debug logging', () => {
404 it('should log when debug is enabled', () => {
405 const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {})
406 const bus = new ClientEventBus({ debug: true })
407 bus.start()
408β
409 expect(logSpy).toHaveBeenCalledWith(
410 'π΄ [tanstack-devtools:client-bus]',
411 'Initializing client event bus',
412 )
413 bus.stop()
414 })
415β
416 it('should not log when debug is disabled', () => {
417 const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {})
418 const bus = new ClientEventBus({ debug: false })
419 bus.start()
420β
421 expect(logSpy).not.toHaveBeenCalled()
422 bus.stop()
423 })
424 })
425β
426 describe('stop()', () => {
427 it('should clean up event listeners on stop', () => {
428 const bus = new ClientEventBus()
429 bus.start()
430β
431 const handler = vi.fn()
432 window.addEventListener('test:cleanup', handler)
433β
434 bus.stop()
435β
436 // After stop, dispatching should not trigger the bus dispatcher
437 // (but the direct listener on window still works)
438 window.removeEventListener('test:cleanup', handler)
439 })
440β
441 it('should close WebSocket on stop', () => {
442 const bus = new ClientEventBus({ connectToServerBus: true })
443 bus.start()
444β
445 expect(mockWebSocketInstances.length).toBe(1)
446 bus.stop()
447β
448 expect(mockWebSocketInstances[0].close).toHaveBeenCalled()
449 })
450β
451 it('should close EventSource on stop', () => {
452 vi.stubGlobal('WebSocket', createThrowingWebSocketClass())
453β
454 const bus = new ClientEventBus({ connectToServerBus: true })
455 bus.start()
456β
457 expect(mockEventSourceInstances.length).toBe(1)
458 bus.stop()
459β
460 expect(mockEventSourceInstances[0].close).toHaveBeenCalled()
461 })
462 })
463})