How to test LiveView state/html received via PubSub

I have a LiveView that starts a GenServer on mount. This GenServer loads data and at some point broadcasts a message to a topic that the LiveView is subscribed to.

How to write tests for this?

  test "displays company name", %{conn: conn} do
    {:ok, view, html} =
      live_isolated(conn, MyLiveView, session: %{"customer_id" => "5013"})

    assert html =~ "Company Name"

Company Name is rendered after the PubSub message is received. But the live_isolated in the test gives me the html right after mount. So how can I get the new html in the test?

Ok, I think I got this by myself. There is also Phoenix.LiveViewTest.render/1

wait_until(fn ->
  assert render(view) =~ "Company Name"
1 Like

I ran into this same problem and wanted to try your solution, but the funciton wait_until does not seem to be a liveview function… I get an undefined function error.

He’s the implementation. You will need to import it in your test

defmodule TimeHelper do
  def wait_until(fun), do: wait_until(1_000, fun)

  def wait_until(0, fun), do: fun.()

  def wait_until(timeout, fun) do
    try do
      ExUnit.AssertionError ->
        wait_until(max(0, timeout - 10), fun)