coladarci

coladarci

LiveView isolated Component Tests?

Hello, all!

I’m curious if anyone has ideas/experience around the best ways to go about testing live view components. Obviously you can write a test for the live route that loads up the full page, start clicking things, etc, but for a complicated setup with many stateful components, it’s extremely difficult to reach good coverage from testing that high up.

In ember (and I’m sure other front-end frameworks) there are testing practices where you can render a component on its own (the equivalent of an ephemeral live route?) and interact with it asserting along the way that the right things happen. This helps assert strong contracts; i.e what happens if you embed a component with a specific field set to nil; does the component handle it correctly.

Is there are a way to do this? Does this sound like a good path for the framework to go down? A (terrible?) hack would be a /testing scope in the router that is used to just embed a single component on the page and we’d manually add one for each component, but that might give an idea of roughly what we’d want to automate in a testing routine..

Marked As Solved

mcrumm

mcrumm

Phoenix Core Team

With a little bit of setup you can definitely drive a LiveComponent under test without a library.

I will share an example and an explanation of how I got there, but it should be noted that I don’t use LiveComponent very often so this may not meet your every need :slight_smile:

Explanation

A common pattern used in the LiveView tests themselves is to create a LiveView that you can drive under test, for example:

defmodule MyLiveTest do

  use MyApp.ConnCase, async: true
 import Phoenix.LiveViewTest

  defmodule DemoLive do
    use Phoenix.LiveView

    def render(assigns) do
    ~H"""
    <p>the answer: <%= @the_answer %></p>
    """

    def mount(_, _, socket) do
      {:ok, assign(socket, :the_answer, nil)}
    end

    def handle_call({:run, func}, _, socket) when is_function(func, 1) do
      func.(socket)
    end

    ## Test Helpers

    def run(lv, func) do
      GenServer.call(lv.pid, {:run, func})
    end
  end

  test "test assign/3", %{conn: conn} do
    {:ok, lv, _html} = live_isolated(conn, DemoLive)

    DemoLive.run(lv, fn socket ->
      {:reply, :ok, assign(socket, :the_answer, 42)}
    end)

    assert render(lv) =~ "the answer: 42"
  end
end

We can use the run/2 function to execute code on the LiveView process, so it’s capable of doing a lot of heavy lifting.

Note: Adding a run function/callback as in the example above is an anti-pattern for testing real LiveViews. Avoid reaching into the LiveView process state in your tests.

If we pair this with LiveView lifecycle events, we can intercept messages to the LiveView under test as well:

test "intercepts a message", %{conn: conn} do
  {:ok, lv, _html} = live_isolated(conn, DemoLive)

  test_pid = self()

  DemoLive.run(lv, fn socket ->
    socket =
      Phoenix.LiveView.attach_hook(socket, :interceptor, :handle_info, fn
        {:intercept_me, term}, socket ->
          send(test_pid, {:intercepted, term})

          # :halt prevents handle_info/2 from being invoked on the LiveView for this message.
          {:halt, socket}

        _other, socket ->
          # :cont allows handle_info/2 to be invoked on the LiveView for this message.
          {:cont, socket}
      end)

    {:reply, :ok, socket}
  end)

  ref = make_ref()

  send(lv.pid, {:intercept_me, ref})

  assert_receive {:intercepted, ^ref}
end

So if we can construct a custom LiveView that renders a dynamic LiveComponent, then we can drive the isolated LiveComponent under test :slight_smile:

Example

This gist has a complete example: Testing Phoenix.LiveComponent in Isolation · GitHub

The LiveComponentTest support module defined in the gist exposes three functions:

  • live_component_isolated/3 - Starts a LiveView process dedicated to driving the LiveComponent under test. You pass in the conn, the LiveComponent module, and any attributes.

  • live_component_intercept/2 - Attaches a lifecycle hook to the :handle_info stage of the driver process. Use this to intercept messages from the LiveComponent. You can send the results back to the test pid to assert on them. Returns an opaque ref that can be used to remove the intercept if needed.

  • live_component_remove_intercept/1 - Removes a previously added intercept.

Overall, I think this approach provides a lot of flexibility. With some additional work under-the-hood I think instead of intercept it could expose macros like assert_lv_receive, but I will leave that for someone else to explore for now :slight_smile:

I hope that helps!

10
Post #6

Also Liked

mcrumm

mcrumm

Phoenix Core Team

You can use live_isolated/3 to test a LiveView in isolation, but it’s recommended to test through the router (i.e. using the live/2 test helper) as that is required to test live navigation.

Note there is also render_component/3 for testing function and stateful components in isolation.

nicocirio

nicocirio

Hi! Thanks for this great solution! In my case, I also needed to intercept events that were targeted to the parent LiveView (in cases where the LiveComponent does not define phx-target={@myself} for a specific event). Adding the following function to live_component_tests.ex helped me test that behavior:

@doc """
  Intercepts events on the LiveComponentTest LiveView.
  Use this function to intercept events sent by the LiveComponent to the LiveView (when phx-target={@myself} is NOT defined).
  ## Examples
      {:ok, lcd, _html} = LiveComponentTest.live_component_isolated(conn, MyLiveComponent)
      test_pid = self()
      live_component_event_intercept(lv, fn
          "some_event_name" =  event, %{"some" => "example_params"} = params, socket ->
            send(test_pid, {:handle_event_intercepted, event, params})
            {:halt, socket}
          _other, _params, socket ->
            {:cont, socket}
      end)
      assert_received {:handle_event_intercepted, "some_event_name", %{"some" => "example_params"}}
  """
  def live_component_event_intercept(lv, func) when is_function(func) do
    Driver.run(lv, fn socket ->
      name = :"lv_event_intercept_#{System.unique_integer([:positive, :monotonic])}"
      ref = {:event_intercept, lv, name, :handle_event}
      {:reply, ref, Phoenix.LiveView.attach_hook(socket, name, :handle_event, func)}
    end)
  end

Hope this function is helpful for others! :slight_smile:

APB9785

APB9785

Creator of ECSx

Maybe this library could be helpful also?

Last Post!

kamaroly

kamaroly

For those who are still looking for a solution,
I found the following package helpful: Overview — live_isolated_component v0.10.0

Where Next?

Popular in Questions Top

vegabook
I’m brand new to Phoenix and I have stripped one of the demo applications to the bone. I just want to get an svg up on the screen. Here i...
New
minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
New
skosch
To my knowledge, put_in, Map.update etc. all have the one limitation of not automatically creating intermediate keys when needed (for exa...
New
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New
aalberti333
As the title describes, I’m trying to run Enum.map() over a list of key/value pairs, where the value is a map. My data looks like this: ...
New
siddhant3030
Hi, I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw ...
New
Harrisonl
We have an ECS cluster with 4 services, where each task joins a single cluster, via discovery ECS discovery service. Currently when I de...
New

Other popular topics Top

nobody
Hi! In PHP: $_SERVER[‘SERVER_ADDR’] - in Elixir? Searched the docs for ip address and the web, no good results. Thanks!
New
hariharasudhan94
I would like to know what is the best IDE for elixir development?
New
gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
bsollish-terakeet
Credo is smart enough to check for (something like) this: assert length(the_list) == 0 with this response: Checking if an enum is empt...
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New
AstonJ
Posting this to see if we can make things easier for people to get into Neovim. If you use Neovim and have a favourite distro please let ...
New

We're in Beta

About us Mission Statement