-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathtest-events.ts
More file actions
74 lines (69 loc) 路 2.48 KB
/
Copy pathtest-events.ts
File metadata and controls
74 lines (69 loc) 路 2.48 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
import { expect } from 'vitest';
import type { ClientSocketContract, NamespaceContract, ServerSocketContract } from './contract';
/** Assert that a namespace adapter retains no room or sid membership. */
export function expectNoResidualMembership(namespace: NamespaceContract): void {
const sids = (
namespace.adapter as typeof namespace.adapter & {
sids: Map<string, Set<string>>;
}
).sids;
expect(namespace.adapter.rooms.size).toBe(0);
expect(sids.size).toBe(0);
}
/** Resolve with the first payload the client receives for `event`. */
export function receive(client: ClientSocketContract, event: string): Promise<unknown> {
return new Promise((resolve) => {
client.once(event, (payload) => resolve(payload));
});
}
/**
* Track whether `event` ever arrives. To prove a client did NOT receive a
* message, emit it a direct `marker` afterwards: socket.io preserves per-socket
* order, so once the marker lands, any message that was coming would already
* have arrived.
*/
export function track(
socket: ClientSocketContract | ServerSocketContract,
event: string,
): { received: boolean } {
const state = { received: false };
socket.on(event, () => {
state.received = true;
});
return state;
}
/**
* Watch a socket's teardown from the server side. `client.disconnect()` returns
* long before the server has processed anything: reading the roster on the next
* line still shows the socket in all of its rooms. Awaiting `disconnected` is
* what makes the cleanup observable, and skipping it gives a test that passes
* locally and races elsewhere.
*
* Both promises resolve with a copy of `socket.rooms` taken at that moment,
* because the live Set is emptied in place between the two events. Call this
* before disconnecting, so the listeners are attached in time.
*/
export function observeDisconnect(socket: ServerSocketContract): {
disconnecting: Promise<Set<string>>;
disconnected: Promise<Set<string>>;
} {
return {
disconnecting: new Promise((resolve) =>
socket.once('disconnecting', () => resolve(new Set(socket.rooms))),
),
disconnected: new Promise((resolve) =>
socket.once('disconnect', () => resolve(new Set(socket.rooms))),
),
};
}
/** Count how many times `event` arrives at a socket (for dedup checks). */
export function count(
socket: ClientSocketContract | ServerSocketContract,
event: string,
): { count: number } {
const state = { count: 0 };
socket.on(event, () => {
state.count += 1;
});
return state;
}