This repository has been archived by the owner on Apr 2, 2024. It is now read-only.
generated from bennycode/ts-node-starter
-
Notifications
You must be signed in to change notification settings - Fork 63
/
WebSocketClient.test.ts
491 lines (402 loc) · 14.2 KB
/
WebSocketClient.test.ts
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
import WebSocket = require('ws');
import tickerBTCUSD from '../test/fixtures/ws/ticker/BTC-USD.json';
import statusPayload from '../test/fixtures/ws/status/status.json';
import matchesBTCUSD from '../test/fixtures/ws/matches/BTC-USD.json';
import l2snapshotBTCUSD from '../test/fixtures/ws/level2/snapshot.json';
import l2updateBTCUSD from '../test/fixtures/ws/level2/l2update.json';
import fullReceivedLimitBTCUSD from '../test/fixtures/ws/full/received-limit.json';
import fullActivateBTCUSD from '../test/fixtures/ws/full/activate.json';
import fullOpenBTCUSD from '../test/fixtures/ws/full/open.json';
import fullDoneBTCUSD from '../test/fixtures/ws/full/done.json';
import fullChangeBTCUSD from '../test/fixtures/ws/full/change.json';
import emptySubscriptions from '../test/fixtures/ws/empty-subscriptions.json';
import {
WebSocketChannelName,
WebSocketClient,
WebSocketEvent,
WebSocketRequestType,
WebSocketResponseType,
WebSocketRequest,
WebSocketChannel,
WebSocketErrorMessage,
} from './WebSocketClient';
import ReconnectingWebSocket from 'reconnecting-websocket';
const WEBSOCKET_PORT = 8087;
const WEBSOCKET_URL = `ws://localhost:${WEBSOCKET_PORT}`;
let server: WebSocket.Server;
describe('WebSocketClient', () => {
function createWebSocketClient(url: string = WEBSOCKET_URL): WebSocketClient {
return new WebSocketClient(url, () => {
return Promise.resolve({
key: '',
passphrase: '',
signature: '',
timestamp: Date.now() / 1000,
});
});
}
beforeEach(done => {
server = new WebSocket.Server({port: WEBSOCKET_PORT});
server.on('listening', () => done());
});
afterEach(done => {
if (server) {
server.close(error => {
if (error) {
done.fail(error);
} else {
done();
}
});
} else {
done();
}
});
describe('connect', () => {
it('attaches an error listener', done => {
const invalidUrl = 'ws://localhost:50001';
const ws = createWebSocketClient(invalidUrl);
ws.on(WebSocketEvent.ON_ERROR, done);
ws.connect();
});
it('throws an error when trying to overwrite an existing connection', done => {
const ws = createWebSocketClient();
ws.connect();
try {
ws.connect();
done.fail('No error has been thrown');
} catch (error) {
done();
}
});
it('supports custom reconnect options', async () => {
const ws = createWebSocketClient();
const socket = ws.connect({startClosed: true});
expect(socket.readyState).toBe(ReconnectingWebSocket.CLOSED);
});
});
describe('constructor', () => {
it('it signals an event when the WebSocket connection is established', done => {
const ws = createWebSocketClient();
ws.on(WebSocketEvent.ON_OPEN, () => done());
ws.connect();
});
});
describe('disconnect', () => {
it('does not do anything if there is no existing connection', () => {
const ws = createWebSocketClient();
const onClose = jasmine.createSpy('onClose');
ws.on(WebSocketEvent.ON_CLOSE, () => {
onClose();
});
ws.disconnect();
expect(onClose).not.toHaveBeenCalled();
});
it('emits an event when an existing connection gets closed', done => {
const ws = createWebSocketClient();
ws.on(WebSocketEvent.ON_CLOSE, () => {
done();
});
ws.on(WebSocketEvent.ON_OPEN, () => {
ws.disconnect();
});
ws.connect();
});
});
describe('sendMessage', () => {
it('does not send a message when there is no active connection', async () => {
const ws = createWebSocketClient();
try {
await ws.sendMessage({
channels: [WebSocketChannelName.HEARTBEAT],
type: WebSocketRequestType.UNSUBSCRIBE,
});
fail('No error has been thrown');
} catch (error) {
expect(error).toBeDefined();
}
});
});
describe('subscribe', () => {
function mockWebSocketResponse(
done: DoneFn,
channels: WebSocketChannel | WebSocketChannel[],
payload: Object
): WebSocketClient {
server.on('connection', ws => {
ws.on('message', (message: string) => {
const request = JSON.parse(message) as WebSocketRequest;
if (request.type === WebSocketRequestType.SUBSCRIBE) {
// Send subscription confirmation
server.clients.forEach(client =>
client.send(
JSON.stringify({
channels: request.channels,
type: WebSocketResponseType.SUBSCRIPTIONS,
})
)
);
// Send event for subscription
server.clients.forEach(client => client.send(JSON.stringify(payload)));
}
if (request.type === WebSocketRequestType.UNSUBSCRIBE) {
// Send unsubscribe confirmation
server.clients.forEach(client => client.send(JSON.stringify(emptySubscriptions)));
}
});
});
const ws = createWebSocketClient();
ws.on(WebSocketEvent.ON_SUBSCRIPTION_UPDATE, subscriptions => {
// Disconnect when there are no more open subscriptions
if (subscriptions.channels.length === 0) {
ws.disconnect();
}
});
ws.on(WebSocketEvent.ON_CLOSE, done);
ws.on(WebSocketEvent.ON_MESSAGE_ERROR, (wsError: WebSocketErrorMessage) => done.fail(wsError.message));
// Send subscription once the WebSocket is ready
ws.on(WebSocketEvent.ON_OPEN, () => ws.subscribe(channels));
return ws;
}
it('receives typed messages from "status" channel', (done: DoneFn) => {
const channel = {
name: WebSocketChannelName.STATUS,
};
const ws = mockWebSocketResponse(done, channel, statusPayload);
ws.on(WebSocketEvent.ON_MESSAGE_STATUS, message => {
expect(message.currencies[2].details.sort_order).toBe(48);
expect(message.products[72].id).toBe('XRP-USD');
ws.unsubscribe(channel);
});
ws.connect();
});
it('receives typed messages from "ticker" channel', done => {
const channel = {
name: WebSocketChannelName.TICKER,
product_ids: ['BTC-USD'],
};
const ws = mockWebSocketResponse(done, channel, tickerBTCUSD);
ws.on(WebSocketEvent.ON_MESSAGE_TICKER, tickerMessage => {
expect(tickerMessage.trade_id).toBe(3526965);
ws.unsubscribe(channel);
});
ws.connect();
});
it('receives typed "snapshot" messages from "level2" channel', done => {
const channel = {
name: WebSocketChannelName.LEVEL2,
product_ids: ['BTC-USD'],
};
const ws = mockWebSocketResponse(done, channel, l2snapshotBTCUSD);
ws.on(WebSocketEvent.ON_MESSAGE_L2SNAPSHOT, snapshotMessage => {
expect<number>(snapshotMessage.asks.length).toBe(10);
expect(snapshotMessage.asks[0]).toEqual(['47009.28', '0.00100000']);
expect<number>(snapshotMessage.bids.length).toBe(10);
ws.unsubscribe(channel);
});
ws.connect();
});
it('receives typed "l2update" messages from "level2" channel', done => {
const channel = {
name: WebSocketChannelName.LEVEL2,
product_ids: ['BTC-USD'],
};
const ws = mockWebSocketResponse(done, channel, l2updateBTCUSD);
ws.on(WebSocketEvent.ON_MESSAGE_L2UPDATE, updateMessage => {
expect<number>(updateMessage.changes.length).toBe(5);
expect(updateMessage.changes[0]).toEqual(['buy', '46961.95', '0.00000000']);
expect(updateMessage.changes[1]).toEqual(['sell', '47027.24', '0.04443115']);
ws.unsubscribe(channel);
});
ws.connect();
});
it('receives typed "activate" messages from "full" channel', done => {
const channel = {
name: WebSocketChannelName.FULL,
product_ids: ['BTC-USD'],
};
const ws = mockWebSocketResponse(done, channel, fullActivateBTCUSD);
ws.on(WebSocketEvent.ON_MESSAGE_FULL_ACTIVATE, message => {
expect(message.profile_id).toBe('30000727-d308-cf50-7b1c-c06deb1934fc');
expect(message.private).toBe(true);
expect(message.stop_type).toBe('entry');
ws.unsubscribe(channel);
});
ws.connect();
});
it('receives typed "received" messages from "full" channel', done => {
const channel = {
name: WebSocketChannelName.FULL,
product_ids: ['BTC-USD'],
};
const ws = mockWebSocketResponse(done, channel, fullReceivedLimitBTCUSD);
ws.on(WebSocketEvent.ON_MESSAGE_FULL_RECEIVED, message => {
expect(message.order_type).toBe('limit');
expect(message.order_id).toBe('d50ec984-77a8-460a-b958-66f114b0de9b');
ws.unsubscribe(channel);
});
ws.connect();
});
it('receives typed "open" messages from "full" channel', done => {
const channel = {
name: WebSocketChannelName.FULL,
product_ids: ['BTC-USD'],
};
const ws = mockWebSocketResponse(done, channel, fullOpenBTCUSD);
ws.on(WebSocketEvent.ON_MESSAGE_FULL_OPEN, message => {
expect(message.profile_id).toBe(undefined);
expect(message.remaining_size).toBe('1.00');
ws.unsubscribe(channel);
});
ws.connect();
});
it('receives typed "done" messages from "full" channel', done => {
const channel = {
name: WebSocketChannelName.FULL,
product_ids: ['BTC-USD'],
};
const ws = mockWebSocketResponse(done, channel, fullDoneBTCUSD);
ws.on(WebSocketEvent.ON_MESSAGE_FULL_DONE, message => {
expect(message.profile_id).toBe(undefined);
expect(message.remaining_size).toBe('0');
expect(message.reason).toBe('filled');
ws.unsubscribe(channel);
});
ws.connect();
});
it('receives typed "change" messages from "full" channel', done => {
const channel = {
name: WebSocketChannelName.FULL,
product_ids: ['BTC-USD'],
};
const ws = mockWebSocketResponse(done, channel, fullChangeBTCUSD);
ws.on(WebSocketEvent.ON_MESSAGE_FULL_CHANGE, message => {
expect(message.new_size).toBe('5.23512');
expect(message.old_size).toBe('12.234412');
ws.unsubscribe(channel);
});
ws.connect();
});
it('receives typed "ticker" messages from the special "ticker_1000" channel', done => {
const channel = {
name: WebSocketChannelName.TICKER_1000,
product_ids: ['BTC-USD'],
};
const ws = mockWebSocketResponse(done, channel, tickerBTCUSD);
ws.on(WebSocketEvent.ON_MESSAGE_TICKER, tickerMessage => {
expect(tickerMessage.trade_id).toBe(3526965);
ws.unsubscribe(channel);
});
ws.connect();
});
it('receives typed messages from multiple "matches" channels', done => {
const channels = [
{
name: WebSocketChannelName.MATCHES,
product_ids: ['BTC-USD'],
},
];
const ws = mockWebSocketResponse(done, channels, matchesBTCUSD);
ws.on(WebSocketEvent.ON_MESSAGE_MATCHES, message => {
expect(message.trade_id).toBe(9713921);
ws.unsubscribe(channels);
});
ws.connect();
});
it('receives typed error messages', done => {
server.on('connection', ws => {
ws.on('message', (message: string) => {
const request = JSON.parse(message);
if (request.type === WebSocketRequestType.SUBSCRIBE) {
const response = JSON.stringify({
message: 'Failed to subscribe',
reason: 'user channel requires authentication',
type: WebSocketResponseType.ERROR,
});
server.clients.forEach(client => {
client.send(response);
});
}
});
});
const ws = createWebSocketClient();
ws.on(WebSocketEvent.ON_MESSAGE_ERROR, errorMessage => {
expect(errorMessage.type).toBe(WebSocketResponseType.ERROR);
done();
});
ws.on(WebSocketEvent.ON_OPEN, () => {
ws.subscribe({
name: WebSocketChannelName.USER,
product_ids: ['BTC-USD'],
});
});
ws.connect();
});
});
describe('unsubscribe', () => {
it('unsubscribes from all products on a channel', done => {
server.on('connection', socket => {
socket.on('message', (message: string) => {
const request = JSON.parse(message);
if (request.type === WebSocketRequestType.UNSUBSCRIBE) {
const response = JSON.stringify(emptySubscriptions);
server.clients.forEach(client => client.send(response));
}
});
});
const ws = createWebSocketClient();
ws.on(WebSocketEvent.ON_SUBSCRIPTION_UPDATE, subscriptions => {
if (subscriptions.channels.length === 0) {
ws.disconnect();
}
});
ws.on(WebSocketEvent.ON_CLOSE, done);
ws.on(WebSocketEvent.ON_OPEN, () => ws.unsubscribe(WebSocketChannelName.TICKER));
ws.connect();
});
});
describe('setupHeartbeat', () => {
it('sends ping messages within a defined interval', done => {
server.on('connection', socket => {
socket.on('ping', () => {
done();
});
});
const ws = createWebSocketClient();
ws['pingTime'] = 100;
ws.connect();
});
});
describe('heartbeat', () => {
it('resets pong timeouts', () => {
const ws = createWebSocketClient();
ws['pongTimeout'] = setTimeout(() => {
fail('I should not get invoked');
}, 1000);
ws['heartbeat']();
});
});
describe('onPongTimeout', () => {
it('does not fail when there is no active socket', () => {
const ws = createWebSocketClient();
ws['onPongTimeout']();
});
it('reconnects a socket when the pong timeout is exceeded', () => {
const ws = createWebSocketClient();
ws.connect();
ws['onPongTimeout']();
});
});
describe('cleanupListener', () => {
it('removes ping & pong listener', () => {
const ws = createWebSocketClient();
ws['pingInterval'] = setInterval(() => {
fail('I should not get invoked');
}, 1000);
ws['pongTimeout'] = setTimeout(() => {
fail('I should not get invoked');
}, 1000);
ws['cleanupListener']();
});
});
});