@@ -20,8 +20,11 @@ describe("WebSocketClient", () => {
2020 // Clear any previous mocks
2121 vi . clearAllMocks ( ) ;
2222
23- // Mock the global WebSocket
24- global . WebSocket = vi . fn ( ( ) => {
23+ // Mock the global WebSocket. Use a regular (constructable) function rather
24+ // than an arrow function: the client invokes `new WebSocket(...)`, which
25+ // vitest satisfies by constructing the mock's implementation — and arrow
26+ // functions cannot be constructed.
27+ global . WebSocket = vi . fn ( function ( ) {
2528 // Set up the mock WebSocket and return it
2629 setTimeout ( ( ) => {
2730 if ( mockWebSocket . onopen ) {
@@ -47,7 +50,9 @@ describe("WebSocketClient", () => {
4750 describe ( "connection management" , ( ) => {
4851 it ( "establishes connection on instantiation" , ( ) => {
4952 // Mock the WebSocket constructor before creating the client
50- const wsConstructorSpy = vi . fn ( ( ) => mockWebSocket ) ;
53+ const wsConstructorSpy = vi . fn ( function ( ) {
54+ return mockWebSocket ;
55+ } ) ;
5156 global . WebSocket = wsConstructorSpy ;
5257
5358 client = new WebSocketClient ( ) ;
@@ -78,10 +83,15 @@ describe("WebSocketClient", () => {
7883 onclose : null ,
7984 } ;
8085
81- const wsConstructorSpy = vi
82- . fn ( )
83- . mockReturnValueOnce ( firstMockWebSocket )
84- . mockReturnValueOnce ( secondMockWebSocket ) ;
86+ // Regular (constructable) function returning a different socket per call:
87+ // the client constructs the WebSocket via `new`, which arrow functions and
88+ // bare mockReturnValue mocks cannot satisfy. The call counter lives outside
89+ // the spy so it survives the mockClear() below.
90+ let constructCount = 0 ;
91+ const sockets = [ firstMockWebSocket , secondMockWebSocket ] ;
92+ const wsConstructorSpy = vi . fn ( function ( ) {
93+ return sockets [ constructCount ++ ] ?? secondMockWebSocket ;
94+ } ) ;
8595
8696 global . WebSocket = wsConstructorSpy ;
8797
0 commit comments