summaryrefslogtreecommitdiffstats
path: root/test/websocket/diagnostics-channel.js
blob: c3bf05a51055a2e9290aa657ad8581721603ddb4 (plain)
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
'use strict'

const t = require('tap')
const dc = require('diagnostics_channel')
const { WebSocketServer } = require('ws')
const { WebSocket } = require('../..')

t.test('diagnostics channel', { jobs: 1 }, (t) => {
  t.plan(2)

  t.test('undici:websocket:open', (t) => {
    t.plan(3)

    const server = new WebSocketServer({ port: 0 })

    server.on('connection', (ws) => {
      ws.close(1000, 'goodbye')
    })

    const listener = ({ extensions, protocol }) => {
      t.equal(extensions, null)
      t.equal(protocol, 'chat')
    }

    t.teardown(() => {
      dc.channel('undici:websocket:open').unsubscribe(listener)
      return server.close()
    })

    const { port } = server.address()

    dc.channel('undici:websocket:open').subscribe(listener)

    const ws = new WebSocket(`ws://localhost:${port}`, 'chat')

    ws.addEventListener('open', () => {
      t.pass('Emitted open')
    })
  })

  t.test('undici:websocket:close', (t) => {
    t.plan(4)

    const server = new WebSocketServer({ port: 0 })

    server.on('connection', (ws) => {
      ws.close(1000, 'goodbye')
    })

    const listener = ({ websocket, code, reason }) => {
      t.type(websocket, WebSocket)
      t.equal(code, 1000)
      t.equal(reason, 'goodbye')
    }

    t.teardown(() => {
      dc.channel('undici:websocket:close').unsubscribe(listener)
      return server.close()
    })

    const { port } = server.address()

    dc.channel('undici:websocket:close').subscribe(listener)

    const ws = new WebSocket(`ws://localhost:${port}`, 'chat')

    ws.addEventListener('close', () => {
      t.pass('Emitted open')
    })
  })
})