-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathconnect-url.test.ts
More file actions
418 lines (352 loc) Β· 16.8 KB
/
Copy pathconnect-url.test.ts
File metadata and controls
418 lines (352 loc) Β· 16.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
import { beforeEach, expect, it, vi } from 'vitest';
import { connect, resetRegistry, Server } from './mock-server';
import { receive } from './test-events';
// These tests exercise `connect(url)` and its origin registry, a smocket-only
// mechanism: real socket.io resolves a url through an actual network, so there is
// no dual-run counterpart to compare against (like the adapter, see
// docs/differences.md Β§B). They import the Server directly and always run the same
// under both `pnpm test` targets. The registry is a module-level singleton, so it
// is cleared before each test to keep lookups isolated.
beforeEach(() => resetRegistry());
it('connect(url) resolves to the server registered for that origin', async () => {
const server = new Server('http://localhost');
const client = connect('http://localhost');
const serverSocket = await server.nextConnection();
expect(client.connected).toBe(true);
expect(client.disconnected).toBe(false);
expect(client.recovered).toBe(false);
expect(serverSocket.id).toBe(client.id);
});
it('a missing-server socket exposes disconnected state and mutable auth', async () => {
const auth = { token: 'first' };
const client = connect('http://missing.example', { auth });
const connectError = receive(client, 'connect_error');
expect(client.connected).toBe(false);
expect(client.disconnected).toBe(true);
expect(client.recovered).toBe(false);
expect(client.auth).toBe(auth);
const replacement = (cb: (data: object) => void): void => cb({ token: 'second' });
client.auth = replacement;
expect(client.auth).toBe(replacement);
await expect(connectError).resolves.toBeInstanceOf(Error);
});
it('handshake.url is the normalized origin the client connected to', async () => {
// The one mock-only handshake field: real socket.io fills `url` with the request
// path, smocket with the normalized origin it holds as the registry key (0006), so
// the exact value is pinned here rather than in the dual-run handshake test.
const server = new Server('http://localhost');
server.of('/game');
connect('http://localhost/game');
const serverSocket = await server.nextConnection('/game');
expect(serverSocket.handshake.url).toBe('http://localhost:80');
});
it('two spellings of one origin resolve to the same server', async () => {
// A missing port is filled from the scheme (http -> 80), so the bare host and
// the same host with its default port are one key (0003).
const server = new Server('http://localhost');
const client = connect('http://localhost:80');
const serverSocket = await server.nextConnection();
expect(serverSocket.id).toBe(client.id);
});
it('a bare https origin resolves to the same server as its default port', async () => {
const server = new Server('https://localhost');
const client = connect('https://localhost:443');
const serverSocket = await server.nextConnection();
expect(serverSocket.id).toBe(client.id);
expect(serverSocket.handshake.url).toBe('https://localhost:443');
});
it('connect(url) caches one Manager per normalized origin unless opted out', async () => {
const server = new Server('http://localhost');
server.of('/game');
server.of('/forced');
server.of('/solo');
const root = connect('http://localhost');
const game = connect('http://localhost:80/game');
const duplicate = connect('http://localhost/game');
const forced = connect('http://localhost/forced', { forceNew: true });
const unmultiplexed = connect('http://localhost/solo', { multiplex: false });
await Promise.all([
server.nextConnection(),
server.nextConnection('/game'),
server.nextConnection('/game'),
server.nextConnection('/forced'),
server.nextConnection('/solo'),
]);
expect(root.io).toBe(game.io);
expect(duplicate.io).not.toBe(root.io);
expect(forced.io).not.toBe(root.io);
expect(unmultiplexed.io).not.toBe(root.io);
expect(forced.io).not.toBe(unmultiplexed.io);
});
it("the url's query string lands on handshake.query", async () => {
// The url is one of the two sources for `handshake.query`. Reading it off `connect(url)`
// is mock-only for the same reason as the rest of this file: the mock setup routes
// through `connect(url)`, whereas real socket.io's url query rides its own network
// stack. Values arrive as strings, matching how a real querystring is decoded.
const server = new Server('http://localhost');
connect('http://localhost/?room=lobby&max=4');
const serverSocket = await server.nextConnection();
expect(serverSocket.handshake.query.room).toBe('lobby');
expect(serverSocket.handshake.query.max).toBe('4');
});
it('connect(url, { auth }) puts the auth object on the handshake', async () => {
const server = new Server('http://localhost');
connect('http://localhost', { auth: { token: 't' } });
const serverSocket = await server.nextConnection();
expect(serverSocket.handshake.auth).toEqual({ token: 't' });
});
it('a function auth holds the pairing until its callback fires', async () => {
// The callback form is resolved before the pairing completes, so a connection whose
// auth callback has not fired yet has no server socket. This proves the hold by
// ordering, not a timeout: the pairing is observed absent, then present once the
// callback runs. Real socket.io likewise holds the connect until the callback fires.
const server = new Server('http://localhost');
let fire!: () => void;
connect('http://localhost', { auth: (cb) => (fire = () => cb({ token: 'late' })) });
let paired = false;
const pending = server.nextConnection().then((socket) => ((paired = true), socket));
// Flush the microtask queue; with the callback still unfired, nothing can pair.
await Promise.resolve();
expect(paired).toBe(false);
fire();
const serverSocket = await pending;
expect(serverSocket.handshake.auth).toEqual({ token: 'late' });
});
it('a function auth is re-evaluated on each connection, including a reconnect', async () => {
// Measured against the real client: the auth function runs once per connection, so a
// reconnect calls it again and can hand over a fresh value (a rotated token).
const server = new Server('http://localhost');
let calls = 0;
const client = connect('http://localhost', { auth: (cb) => cb({ n: (calls += 1) }) });
await server.nextConnection();
const reconnected = server.nextConnection();
client.disconnect();
client.connect();
const serverSocket = await reconnected;
expect(calls).toBe(2);
expect(serverSocket.handshake.auth).toEqual({ n: 2 });
});
it('a completed reconnect resets client.recovered to false', async () => {
const server = new Server('http://localhost');
const client = connect('http://localhost');
const first = await server.nextConnection();
client.recovered = true;
const disconnected = new Promise<void>((resolve) => first.once('disconnect', () => resolve()));
client.disconnect();
await disconnected;
const reconnected = server.nextConnection();
client.connect();
await reconnected;
expect(client.recovered).toBe(false);
});
it('the url query wins wholesale over the options query when both are given', async () => {
// Measured against socket.io-client 4.x: a url carrying a query uses that query and
// ignores opts.query entirely, so even an opts-only key is dropped. smocket matches,
// so connect(url, opts) yields the same handshake the real client would.
const server = new Server('http://localhost');
connect('http://localhost/?room=fromurl', { query: { room: 'fromopts', only: 'opt' } });
const serverSocket = await server.nextConnection();
expect(serverSocket.handshake.query.room).toBe('fromurl');
expect(serverSocket.handshake.query.only).toBeUndefined();
});
it('the options query is used only when the url carries none', async () => {
const server = new Server('http://localhost');
connect('http://localhost', { query: { room: 'fromopts' } });
const serverSocket = await server.nextConnection();
expect(serverSocket.handshake.query.room).toBe('fromopts');
});
it("the url's path selects the namespace", async () => {
const server = new Server('http://localhost');
server.of('game');
const client = connect('http://localhost/game');
const serverSocket = await server.nextConnection('/game');
expect(serverSocket.nsp.name).toBe('/game');
expect(serverSocket.id).toBe(client.id);
});
it('connect(url) rejects an unregistered namespace without creating membership', async () => {
const server = new Server('http://localhost');
const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
try {
const client = connect('http://localhost/private');
const outcome = await Promise.race([
receive(client, 'connect').then(() => 'connect' as const),
receive(client, 'connect_error'),
]);
expect(outcome).toBeInstanceOf(Error);
expect((outcome as Error).message).toBe('Invalid namespace');
expect(client.connected).toBe(false);
expect(client.id).toBeUndefined();
// Unlike the intentional missing-origin divergence (0005), Socket.IO itself
// supplies this application-level error, so smocket adds no console diagnostic.
expect(consoleError).not.toHaveBeenCalled();
const namespace = server.of('/private');
const adapter = namespace.adapter;
const sids = (adapter as typeof adapter & { sids: Map<string, Set<string>> }).sids;
expect(adapter.rooms.size).toBe(0);
expect(sids.size).toBe(0);
} finally {
consoleError.mockRestore();
}
});
it('a relative url resolves against location.origin', async () => {
// Node has no `location`, so the origin is stubbed there. A browser has a real one
// that cannot be redefined (#105), so the browser run reads it and resolves against
// the page it is actually served from, which is the case this rule exists for.
const pageOrigin = (globalThis as { location?: { origin: string } }).location?.origin;
const origin = pageOrigin ?? 'http://localhost:3000';
if (pageOrigin === undefined) vi.stubGlobal('location', { origin });
try {
const server = new Server(origin);
const client = connect('/');
const serverSocket = await server.nextConnection();
expect(serverSocket.id).toBe(client.id);
} finally {
vi.unstubAllGlobals();
}
});
it('connect(url) to an unregistered origin fires connect_error, without throwing', async () => {
const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
try {
const client = connect('http://localhost:9999');
const error = new Promise<Error>((resolve) => {
client.on('connect_error', (err: Error) => resolve(err));
});
expect(client.connected).toBe(false);
await expect(error).resolves.toBeInstanceOf(Error);
expect(client.connect()).toBe(client);
expect(client.disconnect()).toBe(client);
// A parallel console.error alongside the event, so a mistyped url is not
// silent for the common case of no connect_error handler (0005).
expect(consoleError).toHaveBeenCalledOnce();
} finally {
consoleError.mockRestore();
}
});
it('a failed client still rejects reserved names on every emit wrapper', async () => {
const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
try {
const client = connect('http://localhost:9997');
const failed = new Promise<void>((resolve) => client.once('connect_error', () => resolve()));
const reserved = new Error('"disconnect" is a reserved event name');
expect(() => client.emit('disconnect')).toThrowError(reserved);
expect(() => client.timeout(20).emit('disconnect')).toThrowError(reserved);
expect(() => client.volatile.emit('disconnect')).toThrowError(reserved);
await expect(client.emitWithAck('disconnect')).rejects.toThrowError(reserved);
await expect(client.timeout(20).emitWithAck('disconnect')).rejects.toThrowError(reserved);
await expect(client.volatile.emitWithAck('disconnect')).rejects.toThrowError(reserved);
await failed;
expect(consoleError).toHaveBeenCalledOnce();
} finally {
consoleError.mockRestore();
}
});
it('close unregisters the server so later connect(url) reports a missing server', async () => {
const server = new Server('http://localhost');
const closing = server.close();
expect(closing).toBeInstanceOf(Promise);
await closing;
const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
try {
const client = connect('http://localhost');
const error = new Promise<Error>((resolve) => client.once('connect_error', resolve));
await expect(error).resolves.toMatchObject({
message: expect.stringContaining('no server registered'),
});
expect(consoleError).toHaveBeenCalledOnce();
} finally {
consoleError.mockRestore();
}
});
it('closing a replaced server does not unregister its replacement', async () => {
const oldServer = new Server('http://localhost');
const replacement = new Server('http://localhost');
await oldServer.close();
const pending = replacement.nextConnection();
const client = connect('http://localhost');
const serverSocket = await pending;
expect(client.id).toBe(serverSocket.id);
});
it('the socket from a failed connect still chains', async () => {
// The socket a failed connect hands back is inert (0005), but it is still a client
// socket, and the client emitters chain. App code that wrote `socket.emit(a).emit(b)`
// should not start throwing because no server was registered for the origin.
const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
try {
const client = connect('http://localhost:9998');
// The failure report is deferred to the next tick (0005), and every assertion below is
// synchronous, so without awaiting it the spy would be restored first and the
// `console.error` would land outside it. Awaited here, so the mock covers the whole
// failure and the report is asserted rather than merely tolerated.
const failed = new Promise<void>((resolve) => {
client.once('connect_error', () => resolve());
});
expect(client.emit('a', 1)).toBe(client);
expect(client.send('message')).toBe(client);
expect(client.compress(false)).toBe(client);
expect(client.open()).toBe(client);
expect(client.close()).toBe(client);
const timed = client.timeout(50);
expect(timed).toBe(client);
expect(timed.emit('a', 1)).toBe(client);
const volatile = client.volatile;
expect(volatile).toBe(client);
expect(volatile.emit('a', 1)).toBe(client);
await failed;
expect(consoleError).toHaveBeenCalledOnce();
} finally {
consoleError.mockRestore();
}
});
it('a failed client carries the complete catch-all listener surface', async () => {
const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
try {
const client = connect('http://localhost:9996');
const incoming = () => {};
const outgoing = () => {};
const failed = new Promise<void>((resolve) => client.once('connect_error', () => resolve()));
const emptyIncoming = client.listenersAny();
const emptyOutgoing = client.listenersAnyOutgoing();
expect(client.listenersAny()).not.toBe(emptyIncoming);
expect(client.listenersAnyOutgoing()).not.toBe(emptyOutgoing);
expect(client.prependAny(incoming)).toBe(client);
expect(client.prependAnyOutgoing(outgoing)).toBe(client);
expect(client.listenersAny()).toEqual([incoming]);
expect(client.listenersAnyOutgoing()).toEqual([outgoing]);
const oldIncoming = client.listenersAny();
const oldOutgoing = client.listenersAnyOutgoing();
expect(client.offAny()).toBe(client);
expect(client.offAnyOutgoing()).toBe(client);
expect(client.listenersAny()).not.toBe(oldIncoming);
expect(client.listenersAnyOutgoing()).not.toBe(oldOutgoing);
await failed;
expect(consoleError).toHaveBeenCalledOnce();
} finally {
consoleError.mockRestore();
}
});
it('a failed client carries component-emitter listener introspection', async () => {
const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
try {
const client = connect('http://localhost:9995');
const listener = () => {};
const failed = new Promise<void>((resolve) => client.once('connect_error', () => resolve()));
expect(client.listeners('missing')).not.toBe(client.listeners('missing'));
expect(client.hasListeners('missing')).toBe(false);
expect('listenerCount' in client).toBe(false);
expect('eventNames' in client).toBe(false);
client.once('custom', listener);
const live = client.listeners('custom');
const wrapper = live[0] as typeof listener & { fn?: typeof listener };
expect(client.listeners('custom')).toBe(live);
expect(wrapper.fn).toBe(listener);
expect(client.hasListeners('custom')).toBe(true);
client.off('custom', listener);
expect(live).toEqual([]);
expect(client.listeners('custom')).not.toBe(live);
expect(client.hasListeners('custom')).toBe(false);
await failed;
expect(consoleError).toHaveBeenCalledOnce();
} finally {
consoleError.mockRestore();
}
});