How to simulate LiveView socket reconnection

A tip for my future self!

When testing LiveViews, it is often useful to test what happens on socket disconnection-reconnection. This cycle is what happens when a new deployment goes live, and when a browser tab wakes up from suspended state (which browsers do to save battery/resources).

There are so many ways to do it, but one neat trick is to crash the LiveView process by sending it an event it doesn’t handle. From the browser console:

liveSocket.js().push(liveSocket.main.el, "crash")

For completeness, you may also explicitly disconnect and connect the socket:

liveSocket.disconnect()
// and some time later...
liveSocket.connect()

And if you want to “drive it” from the server side, you can make the LiveView process exit. The tools available at an IEX shell include:

lvs = Phoenix.LiveView.Debug.list_liveviews()
# find the actual LiveView you want to target
lv = Enum.at(lvs, 0)
Process.exit(lv.pid, :kill)

And if you have LiveDashboard in the project, you can filter through the process list and click a button to kill the process, also causing the client to reconnect and spawn a new LiveView process.

6 Likes