defmodule PhoenixTest do @moduledoc """ PhoenixTest provides a unified way of writing feature tests -- regardless of whether you're testing LiveView pages or static pages. It also handles navigation between LiveView and static pages seamlessly. So, you don't have to worry about what type of page you're visiting. Just write the tests from the user's perspective. Thus, you can test a flow going from static to LiveView pages and back without having to worry about the underlying implementation. This is a sample flow: ```elixir test "admin can create a user", %{conn: conn} do conn |> visit("/") |> click_link("Users") |> fill_in("Name", with: "Aragorn") |> choose("Ranger") |> assert_has(".user", text: "Aragorn") end ``` Note that PhoenixTest does _not_ handle JavaScript. If you're looking for something that supports JavaScript, take a look at [Wallaby](https://hexdocs.pm/wallaby/readme.html) or the external [PhoenixTest.Playwright](https://hexdocs.pm/phoenix_test_playwright) driver. ## Setup PhoenixTest requires Phoenix `1.7+` and LiveView `1.0+`. It may work with earlier versions, but those are "officially" supported. ### Installation Add `phoenix_test` to your list of dependencies in `mix.exs`: ```elixir def deps do [ {:phoenix_test, "~> 0.8.2", only: :test, runtime: false} ] end ``` ### Configuration In `config/test.exs` specify the endpoint to be used for routing requests: ```elixir config :phoenix_test, :endpoint, MyAppWeb.Endpoint ``` ### Getting `PhoenixTest` helpers `PhoenixTest` helpers can be included via `import PhoenixTest`. But since each test needs a `conn` struct to get started, you'll likely want to set up a few things before that. There are two ways to do that. ### With `ConnCase` If you plan to use `ConnCase` solely for `PhoenixTest`, then you can import the helpers there: ```elixir using do quote do # importing other things for ConnCase import PhoenixTest # doing other setup for ConnCase end end ``` ### Adding a `FeatureCase` If you want to create your own `FeatureCase` helper module like `ConnCase`, you can copy the code below which can be `use`d from your tests (replace `MyApp` with your app's name): ```elixir defmodule MyAppWeb.FeatureCase do use ExUnit.CaseTemplate using do quote do use MyAppWeb, :verified_routes import MyAppWeb.FeatureCase import PhoenixTest end end setup tags do pid = Ecto.Adapters.SQL.Sandbox.start_owner!(MyApp.Repo, shared: not tags[:async]) on_exit(fn -> Ecto.Adapters.SQL.Sandbox.stop_owner(pid) end) {:ok, conn: Phoenix.ConnTest.build_conn()} end end ``` Note that we assume your Phoenix project is using Ecto and its phenomenal `SQL.Sandbox`. If it doesn't, feel free to remove the `SQL.Sandbox` code above. ## Usage Now that we have all the setup out of the way, we can create tests like this: ```elixir # test/my_app_web/features/admin_can_create_user_test.exs defmodule MyAppWeb.AdminCanCreateUserTest do use MyAppWeb.FeatureCase, async: true test "admin can create user", %{conn: conn} do conn |> visit("/") |> click_link("Users") |> fill_in("Name", with: "Aragorn") |> fill_in("Email", with: "aragorn@dunedain.com") |> click_button("Create") |> assert_has(".user", text: "Aragorn") end end ``` ### Filling out forms We can fill out forms by targetting their inputs, selects, etc. by label: ```elixir test "admin can create user", %{conn: conn} do conn |> visit("/") |> click_link("Users") |> fill_in("Name", with: "Aragorn") |> select("Elessar", from: "Aliases") |> choose("Human") # <- choose a radio option |> check("Ranger") # <- check a checkbox |> click_button("Create") |> assert_has(".user", text: "Aragorn") end ``` For more info, see `fill_in/3`, `select/3`, `choose/3`, `check/2`, `uncheck/2`. ### Submitting forms without clicking a button Once we've filled out a form, you can click a button with `click_button/2` to submit the form. But sometimes you want to emulate what would happen by just pressing . For that case, you can use `submit/1` to submit the form you just filled out. ```elixir session |> fill_in("Name", with: "Aragorn") |> check("Ranger") |> submit() ``` For more info, see `submit/1`. ### Targeting which form to fill out If you find yourself in a situation where you have multiple forms with the same labels (even when those labels point to different inputs), then you might have to scope your form-filling. To do that, you can scope all of the form helpers using `within/3`: ```elixir session |> within("#user-form", fn session -> session |> fill_in("Name", with: "Aragorn") |> check("Ranger") |> click_button("Create") end) ``` For more info, see `within/3`. ## Credo Add `PhoenixTest.Credo.NoOpenBrowser` to your `.credo.exs` config file to prevent dev-only `open_browser/1` from lingering in your code base. """ alias PhoenixTest.ConnHandler alias PhoenixTest.Driver @doc """ Entrypoint to create a session. `visit/2` takes a `Plug.Conn` struct and the path to visit. It returns a `session` which the rest of the `PhoenixTest` functions can use. Note that `visit/2` is smart enough to know if the page you're visiting is a LiveView or a static view. You don't need to worry about which type of page you're visiting. """ def visit(%Plug.Conn{} = conn, path) do ConnHandler.visit(conn, path) end def visit(initial_struct, path) do Driver.visit(initial_struct, path) end @doc """ Clicks a link with given text (using a substring match) and performs the action. Here's how it handles different types of `a` tags: - With `href`: follows it to the next page - With `phx-click`: it'll send the event to the appropriate LiveView - With live redirect: it'll follow the live navigation to the next LiveView - With live patch: it'll patch the current LiveView ## Examples ```heex <.link href="/page/2">Page 2 <.link phx-click="next-page">Next Page <.link navigate="next-liveview">Next LiveView <.link patch="page/details">Page Details ``` ```elixir session |> click_link("Page 2") # <- follows to next page session |> click_link("Next Page") # <- sends "next-page" event to LiveView session |> click_link("Next LiveView") # <- follows to next LiveView session |> click_link("Page Details") # <- applies live patch ``` ## Submitting forms Phoenix allows for submitting forms on links via Phoenix.HTML's `data-method`, `data-to`, and `data-csrf`. We can use `click_link` to emulate Phoenix.HTML.js and submit the form via data attributes. But note that this _doesn't guarantee_ the JavaScript that handles form submissions via `data` attributes is loaded. The test emulates the behavior but you must make sure the JavaScript is loaded. For more on that, see https://hexdocs.pm/phoenix_html/Phoenix.HTML.html#module-javascript-library ### Example ```html Delete ``` ```elixir session |> click_link("Delete") # <- will submit form like Phoenix.HTML.js does ``` """ defdelegate click_link(session, text), to: Driver @doc """ Clicks a link with given CSS selector and text and performs the action. selector to target the link. See `click_link/2` for more details. """ defdelegate click_link(session, selector, text), to: Driver @doc """ Perfoms action defined by button with given text (using a substring match). The action is based on attributes present. This can be used in a number of ways. ## Button with `phx-click` If the button has a `phx-click` on it, it'll send the event to the LiveView. ### Example ```html ``` ```elixir session |> click_button("Save") # <- will send "save" event to LiveView ``` ## Button relying on Phoenix.HTML.js If the button acts as a form via Phoenix.HTML's `data-method`, `data-to`, and `data-csrf`, this will emulate Phoenix.HTML.js and submit the form via data attributes. But note that this _doesn't guarantee_ the JavaScript that handles form submissions via `data` attributes is loaded. The test emulates the behavior but you must make sure the JavaScript is loaded. For more on that, see https://hexdocs.pm/phoenix_html/Phoenix.HTML.html#module-javascript-library ### Example ```html ``` ```elixir session |> click_button("Delete") # <- will submit form like Phoenix.HTML.js does ``` ## Combined with `fill_in/3`, `select/3`, etc. This function can be preceded by filling out a form. ### Example ```elixir session |> fill_in("Name", name: "Aragorn") |> check("Human") |> click_button("Create") ``` ### Submitting default data By default, using `click_button/2` will submit the form it's part of (so long as it has a `phx-click`, `data-*` attrs, or an `action`). It will also include any hidden inputs and default data (e.g. inputs with a `value` set and the button's `name` and `value` if present). ### Example ```html
``` ```elixir session |> click_button("Complete") # ^ includes `%{"admin" => "true", "complete" => "true"}` in payload ``` ## Single-button forms `click_button/2` is smart enough to use a hidden input's value with `name=_method` as the method to send (e.g. when we want to send `delete`, `put`, or `patch`) That means, it is helpful to submit single-button forms. ### Example ```html
``` ```elixir session |> click_button("Delete") # <- Triggers full form delete. ``` ## Clicking elements that behave as buttons Even though we can technically add an `onClick` or `phx-click` handler on any HTML element, the HTML spec encourages that clickable elements be links or buttons. But in some cases, people want to have other elements act as buttons even if they don't use a `