14

How do I simulate a websocket disconnect manually? I'm trying to test websocket reconnect logic, and I have no way of doing this other than waiting for the browser's 10 minute websocket timeout.

dessalines
  • 6,352
  • 5
  • 42
  • 59

2 Answers2

1

With SockJS and Stomp:

socket = new SockJS(socketUrl);
stompClient = Stomp.over(socket); // global variable stompClient

Closing the underlying socket with:

socket.close();

triggered the stompClient's error handler as if the connection had been interrupted.

Markus Pscheidt
  • 6,853
  • 5
  • 55
  • 76
0

I found a solution to test this here: https://stackoverflow.com/a/59916046/2929675

Before the WebSocket connection gets opened, you must execute this script to monkey patch the browsers WebSocket function:

const sockets = [];
const nativeWebSocket = window.WebSocket;
window.WebSocket = function(...args){
  const socket = new nativeWebSocket(...args);
  sockets.push(socket);
  return socket;
};

Now you have access to all WebSocket connections via the sockets array. And when you want to trigger a reconnect, you can call

sockets[0].close();

using the index of the connection you want to close.

It's a bit hacky, but it's the best solution I have found so far.

It looks like there is also some progress in the chromium issue to support this in the dev tools: https://bugs.chromium.org/p/chromium/issues/detail?id=423246

berhir
  • 1,401
  • 1
  • 10
  • 7