elixirphoenix-frameworkex-unitphoenix-live-view

How to use render_change result to match specific element?


I'm testing LiveView form with render_change/2

html = 
  view 
  |> element("#filter-form") 
  |> render_change(%{filter: %{days: "14"}})

The result I get is a string containing rendered html.

I want to assert that the result has some specific element. It could be done with element/2 function like this

assert view |> element("#target", "test") |> has_element?()

but it only accepts the LiveView's instance, not a html string.

What would be the best approach to assert that a render_change/2 result would have a certain tag with specific text?


Solution

  • There are three main ways in which you could verify this.

    The first and simplest one would be to compare the updated HTML with some specific text from your element. So, something like:

    html =
      view
      |> element("#filter-form")
      |> render_change(%{filter: %{days: "14"}})
    
    assert html =~ "my specific text"
    

    Another one would be to use Floki to parse the HTML and find the element you want, like:

    html =
      view
      |> element("#filter-form")
      |> render_change(%{filter: %{days: "14"}})
    
    assert [element] =
      html
      |> Floki.parse_document!()
      |> Floki.find("#target")
    

    And with that element you could also verify specific properties.

    And the last one would be exactly what you suggested. The view that is used in LiveView tests is a reference for something that processes the events. So, when you call the render_* test helper functions, the state of that changes. So:

    assert view |> element("#target", "test") |> has_element?()
    

    Should usually work.