germsvel / phoenix_test

PhoenixTest provides a unified way of writing feature tests -- regardless of whether you're testing LiveView pages or static (non-LiveView) pages.
https://hex.pm/packages/phoenix_test
MIT License
181 stars 23 forks source link

Proposal: build with `live_isolated` to unit test live_components #56

Open totaltrash opened 7 months ago

totaltrash commented 7 months ago

This might be a bit out of scope for phoenix_test, but thought I would ask!

I'd like to use phoenix_test to unit test live_components - unit test as in testing a live component that is not routable and not accessible using visit.

The strategy I'm using is to define a live view in my test, something like this works well:

defmodule Test.MyComponent do
  use Test.FeatureCase
  import Phoenix.LiveViewTest

  defmodule WrapperLive do
    use Phoenix.LiveView

    def render(assigns) do
      ~H"""
      <.live_component module={MyComponent} id="test" />
      """
    end
  end

  test "my component", %{conn: conn} do
    # Might be nice to have this available in PhoenixTest?:
    {:ok, view, _} = live_isolated(conn, WrapperLive)
    session = %PhoenixTest.Live{view: view, conn: conn}

    session
    |> fill_form("#blah", %{title: "stuff"})
    |> assert_has(...)
  end
end

Just wondering if you would accept a PR to add PhoenixTest.Live.build_isolated(conn, module) that would do something similar to PhoenixTest.Live.build, and optionally add a PhoenixTest.build_isolated(conn, module) so it's available in the main test module? Then the test could look something like:

  test "my component", %{conn: conn} do
    conn
    |> build_isolated(WrapperLive)
    |> fill_form("#blah", %{title: "stuff"})
    |> assert_has(...)
  end
germsvel commented 7 months ago

Hey @totaltrash thanks for opening this issue! Testing isolated LiveComponents can be such a pain (usually I test them through their parent LiveView). But it would be great to be able to support this somehow.

Let me think about how we could expose this nicely. I'm not a huge fan of the idea of build_isolated because it sounds specific to LiveView. But I wonder if there's a way to create an entry point (outside of visit) that would allow us to use PhoenixTest like you're thinking.

totaltrash commented 7 months ago

Thanks @germsvel, yes it's a LiveView only thing, that's why I thought it might be considered out of scope. But, PhoenixTest has such a nice api, I can't use anything else now.