-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest.js
89 lines (79 loc) · 2.41 KB
/
test.js
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
const tap = require('tap')
const RSWS = require('./index')
const Server = require('simple-websocket/server')
tap.test('argument assertions', async t => {
t.throws(() => {
var a = new RSWS()
a.stop()
}, 'URL parameter is a string')
})
tap.test('yolo hook it all up test', t => {
t.plan(9)
const port = 8456
const connections = []
let server = new Server({ port: port })
const serverHandler = (socket) => {
console.log('client connected')
connections.push(socket)
socket.on('data', function (buf) {
t.pass(`server received a message: ${buf.toString('utf8')}`)
socket.write(buf.toString('utf8').toUpperCase())
})
socket.on('close', () => {
t.pass('server closed')
connections.splice(connections.find(s => s === socket), 1)
})
socket.on('error', err => t.error(err, 'socket should not error'))
}
server.on('connection', serverHandler)
server.on('error', (err) => { t.fail(err, 'server should not emit errors') })
function closeAllConnections () {
connections.forEach(socket => socket.destroy())
}
const firstConnectPath = (buf) => {
t.equal(buf.toString('utf8'), 'PING1', 'uppercase ping1')
server.close()
closeAllConnections()
setTimeout(() => {
console.log('server starting again')
server = new Server({ port: port })
server.on('connection', serverHandler)
server.on('error', (err) => { t.fail(err, 'server should not emit errors') })
}, 3000)
}
const secondConnectPath = (buf) => {
t.equal(buf.toString('utf8'), 'PING2', 'uppercase ping2')
server.close()
reconnectingWS.stop()
setTimeout(() => {
reconnectingWS.start()
}, 500)
}
const reconnectingWS = new RSWS(`ws://localhost:${8456}`, {
backoff: {
failAfter: 4
},
onopen (socket, firstOpen) {
if (firstOpen) {
t.pass('fisrtOpen socket ran')
socket.on('data', firstConnectPath)
socket.write('ping1')
} else {
t.pass('!fisrtOpen socket ran')
socket.on('data', secondConnectPath)
socket.write('ping2')
}
},
onclose (socket) {
socket.removeListener('data', firstConnectPath)
socket.removeListener('data', secondConnectPath)
},
onfail (err) {
t.equals(err.message, 'connection error to ws://localhost:8456')
}
})
reconnectingWS.on('info', console.log)
server.on('listening', () => {
reconnectingWS.start()
})
})