Passed
Push — master ( b0ae8b...67a8ba )
by Michael
01:38
created

test/specs/existing-socket.ts   A

Complexity

Total Complexity 8
Complexity/F 0

Size

Lines of Code 53
Function Count 0

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
wmc 8
eloc 43
mnd 8
bc 8
fnc 0
dl 0
loc 53
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', () => new Promise(async (ff, rj) => {
13
  const {port} = await mockServer()
14
  const to = setTimeout(() => rj(), 4e4)
15
  const existing_addr = addr(port)
16
17
  // This one CANNOT connect as fast as we send to it,
18
  // So readyState is 0.
19
  const ws1 = createNew({socket: new WS(existing_addr)}, port)
20
21
  if(ws1.socket?.readyState !== 0) return rj('not ready.')
22
23
  const msg1 = {echo: true, msg: 'existing_socket!'}
24
  const response1 = await ws1.send(msg1)
25
26
  if(
27
    ws1.socket?.readyState as number !== 1
28
    || !equals(response1, msg1)
29
  ) return rj('not ready.')
30
  await ws1.close()
31
32
  // This one DO CAN connect as fast as we send to it,
33
  // So readyState should be 1.
34
  const ws2_0 = new WS(existing_addr)
35
36
  ws2_0.addEventListener('open', async () => {
37
    const ws2 = createNew({socket: ws2_0}, port)
38
39
    if(ws2.socket?.readyState !== 1) return rj('not ready.')
40
  
41
    const msg2 = {echo: true, msg: 'existing_socket!'}
42
    const response2 = await ws2.send(msg2)
43
44
    if(
45
      ws2.socket?.readyState as number !== 1
46
      || !equals(response2, msg2)
47
    ) return rj('not ready.')
48
    await ws2.close()
49
50
    clearTimeout(to)
51
    ff()
52
  })
53
}))