coladarci

coladarci

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..

Showing Posts 1 to 10

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.

coladarci

coladarci OP

giggity! Thanks @mcrumm

APB9785

APB9785

Creator of ECSx

Maybe this library could be helpful also?

coladarci

coladarci OP

This is very helpful - so @mcrumm it sounds like render_component is what I want except that it only renders it; it doesn’t let you interact with it and test the result. @APB9785 's link to live_isolated appears to do what I’m after - is there no way to do that w/out a library at this point, to know your knowledge?

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 #5
coladarci

coladarci OP

Just want to thank you for this extremely thorough response and example - this is exceptional. In my experience outside of live view, this is the way to think about testing a complicated live view app; your components are like functions and you want to write them to be easily testable in isolation to cover all the edge cases they have to handle. It’s wonderful to know it’s possible, and with your macros, straight-forward :slight_smile:

Once again, appreciate all you do!

coladarci

coladarci OP

UPDATE: I got it but leaving here for posterity. Just some confusing meta programing warnings that go away when I completed the test that uses live_component_intercept.. Thanks, again!

As an FYI, the code you provided seems to work great locally, though the macro is throwing a warning on this line: Testing Phoenix.LiveComponent in Isolation · GitHub

warning: this check/guard will always yield the same result

I’m having a hard time figuring out why but will keep digging!

mcrumm

mcrumm

Phoenix Core Team

Ah, it was the default attrs on the macro. I updated the gist to use an empty list instead of nil and that seems to have resolved it. :slight_smile: Thanks for pointing that out!

coladarci

coladarci OP

Just want to followup here and say this is working quite nicely for us. The only thing that is a bit difficult is debugging with open_browser/1 since it’s not rendering the root template; we lose the styling. Is there an easy way in your mind to change

    def render(assigns) do
      ~H"""
      <.live_component :if={@lc_module} module={@lc_module} {@lc_attrs} />
      """
    end

in the driver to render this inside the root template? :grin:

mwhitworth

mwhitworth

Thanks for this - I can confirm live_isolated_component does the trick and works great for this use case!

Where Next? Top

Trending in Questions Top

stjefim
Hello! Suppose you are building workflow (order / task / payment) processing system with the following requirements: Each workflow con...
New
Blokh
Hey guys, I’ve got a huge CSV ( around 10 GB ) that needs to be processed hourly Do you guys have any suggestions what is the best prac...
New
roeland
Kia ora, We have been using elixir-google-api to connect to Google Drive. However, with the updates to Tesla due to CVEs this is now bro...
New
kszambelanczyk
Hello! Could someone please give me a help/sample code, how to delete a file from s3 using waffle/waffle_ecto from Phoenix app. I creat...
New
Onor.io
I have what I’ve heard referred to as a “lookup table” in my database. This is a way of assigning codes to common values. One common lo...
New
jaybe78
Hello, I’m developing a online persistent chat system (what’s app) like using elixir/dynamodb/aws for a mobile app(flutter). The diffic...
New
Trolleger
What approach to take when sending live updates to “random” users Hi! I have a question, I have a little chat app, and when I create a DM...
New

Other Trending Topics Top

garrison
Hobbes is a low-level distributed database for the Elixir programming language. Hobbes provides a simple, safe, and scalable storage lay...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
mcass19
ExRatatui lets you cook up rich terminal UIs in Elixir, powered by Rust’s ratatui via Rustler NIFs. Build interactive terminal applicatio...
New
Damirados
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge &amp; Solve. They are GUI (Emerge) and State management (S...
New
netoum
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New
wintermeyer
There are three potential reasons for members of this forum to have a look at https://vutuv.de You are tired or annoyed of LinkedIn. Yo...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews