testing delete in liveview.
this is my element in component:
<div id={"row-#{@row.id}"}>
.
.
.
.
<div>
.
.
.
<strong>
<%= link “Delete” to: “#”, phx_click: “delete”, phx_value: row.id, data: [confirm: “Are you sure?”] %>
</strong>
</div>
</div>
and this is my test:
test "deletes row in listing", %{conn: conn, row: row} do
{:ok, index_live, _html} = live(conn, Routes.row_index_path(conn, :index))
assert index_live
|> element("#row-#{row.id} a", "Delete")
|> render_click()
refute has_element?(index_live, "#row-#{row.id}")
end
error:
Expected false or nil, got true
code: refute has_element?(index_live, "#row-#{row.id}")
Have you tried it with a button instead of a link?
< button
type="submit"
phx-target="<%= @myself %>"
phx-click="delete"
phx-value="<%= row.id %>"
data-confirm="Are you sure?" >
Delete
</button>
Does your component work when you test it manually?
Then what does your handle_event("delete", values, socket)
look like?
If you give us some more info about your component and assigns we can help you out better.
i tried using a button but it didn’t work, and returned ** (FunctionClauseError) no function clause matching in StoreWeb.RowLive.Index.handle_event/3
i tested manually on my browser and it works fine, row gets deleted no problem.
this is my handle event:
@impl true
def handle_event("delete", %{"id" => id}, socket) do
row = Catalog.get_row!(id)
{:ok, _} = Catalog.delete_row(row)
{:noreply, assign(socket, :row, list_rows())}
end
My apologies
please ignore that error since I didn’t realize that phx-target=<%= @myself %>
works only for when a handle_event/3
is inside a :live_component
module and not a :live_view
module.
Have you ever found a way for the test to also click “confirm” on the pop up modal that the browser creates with the data-confirm
attribute?
It’s what’s possibly blocking your row
from being completely removed during the test. Since the test is clicking on the delete button but is missing the click for the confirmation modal; unlike the way that you are doing it manually where you click both delete and confirm buttons, therefore the element is not removed and your test keeps failing.
Plus I haven’t seen in the LiveView docs says anything about testing pop ups that are created by the browser through the data-*
attribute types. Maybe someone here can shine light on this or point us to helpful resource? Or add it in to a future LiveView version if something like this doesn’t exist yet?