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! ![]()






















