-
-
Save msimonborg/dfcb7f21ef02111f04a8c9303c34ec60 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule AppWeb.Router do | |
# ... | |
scope "/", AppWeb do | |
pipe_through :browser | |
live "/test", TestLive | |
end | |
end | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule AppWeb.TestComponent do | |
use AppWeb, :live_component | |
def render(assigns) do | |
~H""" | |
<div> | |
<.form let={_f} for={:form} action="#" phx-submit="submit"> | |
<%= submit("submit") %> | |
</.form> | |
<%= if @redirected do %> | |
<p>redirected</p> | |
<% end %> | |
</div> | |
""" | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule AppWeb.TestLive do | |
use AppWeb, :live_view | |
@impl true | |
def render(assigns) do | |
~H""" | |
<.live_component module={AppWeb.TestComponent} id={1} {assigns}/> | |
""" | |
end | |
@impl true | |
def mount(_params, _session, socket) do | |
socket = | |
socket | |
|> assign_defaults() | |
|> assign_new(:redirected, fn -> false end) | |
{:ok, socket, layout: false} | |
end | |
defp assign_defaults(socket) do | |
attach_hook(socket, :set_current_url, :handle_params, fn | |
_params, url, socket -> | |
uri = URI.parse(url) | |
if uri.query do | |
{:cont, assign(socket, current_url: uri.path <> "?" <> uri.query)} | |
else | |
{:cont, assign(socket, current_url: uri.path)} | |
end | |
end) | |
end | |
@impl true | |
def handle_event("submit", _, socket) do | |
if socket.assigns.current_url do | |
{:noreply, assign(socket, :redirected, true)} | |
else | |
{:noreply, socket} | |
end | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule AppWeb.TestLiveTest do | |
use AppWeb.ConnCase | |
import Phoenix.LiveViewTest | |
test "renders redirected", %{conn: conn} do | |
{:ok, view, html} = live(conn, Routes.live_path(conn, AppWeb.TestLive)) | |
assert html =~ "submit" | |
refute html =~ "redirected" | |
view | |
|> element("form") | |
|> render_submit() | |
assert render(view) =~ "redirected" | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment