arcanemachine
Testing LiveView and Presence: How to simulate a user has left (e.g. closed tab)
I have a LiveView that tracks how many users are viewing another page. The other page is using Presence to track when users enter and leave. Everything works fine during manual testing.
For my tests, I need to simulate that a user has left the page (closed tab, clicked a link, etc.) so that they no longer appear in the list of users being tracked. I am unable to simulate such an event in my Elixir test code.
In my Elixir test code, how can I simulate that a LiveView user has exited the page?
EDIT: I can use render_click/2 to click a link that happens to be in the view and that does the trick for now, but hopefully there’s something a little less hacky that I can use.
Marked As Solved
arcanemachine
Finally got it! GenServer.stop(view.pid()) did the trick.
Also Liked
LostKobrakai
The issue is that two things are started. A LV client and a channel for communication. Both seem to be linked to the test process. Most of that stuff is private though. stop_supervised(view.pid) seems to work, though with a warning. I’d argue that LV should provide an API to close a view.
adw632
To simulate a user being unauthenticated and disconnected in all liveviews and channels you can do:
MyAppWeb.Endpoint.broadcast("users_socket:#{user.id}", "disconnect", %{})
This covered in the documentation here Disconnecting all instances of a live user.
sodapopcan
You could always just kill the process:
{:ok, lv, _html} = live(conn, ~p"/the-page")
Process.exit(lv.pid, :kill)
If there is a cleaner way I am not sure.








