Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 38 ยท Testing and Deployment

Testing LiveView

Test LiveViews without a browser: live/2, element, render_click, form render_change and render_submit, has_element?, patch and redirect asserts, PubSub and async.

A LiveView is a stateful process that reacts to events and renders HTML. That makes it surprisingly easy to test: you start the process, send it events as if a user were clicking, and look at the HTML it produces. There is no browser, no JavaScript and no network. The tests run at the speed of ordinary function calls, and they use the same sandbox and fixtures as the controller and context tests.

Real ExUnit code is read-only on this site. The stand-ins model Phoenix.LiveViewTest in JavaScript to show what the helpers do. The test tools live in Phoenix.LiveViewTest, which ConnCase imports for you.

Mounting a LiveView

live/2 performs both the disconnected HTTP render and the connected mount (see the lifecycle) and gives you a handle to the running process:

ELIXIR
defmodule MyAppWeb.CounterLiveTest do
  use MyAppWeb.ConnCase, async: true
  import Phoenix.LiveViewTest

  test "renders the starting count", %{conn: conn} do
    {:ok, view, html} = live(conn, ~p"/counter")

    assert html =~ "Count: 0"
    assert has_element?(view, "#count", "0")
  end

  test "increments on click", %{conn: conn} do
    {:ok, view, _html} = live(conn, ~p"/counter")

    view |> element("button", "+1") |> render_click()

    assert render(view) =~ "Count: 1"
  end
end

Two details. live/2 returns the disconnected HTML as its third element, so you can assert on what search engines would see. And render_click/1 returns the new HTML of the whole view; you can also call render(view) any time to get the current markup.

If you only want the static HTML, use a plain get(conn, ~p"/counter") and html_response/2; if the route redirects (for example to the login page), live/2 returns {:error, {:redirect, %{to: path}}} instead, which you can assert on directly.

Selecting elements

element(view, selector, text_filter \\ nil) finds one element by CSS selector and an optional text match. It raises if there are zero or more than one match, which keeps tests honest. This is why generated templates give important elements ids:

ELIXIR
element(view, "#delete-post-12")          # by id (best)
element(view, "button", "Delete")         # by tag and text
element(view, "a[href='/posts/new']")     # by attribute

Then act on it with render_click/1,2, render_hook/3, render_blur/1, render_keydown/2, and so on, passing extra values where the binding takes phx-value-* attributes. To check what is on the page without acting, use has_element?/2,3 and its negation refute has_element?/3.

Prefer testing what the user sees (text, element presence) over internal assigns. :sys.get_state(view.pid) can peek inside but couples your test to implementation.

Forms: change and submit

Form tests mirror the form cycle: first phx-change for validation, then phx-submit.

ELIXIR
test "shows validation errors while typing", %{conn: conn} do
  {:ok, view, _html} = live(conn, ~p"/posts/new")

  html =
    view
    |> form("#post-form", post: %{title: ""})
    |> render_change()

  assert html =~ "can't be blank"
end

test "creates a post and redirects", %{conn: conn} do
  {:ok, view, _html} = live(conn, ~p"/posts/new")

  {:ok, _view, html} =
    view
    |> form("#post-form", post: %{title: "Hello", body: "World"})
    |> render_submit()
    |> follow_redirect(conn, ~p"/posts/1")   # asserts the target and mounts it

  assert html =~ "Post created"
end

form/3 checks that the field names you pass exist in the rendered form, so a typo (or an input the real form lacks) fails loudly instead of silently testing nothing. Hidden inputs and defaults are filled in as a browser would.

Other navigation assertions: assert_patch(view, path) after a push_patch, assert_redirect(view, path) for a redirect, assert_redirected(view, path) once it has happened, and follow_redirect/2,3 to continue into the next LiveView.

Node.js Clicking and forms without a browser (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Testing PubSub-driven updates

To test that a LiveView reacts to broadcasts, mount it, change data through the context (which broadcasts), and then render. Because the update arrives as a message, render/1 synchronizes: it waits until the view has processed its mailbox.

ELIXIR
test "updates when the order ships", %{conn: conn} do
  order = order_fixture(status: :paid)
  {:ok, view, html} = live(conn, ~p"/orders/#{order}")
  assert html =~ "Paid"

  {:ok, _} = Orders.ship_order(order)

  assert render(view) =~ "Shipped"
end

You can also send a message directly with send(view.pid, {:order_shipped, order}), which is handy for testing a single handle_info/2 clause. Compare this to the PubSub lesson: the test needs no WebSocket, because the view process is right there in the test VM.

Async assigns need one extra call, render_async(view), which waits for assign_async and start_async tasks to finish:

ELIXIR
{:ok, view, html} = live(conn, ~p"/dashboard")
assert html =~ "Loading revenue"
assert render_async(view) =~ "Revenue:"

Testing components and streams

Function components can be rendered in isolation with render_component/2, no process needed:

ELIXIR
test "badge renders its status" do
  html = render_component(&MyAppWeb.CoreComponents.badge/1, status: :published, inner_block: [])
  assert html =~ "badge-success"
end

For a LiveComponent, test it through the page that uses it, or with live_isolated/3, which mounts a LiveView without a route. Streams are tested through the DOM: after a stream insert, has_element?(view, "#messages-12") is the right assertion, because the server holds no list to inspect (see streams).

A test for presence just mounts two views as two users and asserts that each sees the other, then stops one and asserts that it disappears. For JavaScript hooks, LiveViewTest cannot run the JS; use render_hook/3 to simulate the client message, and a browser-level tool (Wallaby or Playwright) for the few end-to-end journeys that must prove the real UI works.

Node.js Two views, one broadcast (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Habits that keep LiveView tests healthy

  • Give interactive elements stable ids and use them in selectors.
  • Assert on visible text and elements, not assigns.
  • Test each handle_event clause, including the unauthorized path (IDOR checks apply to events too).
  • Keep one or two browser-level tests for critical flows, and rely on LiveViewTest for everything else.
  • Use async: true everywhere the sandbox allows it.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does live(conn, path) return on success?

    You get the view process handle and the disconnected HTML; you then drive the view with the handle.
  2. 2. Why does form/3 check the field names you pass?

    The helper validates against the real HTML, so the test exercises the form a user sees.
  3. 3. How do you wait for assign_async work to finish in a test?

    render_async waits for pending async tasks deterministically, with no fixed sleep.
  4. 4. How should you test that a stream item appeared?

    Streams are not kept on the server, so the rendered DOM is the only place to look.

Summary

  • live/2 mounts a LiveView in the test process; drive it with element/3, render_click, form/3, render_change and render_submit.
  • Assert on rendered HTML and elements with has_element?, plus assert_patch, assert_redirect and follow_redirect.
  • Broadcast changes through the context, then render(view); use render_async/1 for async assigns.
  • Streams are tested through the DOM, components with render_component/2.
  • Reserve browser tests for the few journeys that need real JavaScript.

Next: Releases, Configuration and Deployment