From 5854969a329ec914807e17fda384a8a145b5b0a2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jouni=20M=C3=A4kel=C3=A4?= Date: Wed, 5 Jun 2024 12:51:18 +0300 Subject: [PATCH] Fix: support links with only query parameters This commit resolves an issue where links containing only query parameters without a specified path would incorrectly direct to the root path instead of the current path, unlike standard browser behavior. Example of a link without a path: English Previously, `click_link/2` would direct to root path. In this commit the link correctly retains the current page while applying the query parameters. --- lib/phoenix_test/link.ex | 10 ++++++++++ lib/phoenix_test/static.ex | 4 +++- test/phoenix_test/static_test.exs | 7 +++++++ test/support/page_view.ex | 2 ++ 4 files changed, 22 insertions(+), 1 deletion(-) diff --git a/lib/phoenix_test/link.ex b/lib/phoenix_test/link.ex index c26e8aef..2370ebee 100644 --- a/lib/phoenix_test/link.ex +++ b/lib/phoenix_test/link.ex @@ -28,4 +28,14 @@ defmodule PhoenixTest.Link do |> Html.attribute("data-method") |> Utils.present?() end + + def maybe_append_path(link, path) do + link.href + |> URI.parse() + |> Map.replace_lazy(:path, fn + nil -> path + current_path -> current_path + end) + |> URI.to_string() + end end diff --git a/lib/phoenix_test/static.ex b/lib/phoenix_test/static.ex index 178f8c04..ac67f420 100644 --- a/lib/phoenix_test/static.ex +++ b/lib/phoenix_test/static.ex @@ -70,7 +70,9 @@ defmodule PhoenixTest.Static do |> dispatch(@endpoint, form.method, form.action, form.data) |> maybe_redirect(session) else - PhoenixTest.visit(session.conn, link.href) + path = Link.maybe_append_path(link, session.conn.request_path) + + PhoenixTest.visit(session.conn, path) end end diff --git a/test/phoenix_test/static_test.exs b/test/phoenix_test/static_test.exs index 14befa52..df8548a5 100644 --- a/test/phoenix_test/static_test.exs +++ b/test/phoenix_test/static_test.exs @@ -77,6 +77,13 @@ defmodule PhoenixTest.StaticTest do |> assert_has("h1", text: "LiveView main page") end + test "handles links with query parameters and no path", %{conn: conn} do + conn + |> visit("/page/index") + |> click_link("English") + |> assert_has("h1", text: "Main page") + end + test "handles form submission via `data-method` & `data-to` attributes", %{conn: conn} do conn |> visit("/page/index") diff --git a/test/support/page_view.ex b/test/support/page_view.ex index 2316f34c..e7515aef 100644 --- a/test/support/page_view.ex +++ b/test/support/page_view.ex @@ -41,6 +41,8 @@ defmodule PhoenixTest.PageView do To LiveView! + English +