jest-websocket-mock icon indicating copy to clipboard operation
jest-websocket-mock copied to clipboard

server.error() removes the server from the urlMap, and it cannot be reconnected to

Open johanlajili opened this issue 4 years ago • 3 comments

Hi, I have a unit test that is something along the line of

it('retries to connect to the websocket connection after 5 seconds on error'){
  await server.connected

   server.error();
   await server.closed;
   jest.useFakeTimers()
   jest.advancedTimerByTime(5000);
   jest.useRealTimers()
   
   await server.connected;
   server.send({message: 'whatever'})
   expect(clentMessages).toBe([{message: 'whatever'}])
}

Bit pseudo-cody to prevent drowning you in implementation details. But the problem is that on the second instantiation of WebSocket(), this.urlMap[serverURL] is undefined, and the websocket is then never attached.

I have to recreate the websocket server in the middle of my test to make it work, which is not ideal.

johanlajili avatar Sep 10 '20 17:09 johanlajili

Hi @johanlajili !

That’s expected, the server socket is indeed closed after an error. You’ll have to instantiate a new WS object before your advanceTimersByTime call.

That behaviour is as close as possible to a “real “ server. What behaviour were you expecting?

romgain avatar Sep 10 '20 17:09 romgain

Sorry forgot to reply to that. Yeah that is indeed what we did and that made it work, but would not be the behaviour i'm expecting.

On a real server, i can call websocket.terminate(), which would end the connection with an error message, but that does not mean I need to reinstanciate my whole server with the port listening etc., the client can immediately send a reconnection request.

TBH it's not the end of the world but it did trip me up for a bit of time before I understood what was going on, at the very least now if someone look up that issue on your github they can find it.

johanlajili avatar Sep 17 '20 14:09 johanlajili

Hi @johanlajili !

Sorry for the super late answer. After thinking about this some more, I think you're right. We could add a autoRestart config option to the WS constructor to automatically restart the instance after .stop() or .error().

Is that something you'd be interested in working on ?

Thanks again for your feedback!

romgain avatar Jan 21 '21 11:01 romgain