Debian Codegraph @

test/websocket/diagnostics-channel-ping-pong.js

raw symbols SCIP
1 'use strict'
2
3 const { test } = require('node:test')
4 const dc = require('node:diagnostics_channel')
5 const { WebSocketServer } = require('ws')
6 const { WebSocket } = require('../..')
7 const { once } = require('node:events')
8
9 test('diagnostics channel - undici:websocket:[ping/pong]', async (t) => {
10 t.plan(4)
11
12 const server = new WebSocketServer({ port: 0 })
13 const { port } = server.address()
14 const pingChannel = dc.channel('undici:websocket:ping')
15 const pongChannel = dc.channel('undici:websocket:pong')
16
17 const pingListener = ({ websocket, payload }) => {
18 // Diagnostics channels are process-global, so ignore events from other
19 // WebSocket instances.
20 if (websocket !== ws) {
21 return
22 }
23
24 t.assert.strictEqual(websocket, ws)
25 t.assert.deepStrictEqual(payload, Buffer.from('Ping'))
26 }
27
28 const pongListener = ({ websocket, payload }) => {
29 // Diagnostics channels are process-global, so ignore events from other
30 // WebSocket instances.
31 if (websocket !== ws) {
32 return
33 }
34
35 t.assert.strictEqual(websocket, ws)
36 t.assert.deepStrictEqual(payload, Buffer.from('Pong'))
37 }
38
39 pingChannel.subscribe(pingListener)
40 pongChannel.subscribe(pongListener)
41
42 // The listeners and server handler must be in place before creating the
43 // WebSocket, because the constructor starts the connection immediately.
44 server.on('connection', (websocket) => {
45 websocket.ping('Ping')
46 websocket.pong('Pong')
47 websocket.close()
48 })
49
50 const ws = new WebSocket(`ws://localhost:${port}`, 'chat')
51
52 t.after(() => {
53 server.close()
54 pingChannel.unsubscribe(pingListener)
55 pongChannel.unsubscribe(pongListener)
56 })
57
58 await once(ws, 'close')
59 })