Passed
Branch master (5df6c0)
by Michael
02:01
created

test/specs/existing_socket.ts   A

Complexity

Total Complexity 8
Complexity/F 0

Size

Lines of Code 55
Function Count 0

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
wmc 8
eloc 44
mnd 8
bc 8
fnc 0
dl 0
loc 55
rs 10
bpm 0
cpm 0
noi 0
c 0
b 0
f 0
1
import { createNew } from '../utils'
2
import mockServer from '../mock/server'
3
4
import WS from 'ws'
5
import { test } from '../suite'
6
import { equals } from 'pepka'
7
8
9
const addr = (port: number) => 'ws://localhost:' + port
10
11
/** If an existing socket connection is provided via config. */
12
test('existing_socket', () => {
13
  return new Promise(async (ff, rj) => {
14
    const {port} = await mockServer()
15
    const to = setTimeout(() => rj(), 4e4)
16
    const existing_addr = addr(port)
17
18
    // This one CANNOT connect as fast as we send to it,
19
    // So readyState is 0.
20
    const ws1 = createNew({socket: new WS(existing_addr)}, port)
21
22
    if(ws1.socket?.readyState !== 0) return rj('not ready.')
23
24
    const msg1 = {echo: true, msg: 'existing_socket!'}
25
    const response1 = await ws1.send(msg1)
26
27
    if(
28
      ws1.socket?.readyState as number !== 1
29
      || !equals(response1, msg1)
30
    ) return rj('not ready.')
31
    await ws1.close()
32
33
    // This one DO CAN connect as fast as we send to it,
34
    // So readyState should be 1.
35
    const ws2_0 = new WS(existing_addr)
36
37
    ws2_0.addEventListener('open', async () => {
38
      const ws2 = await createNew({socket: ws2_0}, port)
39
40
      if(ws2.socket?.readyState !== 1) return rj('not ready.')
41
    
42
      const msg2 = {echo: true, msg: 'existing_socket!'}
43
      const response2 = await ws2.send(msg2)
44
45
      if(
46
        ws2.socket?.readyState as number !== 1
47
        || !equals(response2, msg2)
48
      ) return rj('not ready.')
49
      await ws2.close()
50
51
      clearTimeout(to)
52
      ff()
53
    })
54
  })
55
})