3
votes

Greetings Phoenix LiveView Wizards! ????

Context

We have a basic LiveView counter app: https://github.com/dwyl/phoenix-liveview-counter-tutorial
The code is very simple: /live/counter.ex
The App works as expected, see: https://live-view-counter.herokuapp.com

The test file is: test/live_view_counter_web/live/counter_test.exs
We are stuck with trying to invoke the handle_info/2 function in a test.
So we have code in our project that is untested. Which is undesirable.
See: https://codecov.io/gh/dwyl/phoenix-liveview-counter-tutorial/src/master/lib/live_view_counter_web/live/counter.ex

counter-not-covered

We have read through the official docs https://hexdocs.pm/phoenix_live_view/Phoenix.LiveViewTest.html
but have not been able to understand how to do it. What are we missing?

We really want to use LiveView in our "real" projects, but we want to ensure that our LiveView apps are fully tested.

Question

How do we write a test to invoke the handle_info/2 function?

2
Could you elaborate on what exactly here is unclear?Aleksei Matiushkin
@AlekseiMatiushkin thanks for your quick reply. It was unclear how to setup the test file and then invoke the handle_event/3 function. But from re-reading the docs, it appears we do not invoke the function directly rather it is invoked indirectly by the render_click(view, :inc) 👍(thank you for helping us come to this realisation ...)nelsonic
handle_event/3 is a callback for the message arrived to the LV process, which means one does not ever want to test it via direct call.Aleksei Matiushkin
Updated the question to reflect the challenge of testing the handle_info/2 function.nelsonic

2 Answers

3
votes

After much research, trial and error, error, error (iteration), we came up with the following test:

test "handle_info/2", %{conn: conn} do
  {:ok, view, disconnected_html} = live(conn, "/")
  assert disconnected_html =~ "Count: 0"
  assert render(view) =~ "Count: 0"
  send(view.pid, %{payload: %{ val: 1 }})
  assert render(view) =~ "Count: 1"
end

Thanks to @daniel for pointing us in the direction of the send/2 function.
and @AlekseiMatiushkin for patiently asking probing questions above. 👍 Thanks to @chrismccord for the insight: https://elixirforum.com/t/how-to-test-handle-info-2-in-phoenix-liveview/30070/7

1
votes

handle_info/2 is a general behavior of Genserver. If you read documentation, you can find:

Besides the synchronous and asynchronous communication provided by call/3 and cast/2, "regular" messages sent by functions such as Kernel.send/2, Process.send_after/4 and similar, can be handled inside the handle_info/2 callback.

So you can send either of those as long as you know the pid of the process.