Skip to content

Commit

Permalink
Fix formatting found elements with nested children (#9)
Browse files Browse the repository at this point in the history
As part of its assertion error messages, PhoenixTest outputs HTML
elements that match the query selector but do not
contain the requested text. Currently it only works for elements that
only contain one child, and breaks otherwise. It
is sometimes useful to assert that a word will be present in a complex
structure (maybe generated, like the modal popup
from `PetalComponents`) without coupling the code too much to the
internal DOM of the structure.

Proposal: allow complex structures but not assuming only one child by
default, and use `Floki.raw_html(content, pretty: true)` to render the
error message.
  • Loading branch information
soundmonster authored Feb 7, 2024
1 parent 7de6684 commit 7151834
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 1 deletion.
6 changes: 5 additions & 1 deletion lib/phoenix_test/assertions.ex
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,10 @@ defmodule PhoenixTest.Assertions do
end

defp format_found_element({tag, _attrs, [content]}) do
"<#{tag}> with content #{inspect(content)}"
"<#{tag}> with content \"#{Floki.raw_html(content)}\""
end

defp format_found_element({tag, _attrs, content}) when is_list(content) do
"<#{tag}> with content:\n#{Floki.raw_html(content, pretty: true)}"
end
end
28 changes: 28 additions & 0 deletions test/phoenix_test/assertions_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,34 @@ defmodule PhoenixTest.AssertionsTest do
conn |> assert_has("h1", "Super page")
end
end

test "raises error if element cannot be found and selector matches a nested structure", %{
conn: conn
} do
conn = visit(conn, "/page/index")

msg = """
Could not find element with text "Frodo".
Found other elements matching the selector "#multiple-items":
<ul> with content:
<li>
Aragorn
</li>
<li>
Legolas
</li>
<li>
Gimli
</li>
"""

assert_raise RuntimeError, msg, fn ->
conn |> assert_has("#multiple-items", "Frodo")
end
end
end

describe "refute_has/3" do
Expand Down

0 comments on commit 7151834

Please sign in to comment.