Skip to content
Source
Sign inSign up
TanStack/devtools
Open History to see the last commit

server.test.ts

251 lines8.3 KB

1import http from 'node:http'
2import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
3import { ServerEventBus } from '../src/server/server'
4​
5// Clear globalThis between tests to avoid cross-test contamination
6function clearGlobals() {
7 globalThis.__TANSTACK_DEVTOOLS_SERVER__ = null
8 globalThis.__TANSTACK_DEVTOOLS_WSS_SERVER__ = null
9 globalThis.__TANSTACK_EVENT_TARGET__ = null
11​
12describe('ServerEventBus', () => {
13 let bus: ServerEventBus
14 const originalNodeEnv = process.env.NODE_ENV
15​
16 beforeEach(() => {
17 clearGlobals()
18 process.env.NODE_ENV = 'development'
19 })
20​
21 afterEach(async () => {
22 bus?.stop()
23 clearGlobals()
24 process.env.NODE_ENV = originalNodeEnv
25 // Small delay to let servers fully close
26 await new Promise((resolve) => setTimeout(resolve, 50))
27 })
28​
29 describe('constructor', () => {
30 it('should initialize with default config', () => {
31 bus = new ServerEventBus()
32 expect(bus.port).toBe(4206)
33 })
34​
35 it('should accept custom port', () => {
36 bus = new ServerEventBus({ port: 9999 })
37 expect(bus.port).toBe(9999)
38 })
39​
40 it('should log when debug is enabled', () => {
41 const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {})
42 bus = new ServerEventBus({ debug: true })
43 expect(logSpy).toHaveBeenCalledWith(
44 '🌴 [tanstack-devtools:server-bus] ',
45 'Initializing server event bus',
46 )
47 logSpy.mockRestore()
48 })
49​
50 it('should not log when debug is disabled', () => {
51 const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {})
52 bus = new ServerEventBus({ debug: false })
53 expect(logSpy).not.toHaveBeenCalled()
54 logSpy.mockRestore()
55 })
56 })
57​
58 describe('start() - standalone mode', () => {
59 it('should start and resolve with a port', async () => {
60 bus = new ServerEventBus({ port: 0 }) // port 0 = OS-assigned
61 const port = await bus.start()
62 expect(port).toBeGreaterThan(0)
63 expect(bus.port).toBe(port)
64 })
65​
66 it('should create its own HTTP server in standalone mode', async () => {
67 bus = new ServerEventBus({ port: 0 })
68 await bus.start()
69 expect(globalThis.__TANSTACK_DEVTOOLS_SERVER__).not.toBeNull()
70 })
71​
72 it('should create a WebSocket server in standalone mode', async () => {
73 bus = new ServerEventBus({ port: 0 })
74 await bus.start()
75 expect(globalThis.__TANSTACK_DEVTOOLS_WSS_SERVER__).not.toBeNull()
76 })
77​
78 it('should resolve immediately in non-development environment', async () => {
79 process.env.NODE_ENV = 'production'
80 bus = new ServerEventBus({ port: 5555 })
81 const port = await bus.start()
82 expect(port).toBe(5555)
83 // No server should be created
84 expect(globalThis.__TANSTACK_DEVTOOLS_SERVER__).toBeNull()
85 })
86​
87 it('should resolve immediately if server is already running (HMR guard)', async () => {
88 bus = new ServerEventBus({ port: 0 })
89 await bus.start()
90 // Create a new bus that picks up globalThis servers
91 const bus2 = new ServerEventBus({ port: 0 })
92 const port2 = await bus2.start()
93 // Should resolve with the port without creating new server
94 expect(port2).toBeGreaterThanOrEqual(0)
95 })
96​
97 it('should handle EADDRINUSE by falling back to OS-assigned port', async () => {
98 // Occupy a port on localhost first
99 const blocker = http.createServer()
100 const blockerPort = await new Promise<number>((resolve) => {
101 blocker.listen(0, 'localhost', () => {
102 const addr = blocker.address()
103 if (typeof addr === 'object' && addr) resolve(addr.port)
104 })
105 })
106​
107 try {
108 // Ensure globals are clean so the bus creates a fresh server
109 clearGlobals()
110 bus = new ServerEventBus({ port: blockerPort, host: 'localhost' })
111 const port = await bus.start()
112 // Should get a different port since the preferred one was in use
113 expect(port).toBeGreaterThan(0)
114 // The port should be different from the blocked port since EADDRINUSE triggers fallback
115 expect(port).not.toBe(blockerPort)
116 } finally {
117 blocker.close()
118 }
119 })
120​
121 it('should pass host to server.listen', async () => {
122 bus = new ServerEventBus({ port: 0, host: '127.0.0.1' })
123 const port = await bus.start()
124 expect(port).toBeGreaterThan(0)
125 })
126 })
127​
128 describe('start() - external httpServer mode', () => {
129 let externalServer: http.Server
130​
131 beforeEach(async () => {
132 externalServer = http.createServer()
133 await new Promise<void>((resolve) => {
134 externalServer.listen(0, () => resolve())
135 })
136 })
137​
138 afterEach(() => {
139 externalServer.close()
140 })
141​
142 it('should not create a standalone server when httpServer is provided', async () => {
143 bus = new ServerEventBus({ httpServer: externalServer })
144 await bus.start()
145 // Should NOT have created its own server in globalThis
146 expect(globalThis.__TANSTACK_DEVTOOLS_SERVER__).toBeNull()
147 })
148​
149 it('should create a WebSocket server when httpServer is provided', async () => {
150 bus = new ServerEventBus({ httpServer: externalServer })
151 await bus.start()
152 expect(globalThis.__TANSTACK_DEVTOOLS_WSS_SERVER__).not.toBeNull()
153 })
154​
155 it('should resolve port from external server address', async () => {
156 bus = new ServerEventBus({ httpServer: externalServer })
157 const port = await bus.start()
158 const addr = externalServer.address()
159 const expectedPort = typeof addr === 'object' && addr ? addr.port : 0
160 expect(port).toBe(expectedPort)
161 })
162​
163 it('should handle SSE requests on external server', async () => {
164 bus = new ServerEventBus({ httpServer: externalServer })
165 const port = await bus.start()
166​
167 // Make an SSE request
168 const response = await new Promise<http.IncomingMessage>((resolve) => {
169 http.get(`http://localhost:${port}/__devtools/sse`, (res) => {
170 resolve(res)
171 })
172 })
173​
174 expect(response.statusCode).toBe(200)
175 expect(response.headers['content-type']).toBe('text/event-stream')
176 response.destroy()
177 })
178​
179 it('should handle POST requests on external server', async () => {
180 bus = new ServerEventBus({ httpServer: externalServer })
181 const port = await bus.start()
182​
183 const response = await new Promise<http.IncomingMessage>((resolve) => {
184 const req = http.request(
185 {
186 hostname: 'localhost',
187 port,
188 path: '/__devtools/send',
189 method: 'POST',
190 headers: { 'Content-Type': 'application/json' },
191 },
192 (res) => resolve(res),
193 )
194 req.write(
195 JSON.stringify({ type: 'test-event', payload: { foo: 'bar' } }),
196 )
197 req.end()
198 })
199​
200 expect(response.statusCode).toBe(200)
201 })
202​
203 it('should remove listeners from external server on stop() without closing it', async () => {
204 bus = new ServerEventBus({ httpServer: externalServer })
205 await bus.start()
206​
207 const listenerCountBefore = externalServer.listenerCount('request')
208 expect(listenerCountBefore).toBeGreaterThan(0)
209​
210 bus.stop()
211​
212 // Wait a tick for cleanup
213 await new Promise((resolve) => setTimeout(resolve, 50))
214​
215 // The external server should still be listening
216 const addr = externalServer.address()
217 expect(addr).not.toBeNull()
218​
219 // Our request listener should be removed
220 const listenerCountAfter = externalServer.listenerCount('request')
221 expect(listenerCountAfter).toBeLessThan(listenerCountBefore)
222 })
223 })
224​
225 describe('stop()', () => {
226 it('should close standalone server on stop', async () => {
227 bus = new ServerEventBus({ port: 0 })
228 await bus.start()
229 expect(globalThis.__TANSTACK_DEVTOOLS_SERVER__).not.toBeNull()
230​
231 bus.stop()
232 await new Promise((resolve) => setTimeout(resolve, 100))
233 })
234​
235 it('should clear all connections on stop', async () => {
236 bus = new ServerEventBus({ port: 0 })
237 await bus.start()
238​
239 const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {})
240 bus = new ServerEventBus({ port: 0, debug: true })
241 await bus.start()
242 bus.stop()
243​
244 expect(logSpy).toHaveBeenCalledWith(
245 '🌴 [tanstack-devtools:server-bus] ',
246 'Clearing all connections',
247 )
248 logSpy.mockRestore()
249 })
250 })
251})