-
-
Notifications
You must be signed in to change notification settings - Fork 276
Expand file tree
/
Copy pathBackendWebSocketService.test.ts
More file actions
1745 lines (1479 loc) · 58.1 KB
/
BackendWebSocketService.test.ts
File metadata and controls
1745 lines (1479 loc) · 58.1 KB
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
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {
Messenger,
MOCK_ANY_NAMESPACE,
type MessengerActions,
type MessengerEvents,
type MockAnyNamespace,
} from '@metamask/messenger';
import {
BackendWebSocketService,
getCloseReason,
WebSocketState,
type BackendWebSocketServiceOptions,
type BackendWebSocketServiceMessenger,
} from './BackendWebSocketService';
import { flushPromises } from '../../../tests/helpers';
// =====================================================
// TYPES
// =====================================================
// Type for global object with WebSocket mock
type GlobalWithWebSocket = typeof global & { lastWebSocket: MockWebSocket };
type AllBackendWebSocketServiceActions =
MessengerActions<BackendWebSocketServiceMessenger>;
type AllBackendWebSocketServiceEvents =
MessengerEvents<BackendWebSocketServiceMessenger>;
type RootMessenger = Messenger<
MockAnyNamespace,
AllBackendWebSocketServiceActions,
AllBackendWebSocketServiceEvents
>;
// =====================================================
// MOCK WEBSOCKET CLASS
// =====================================================
/**
* Mock WebSocket implementation for testing
* Provides controlled WebSocket behavior with immediate connection control
*/
class MockWebSocket extends EventTarget {
// WebSocket state constants
public static readonly CONNECTING = 0;
public static readonly OPEN = 1;
public static readonly CLOSING = 2;
public static readonly CLOSED = 3;
// WebSocket properties
public readyState: number = MockWebSocket.CONNECTING;
public url: string;
// Event handlers
// eslint-disable-next-line n/no-unsupported-features/node-builtins
public onclose: ((event: CloseEvent) => void) | null = null;
public onmessage: ((event: MessageEvent) => void) | null = null;
public onerror: ((event: Event) => void) | null = null;
// Mock methods for testing
public close: jest.Mock<void, [number?, string?]> = jest.fn();
public send: jest.Mock<void, [string]> = jest.fn();
// Test utilities
private _lastSentMessage: string | null = null;
get lastSentMessage(): string | null {
return this._lastSentMessage;
}
private _openTriggered = false;
private _onopen: ((event: Event) => void) | null = null;
public autoConnect: boolean = true;
constructor(
url: string,
{ autoConnect = true }: { autoConnect?: boolean } = {},
) {
super();
this.url = url;
// TypeScript has issues with jest.spyOn on WebSocket methods, so using direct assignment
// eslint-disable-next-line jest/prefer-spy-on
this.close = jest.fn().mockImplementation();
// eslint-disable-next-line jest/prefer-spy-on
this.send = jest.fn().mockImplementation((data: string) => {
this._lastSentMessage = data;
});
this.autoConnect = autoConnect;
(global as GlobalWithWebSocket).lastWebSocket = this;
}
set onopen(handler: ((event: Event) => void) | null) {
this._onopen = handler;
if (
handler &&
!this._openTriggered &&
this.readyState === MockWebSocket.CONNECTING &&
this.autoConnect
) {
// Trigger immediately to ensure connection completes
this.triggerOpen();
}
}
get onopen() {
return this._onopen;
}
public triggerOpen() {
if (
!this._openTriggered &&
this._onopen &&
this.readyState === MockWebSocket.CONNECTING
) {
this._openTriggered = true;
this.readyState = MockWebSocket.OPEN;
const event = new Event('open');
this._onopen(event);
this.dispatchEvent(event);
}
}
public simulateClose(code = 1000, reason = '') {
this.readyState = MockWebSocket.CLOSED;
// eslint-disable-next-line n/no-unsupported-features/node-builtins
const event = new CloseEvent('close', { code, reason });
this.onclose?.(event);
this.dispatchEvent(event);
}
public simulateMessage(data: string | object) {
const messageData = typeof data === 'string' ? data : JSON.stringify(data);
const event = new MessageEvent('message', { data: messageData });
if (this.onmessage) {
this.onmessage(event);
}
this.dispatchEvent(event);
}
public simulateError() {
const event = new Event('error');
this.onerror?.(event);
this.dispatchEvent(event);
}
public getLastSentMessage(): string | null {
return this._lastSentMessage;
}
}
// =====================================================
// TEST UTILITIES & MOCKS
// =====================================================
/**
* Creates and returns a root messenger for testing
*
* @returns A messenger instance
*/
function getRootMessenger(): RootMessenger {
return new Messenger({
namespace: MOCK_ANY_NAMESPACE,
});
}
/**
* Creates a real messenger with registered mock actions for testing
* Each call creates a completely independent messenger to ensure test isolation
*
* @returns Object containing the messenger and mock action functions
*/
const getMessenger = () => {
// Create a unique root messenger for each test
const rootMessenger = getRootMessenger();
const messenger = new Messenger<
'BackendWebSocketService',
AllBackendWebSocketServiceActions,
AllBackendWebSocketServiceEvents,
RootMessenger
>({
namespace: 'BackendWebSocketService',
parent: rootMessenger,
});
rootMessenger.delegate({
actions: ['AuthenticationController:getBearerToken'],
events: ['AuthenticationController:stateChange'],
messenger,
});
// Create mock action handlers
const mockGetBearerToken = jest.fn().mockResolvedValue('valid-default-token');
// Register all action handlers
rootMessenger.registerActionHandler(
'AuthenticationController:getBearerToken',
mockGetBearerToken,
);
return {
rootMessenger,
messenger,
mocks: {
getBearerToken: mockGetBearerToken,
},
};
};
// =====================================================
// TEST CONSTANTS & DATA
// =====================================================
const TEST_CONSTANTS = {
WS_URL: 'ws://localhost:8080',
TEST_CHANNEL: 'test-channel',
SUBSCRIPTION_ID: 'sub-123',
TIMEOUT_MS: 100,
RECONNECT_DELAY: 50,
} as const;
/**
* Helper to create a properly formatted WebSocket response message
*
* @param requestId - The request ID to match with the response
* @param data - The response data payload
* @returns Formatted WebSocket response message
*/
const createResponseMessage = (
requestId: string,
data: Record<string, unknown>,
) => ({
id: requestId,
data: {
requestId,
...data,
},
});
// Setup function following TokenBalancesController pattern
// =====================================================
// TEST SETUP HELPER
// =====================================================
/**
* Test configuration options
*/
type TestSetupOptions = {
options?: Partial<BackendWebSocketServiceOptions>;
mockWebSocketOptions?: { autoConnect?: boolean };
};
/**
* Test setup return value with all necessary test utilities
*/
type TestSetup = {
service: BackendWebSocketService;
messenger: BackendWebSocketServiceMessenger;
rootMessenger: RootMessenger;
mocks: {
getBearerToken: jest.Mock;
};
spies: {
publish: jest.SpyInstance;
call: jest.SpyInstance;
};
completeAsyncOperations: (advanceMs?: number) => Promise<void>;
getMockWebSocket: () => MockWebSocket;
cleanup: () => void;
};
/**
* The callback that `withService` calls.
*/
type WithServiceCallback<ReturnValue> = (payload: {
service: BackendWebSocketService;
messenger: BackendWebSocketServiceMessenger;
rootMessenger: RootMessenger;
mocks: {
getBearerToken: jest.Mock;
};
spies: {
publish: jest.SpyInstance;
call: jest.SpyInstance;
};
completeAsyncOperations: (advanceMs?: number) => Promise<void>;
getMockWebSocket: () => MockWebSocket;
}) => Promise<ReturnValue> | ReturnValue;
/**
* Create a fresh BackendWebSocketService instance with mocked dependencies for testing.
* Follows the TokenBalancesController test pattern for complete test isolation.
*
* @param config - Test configuration options
* @param config.options - WebSocket service configuration options
* @param config.mockWebSocketOptions - Mock WebSocket configuration options
* @returns Test utilities and cleanup function
*/
const setupBackendWebSocketService = ({
options,
mockWebSocketOptions,
}: TestSetupOptions = {}): TestSetup => {
// Setup fake timers to control all async operations
jest.useFakeTimers();
// Create real messenger with registered actions
const messengerSetup = getMessenger();
const { rootMessenger, messenger, mocks } = messengerSetup;
// Create spies BEFORE service construction to capture constructor calls
const publishSpy = jest.spyOn(messenger, 'publish');
const callSpy = jest.spyOn(messenger, 'call');
// Default test options (shorter timeouts for faster tests)
const defaultOptions = {
url: TEST_CONSTANTS.WS_URL,
timeout: TEST_CONSTANTS.TIMEOUT_MS,
reconnectDelay: TEST_CONSTANTS.RECONNECT_DELAY,
maxReconnectDelay: TEST_CONSTANTS.TIMEOUT_MS,
requestTimeout: TEST_CONSTANTS.TIMEOUT_MS,
};
// Create custom MockWebSocket class for this test
class TestMockWebSocket extends MockWebSocket {
constructor(url: string) {
super(url, mockWebSocketOptions);
}
}
// Replace global WebSocket for this test
// eslint-disable-next-line n/no-unsupported-features/node-builtins
global.WebSocket = TestMockWebSocket as unknown as typeof WebSocket;
const service = new BackendWebSocketService({
messenger,
...defaultOptions,
...options,
});
const completeAsyncOperations = async (advanceMs = 10) => {
await flushPromises();
if (advanceMs > 0) {
jest.advanceTimersByTime(advanceMs);
}
await flushPromises();
};
const getMockWebSocket = (): MockWebSocket => {
return (global as GlobalWithWebSocket).lastWebSocket;
};
return {
service,
messenger,
rootMessenger,
mocks,
spies: {
publish: publishSpy,
call: callSpy,
},
completeAsyncOperations,
getMockWebSocket,
cleanup: () => {
service?.destroy();
publishSpy.mockRestore();
callSpy.mockRestore();
jest.useRealTimers();
jest.clearAllMocks();
},
};
};
/**
* Wrap tests for the BackendWebSocketService by ensuring that the service is
* created ahead of time and then safely destroyed afterward as needed.
*
* @param args - Either a function, or an options bag + a function. The options
* bag contains arguments for the service constructor. All constructor
* arguments are optional and will be filled in with defaults as needed
* (including `messenger`). The function is called with the new
* service, root messenger, and service messenger.
* @returns The same return value as the given function.
*/
async function withService<ReturnValue>(
...args:
| [WithServiceCallback<ReturnValue>]
| [TestSetupOptions, WithServiceCallback<ReturnValue>]
): Promise<ReturnValue> {
const [{ options = {}, mockWebSocketOptions = {} }, testFunction] =
args.length === 2 ? args : [{}, args[0]];
const setup = setupBackendWebSocketService({ options, mockWebSocketOptions });
try {
return await testFunction({
service: setup.service,
messenger: setup.messenger,
rootMessenger: setup.rootMessenger,
mocks: setup.mocks,
spies: setup.spies,
completeAsyncOperations: setup.completeAsyncOperations,
getMockWebSocket: setup.getMockWebSocket,
});
} finally {
setup.cleanup();
}
}
/**
* Helper to create a subscription with predictable response
*
* @param service - The WebSocket service
* @param mockWs - Mock WebSocket instance
* @param options - Subscription options
* @param options.channels - Channels to subscribe to
* @param options.callback - Callback function
* @param options.requestId - Request ID
* @param options.subscriptionId - Subscription ID
* @returns Promise with subscription
*/
const createSubscription = async (
service: BackendWebSocketService,
mockWs: MockWebSocket,
options: {
channels: string[];
callback: jest.Mock;
requestId: string;
subscriptionId?: string;
},
) => {
const {
channels,
callback,
requestId,
subscriptionId = 'test-sub',
} = options;
const subscriptionPromise = service.subscribe({
channels,
callback,
requestId,
});
const responseMessage = createResponseMessage(requestId, {
subscriptionId,
successful: channels,
failed: [],
});
mockWs.simulateMessage(responseMessage);
return subscriptionPromise;
};
// =====================================================
// WEBSOCKETSERVICE TESTS
// =====================================================
describe('BackendWebSocketService', () => {
// =====================================================
// CONSTRUCTOR TESTS
// =====================================================
describe('constructor', () => {
it('should create a BackendWebSocketService instance with custom options', async () => {
await withService(
{
options: {
url: 'wss://custom.example.com',
timeout: 5000,
},
mockWebSocketOptions: { autoConnect: false },
},
async ({ service }) => {
expect(service).toBeInstanceOf(BackendWebSocketService);
expect(service.getConnectionInfo().url).toBe(
'wss://custom.example.com',
);
},
);
});
});
// =====================================================
// CONNECTION LIFECYCLE TESTS
// =====================================================
describe('connection lifecycle - connect / disconnect', () => {
it('should establish WebSocket connection and set state to CONNECTED, publishing state change event', async () => {
await withService(async ({ service, spies }) => {
await service.connect();
const connectionInfo = service.getConnectionInfo();
expect(connectionInfo.state).toBe(WebSocketState.CONNECTED);
expect(connectionInfo.reconnectAttempts).toBe(0);
expect(connectionInfo.url).toBe('ws://localhost:8080');
expect(spies.publish).toHaveBeenCalledWith(
'BackendWebSocketService:connectionStateChanged',
expect.objectContaining({
state: WebSocketState.CONNECTED,
reconnectAttempts: 0,
}),
);
});
});
it('should return immediately without creating new connection when already connected', async () => {
await withService(async ({ service, spies }) => {
// Connect first time
await service.connect();
// Try to connect again
await service.connect();
expect(spies.publish).toHaveBeenNthCalledWith(
1,
'BackendWebSocketService:connectionStateChanged',
expect.objectContaining({ state: WebSocketState.CONNECTING }),
);
expect(spies.publish).toHaveBeenNthCalledWith(
2,
'BackendWebSocketService:connectionStateChanged',
expect.objectContaining({ state: WebSocketState.CONNECTED }),
);
});
});
it('should handle connection timeout by rejecting with timeout error and setting state to DISCONNECTED', async () => {
await withService(
{
options: { timeout: TEST_CONSTANTS.TIMEOUT_MS },
mockWebSocketOptions: { autoConnect: false },
},
async ({ service, completeAsyncOperations }) => {
expect(service.getConnectionInfo().state).toBe(
WebSocketState.DISCONNECTED,
);
const connectPromise = service.connect();
connectPromise.catch(() => {
// Expected rejection - no action needed
});
await completeAsyncOperations(TEST_CONSTANTS.TIMEOUT_MS + 50);
await expect(connectPromise).rejects.toThrow(
`Failed to connect to WebSocket: Connection timeout after ${TEST_CONSTANTS.TIMEOUT_MS}ms`,
);
const connectionInfo = service.getConnectionInfo();
expect(connectionInfo.state).toBe(WebSocketState.ERROR);
expect(connectionInfo.reconnectAttempts).toBe(0);
expect(connectionInfo.url).toBe('ws://localhost:8080');
},
);
});
it('should reject sendMessage and sendRequest operations when WebSocket is disconnected', async () => {
await withService(
{ mockWebSocketOptions: { autoConnect: false } },
async ({ service }) => {
expect(service.getConnectionInfo().state).toBe(
WebSocketState.DISCONNECTED,
);
expect(() =>
service.sendMessage({ event: 'test', data: { requestId: 'test' } }),
).toThrow('Cannot send message: WebSocket is disconnected');
await expect(
service.sendRequest({ event: 'test', data: {} }),
).rejects.toThrow('Cannot send request: WebSocket is disconnected');
await expect(
service.subscribe({ channels: ['test'], callback: jest.fn() }),
).rejects.toThrow(
'Cannot create subscription(s) test: WebSocket is disconnected',
);
},
);
});
it('should handle request timeout by clearing pending requests and forcing WebSocket reconnection', async () => {
await withService(
{ options: { requestTimeout: 200 } },
async ({ service, getMockWebSocket }) => {
await service.connect();
const mockWs = getMockWebSocket();
const closeSpy = jest.spyOn(mockWs, 'close');
const requestPromise = service.sendRequest({
event: 'timeout-test',
data: { requestId: 'timeout-req-1', method: 'test', params: {} },
});
jest.advanceTimersByTime(201);
await expect(requestPromise).rejects.toThrow(
'Request timeout after 200ms',
);
expect(closeSpy).toHaveBeenCalledWith(
3000,
'Request timeout - forcing reconnect',
);
closeSpy.mockRestore();
},
);
});
it('should handle abnormal WebSocket close by triggering reconnection', async () => {
await withService(
async ({ service, getMockWebSocket, completeAsyncOperations }) => {
await service.connect();
expect(service.getConnectionInfo().state).toBe(
WebSocketState.CONNECTED,
);
expect(service.getConnectionInfo().reconnectAttempts).toBe(0);
const mockWs = getMockWebSocket();
// Simulate abnormal closure (should trigger reconnection)
mockWs.simulateClose(1006, 'Abnormal closure');
await completeAsyncOperations(0);
// Service should transition to DISCONNECTED
expect(service.getConnectionInfo().state).toBe(
WebSocketState.DISCONNECTED,
);
// Advance time to trigger reconnection attempt
await completeAsyncOperations(100);
// Service should have successfully reconnected
expect(service.getConnectionInfo().state).toBe(
WebSocketState.CONNECTED,
);
expect(service.getConnectionInfo().reconnectAttempts).toBe(0); // Reset on successful connection
},
);
});
it('should handle normal WebSocket close without triggering reconnection', async () => {
await withService(
async ({ service, getMockWebSocket, completeAsyncOperations }) => {
await service.connect();
const mockWs = getMockWebSocket();
// Simulate normal closure (should NOT trigger reconnection)
mockWs.simulateClose(1000, 'Normal closure');
await completeAsyncOperations(0);
// Service should be in DISCONNECTED state (normal closure, not an error)
expect(service.getConnectionInfo().state).toBe(
WebSocketState.DISCONNECTED,
);
// Advance time - should NOT attempt reconnection
await completeAsyncOperations(200);
// Should still be in DISCONNECTED state (no reconnection for normal closures)
expect(service.getConnectionInfo().state).toBe(
WebSocketState.DISCONNECTED,
);
},
);
});
it('should handle WebSocket error events during runtime without immediate state change', async () => {
await withService(async ({ service, getMockWebSocket }) => {
await service.connect();
expect(service.getConnectionInfo().state).toBe(
WebSocketState.CONNECTED,
);
const mockWs = getMockWebSocket();
// Simulate error event - runtime errors are handled but don't immediately change state
// The actual state change happens when the connection closes
mockWs.simulateError();
// Service remains connected (error handler is a placeholder)
// Real disconnection will happen through onclose event
expect(service.getConnectionInfo().state).toBe(
WebSocketState.CONNECTED,
);
});
});
it('should schedule another reconnection attempt when connect fails during reconnection', async () => {
await withService(
{
options: {
reconnectDelay: 50,
maxReconnectDelay: 100,
},
},
async ({ service, completeAsyncOperations, getMockWebSocket }) => {
// Connect first
await service.connect();
// Track connect calls
let connectCallCount = 0;
const connectSpy = jest.spyOn(service, 'connect');
connectSpy.mockImplementation(async () => {
connectCallCount += 1;
// Fail the first reconnection attempt
throw new Error('Connection failed');
});
// Simulate connection loss to trigger reconnection
const mockWs = getMockWebSocket();
mockWs.simulateClose(1006, 'Connection lost');
await completeAsyncOperations(0);
// Advance time to trigger first reconnection attempt (will fail)
await completeAsyncOperations(75);
// Verify first connect was called
expect(connectCallCount).toBe(1);
// Advance time to trigger second reconnection (verifies catch scheduled another)
await completeAsyncOperations(150);
// If catch block works, connect should be called again
expect(connectCallCount).toBeGreaterThan(1);
connectSpy.mockRestore();
},
);
});
it('should handle WebSocket close events during connection establishment without close reason', async () => {
await withService(async ({ service, getMockWebSocket }) => {
// Connect and get the WebSocket instance
await service.connect();
const mockWs = getMockWebSocket();
// Simulate close event without reason - this should hit line 918 (event.reason || 'none' falsy branch)
mockWs.simulateClose(1006, undefined);
// Verify the service state changed due to the close event
expect(service.name).toBe('BackendWebSocketService');
const connectionInfo = service.getConnectionInfo();
expect(connectionInfo.state).toBe(WebSocketState.DISCONNECTED);
expect(connectionInfo.url).toBe('ws://localhost:8080');
});
});
it('should disconnect WebSocket connection and set state to DISCONNECTED when connected', async () => {
await withService(async ({ service }) => {
await service.connect();
expect(service.getConnectionInfo().state).toBe(
WebSocketState.CONNECTED,
);
await service.disconnect();
const connectionInfo = service.getConnectionInfo();
expect(connectionInfo.state).toBe(WebSocketState.DISCONNECTED);
expect(connectionInfo.url).toBe('ws://localhost:8080'); // URL persists after disconnect
expect(connectionInfo.reconnectAttempts).toBe(0);
});
});
it('should handle disconnect gracefully when WebSocket is already disconnected', async () => {
await withService(async ({ service }) => {
expect(() => service.disconnect()).not.toThrow();
expect(service.getConnectionInfo().state).toBe(
WebSocketState.DISCONNECTED,
);
});
});
it('should handle concurrent connect calls by awaiting existing connection promise and returning same result', async () => {
await withService(
{ mockWebSocketOptions: { autoConnect: false } },
async ({ service, getMockWebSocket, completeAsyncOperations }) => {
// Start first connection (will be in CONNECTING state)
const firstConnect = service.connect();
await completeAsyncOperations(10); // Allow connect to start
expect(service.getConnectionInfo().state).toBe(
WebSocketState.CONNECTING,
);
// Start second connection while first is still connecting
// This should await the existing connection promise
const secondConnect = service.connect();
// Complete the first connection
const mockWs = getMockWebSocket();
mockWs.triggerOpen();
// Both promises should resolve successfully
await Promise.all([firstConnect, secondConnect]);
const connectionInfo = service.getConnectionInfo();
expect(connectionInfo.state).toBe(WebSocketState.CONNECTED);
expect(connectionInfo.reconnectAttempts).toBe(0);
expect(connectionInfo.url).toBe('ws://localhost:8080');
},
);
});
it('should handle WebSocket error events during connection establishment by setting state to ERROR', async () => {
await withService(
{ mockWebSocketOptions: { autoConnect: false } },
async ({ service, getMockWebSocket, completeAsyncOperations }) => {
const connectPromise = service.connect();
await completeAsyncOperations(10);
// Trigger error event during connection phase
const mockWs = getMockWebSocket();
mockWs.simulateError();
await expect(connectPromise).rejects.toThrow(
'WebSocket connection error',
);
expect(service.getConnectionInfo().state).toBe(WebSocketState.ERROR);
},
);
});
it('should handle WebSocket close events during connection establishment by setting state to ERROR', async () => {
await withService(
{ mockWebSocketOptions: { autoConnect: false } },
async ({ service, getMockWebSocket, completeAsyncOperations }) => {
const connectPromise = service.connect();
await completeAsyncOperations(10);
// Trigger close event during connection phase
const mockWs = getMockWebSocket();
mockWs.simulateClose(1006, 'Connection failed');
await expect(connectPromise).rejects.toThrow(
'WebSocket connection closed during connection',
);
},
);
});
it('should properly transition through disconnecting state during manual disconnect and set final state to DISCONNECTED', async () => {
await withService(async ({ service, getMockWebSocket }) => {
await service.connect();
const mockWs = getMockWebSocket();
// Mock the close method to simulate manual WebSocket close
mockWs.close.mockImplementation(
(code = 1000, reason = 'Normal closure') => {
mockWs.simulateClose(code, reason);
},
);
// Start manual disconnect - this will trigger close() and simulate close event
await service.disconnect();
// The service should transition through DISCONNECTING to DISCONNECTED
expect(service.getConnectionInfo().state).toBe(
WebSocketState.DISCONNECTED,
);
// Verify the close method was called with normal closure code
expect(mockWs.close).toHaveBeenCalledWith(1000, 'Normal closure');
});
});
});
// =====================================================
// SUBSCRIPTION TESTS
// =====================================================
describe('subscribe', () => {
it('should subscribe to WebSocket channels and return subscription with unsubscribe function', async () => {
await withService(async ({ service, getMockWebSocket }) => {
await service.connect();
const mockCallback = jest.fn();
const mockWs = getMockWebSocket();
const subscription = await createSubscription(service, mockWs, {
channels: [TEST_CONSTANTS.TEST_CHANNEL],
callback: mockCallback,
requestId: 'test-subscribe-success',
subscriptionId: TEST_CONSTANTS.SUBSCRIPTION_ID,
});
expect(subscription.subscriptionId).toBe(
TEST_CONSTANTS.SUBSCRIPTION_ID,
);
expect(typeof subscription.unsubscribe).toBe('function');
});
});
it('should handle various error scenarios including connection failures and invalid responses', async () => {
await withService(async ({ service, getMockWebSocket }) => {
await service.connect();
const mockWs = getMockWebSocket();
// Test subscription failure scenario
const callback = jest.fn();
// Create subscription request - Use predictable request ID
const testRequestId = 'test-error-branch-scenarios';
const subscriptionPromise = service.subscribe({
channels: ['test-channel-error'],
callback,
requestId: testRequestId,
});
// Simulate response with failure - no waiting needed!
mockWs.simulateMessage({
id: testRequestId,
data: {
requestId: testRequestId,
subscriptionId: 'error-sub',
successful: [],
failed: ['test-channel-error'],
},
});
// Should reject due to failed channels
await expect(subscriptionPromise).rejects.toThrow(
'Request failed: test-channel-error',
);
});
});
it('should handle unsubscribe errors and connection errors gracefully without throwing', async () => {
await withService(async ({ service, getMockWebSocket }) => {
await service.connect();
const mockWs = getMockWebSocket();
const mockCallback = jest.fn();
const subscription = await createSubscription(service, mockWs, {
channels: ['test-channel'],
callback: mockCallback,
requestId: 'test-subscription-unsub-error',
subscriptionId: 'unsub-error-test',
});
// Mock sendRequest to throw error during unsubscribe
jest.spyOn(service, 'sendRequest').mockImplementation(() => {
return Promise.reject(new Error('Unsubscribe failed'));
});
await expect(subscription.unsubscribe()).rejects.toThrow(
'Unsubscribe failed',
);
});
});
it('should throw error when subscription response is missing required subscription ID field', async () => {
await withService(async ({ service, getMockWebSocket }) => {
await service.connect();
const mockWs = getMockWebSocket();
const subscriptionPromise = service.subscribe({
channels: ['invalid-test'],
callback: jest.fn(),
requestId: 'test-missing-subscription-id',
});
// Send response without subscriptionId
mockWs.simulateMessage({
id: 'test-missing-subscription-id',
data: {
requestId: 'test-missing-subscription-id',
successful: ['invalid-test'],
failed: [],
},
});
await expect(subscriptionPromise).rejects.toThrow(
'Invalid subscription response: missing subscription ID',
);
});
});
it('should throw subscription-specific error when individual channels fail to subscribe', async () => {
await withService(async ({ service }) => {
await service.connect();
jest.spyOn(service, 'sendRequest').mockResolvedValueOnce({
subscriptionId: 'valid-sub-id',
successful: [],
failed: ['fail-test'],
});
await expect(
service.subscribe({
channels: ['fail-test'],
callback: jest.fn(),