How do I write tests for dropdowns?

I have a use case scenario where I need to update my user after a click event from option tag like below!

What I’m doing is that I have a click event in each of the options and when there is a click, the user’a role is updated. While it’s easy to code something like this, how do I write live view tests for this?

Hi, super late response here but I was looking for the same thing and this was the first post that came up. In my case it wasn’t even Javascript- I just wanted to test contents inside a <details> tag.

So this kind of thing can’t be tested in Phoenix (see Testing LiveView with JS Commands - #2 by sodapopcan). All of the helpers (eg render_click) are triggering server-side changes in Liveview. If your change requires some client-side handling, it can’t be tested.

1 Like

Just a caveat, while this kind of thing can’t be tested directly with Phoenix.LiveViewTest, you can still test client side interactions in Phoenix with integration testing and browser automation libraries such as Wallaby and Hound.

2 Likes

Thank you so much for the responses @codeanpeace and @dfalling

Some time ago I discovered that some support for JS commands has been around for a while now. You can test push events in your JS commands. So this kind of tests works:

heex:

<div :if={@clicked}>Clicked!</div>
<button id="clickez-moi" phx-click={JS.push("clicked")} class="btn">Test</button>

live view:

def handle_event(
        "clicked",
        _,
        socket
      ) do
    {:noreply, assign(socket, clicked: true)}
end

test:

test "test js command", %{view: view} do
      element(view, "#clickez-moi")
      |> render_click()

      assert has_element?(view, "div", "Clicked!")
end

You can’t test other commands that purely operate on the DOM on the client side this way (such as add_class) but you can test events sent to the server. This is very nice!

1 Like