How to test liveview page with async_nolink interactions?

Howdy

I’ve been having some problems to test async_nolink function.
My mount have a function like that:

Task.Supervisor.async_nolink(TaskSupervisor, fn ->
    Accounts.get_dashboard(user.id)
end)

And I have a handle_info like that:

def handle_info({task_ref, dashboard_data}, socket) do
    Process.demonitor(task_ref, [:flush])
    {:noreply, assign(socket, dashboard_data)}
  end

It is working pretty well but when I test and send my message like that:

{:ok, live, _html} = live(conn, ~p"/")
send(live.pid, {task_ref?, %{total_users: 100}})

What I should put inside my task_ref during tests?

You can’t do it like that as the live view process is getting a process monitor when it starts the Task using the task supervisor. That is why it demonitors it once it gets the Account results.

You can probably use Mock for the Accounts.get_dashboard() call to return the canned response and all the process messaging will work the same.

1 Like

Hmmm I got it
When I tried this approach I had to add a Process.sleep to the test have time to get the data and to be able to do the asserts.

Thanks to share your thoughts :smiley:

If you want to do asynchronous assigns, you should probably be using assign_async
https://hexdocs.pm/phoenix_live_view/Phoenix.LiveView.html#assign_async/3

More info:

3 Likes

Beautiful.
It worked so well thank you!

1 Like