PhoenixTestJsdom - A JS integration testing library

PhoenixTestJsdom is a jsdom-based testing library that can test static Phoenix controllers, LiveView pages, and virtual DOM components (such as React components). It integrates seamlessly with any existing LiveView test, and can interop with LiveViewTest functions. It is also PhoenixTest compatible.

Built this over a weekend to address some annoyances in testing JS hooks and JS-mounted components that interoperate with LiveView pages.

Requirements: NodeJS needs to be installed to start the Node process that manages jsdom instances.

Features

  • PhoenixTest.Driver protocol implementation
  • Bundled JSDom, no npm install required. Node execution and package loading is fully configurable
  • Async test support with isolated JSDom instances
  • LiveViewTest interop
  • Static Phoenix controller support
  • Event firing, user interactions, form submissions

Examples

A code snippet speaks a thousand words:

defmodule PhoenixTestJsdomExampleTest do
  use ExUnit.Case, async: true
  import Phoenix.ConnTest
  import Phoenix.LiveViewTest
  @endpoint PhoenixTestJsdom.TestEndpoint

  setup_all do
    start_supervised(PhoenixTestJsdom)
    :ok
  end

  setup do
    {:ok, conn: build_conn()}
  end

  test "Can interact with mounted React components", %{conn: conn} do
    # this page mounts a react component inside of a <script>
    {:ok, view, _} = live(conn, "/react-counter") |> PhoenixTestJsdom.mount()
    # increment the react component's state and return the render HTML in jsdom
    html = PhoenixTestJsdom.render_click(view, "Increment", selector: "button")
    # assert that the rendered HTML contains the rendered react component's state
    assert html =~ "Count: 1"
  end
end

Some more examples:

The library exposes user interaction functions that follows LiveViewTest conventions. Additionally, for even more interactivity testing, one can use the equivalent of dom-testing-library’s fireEvent by using the PhoenixTestJsdom.FireEvent module that exposes equivalent browser events as module functions.

In comparison to alternatives, PhoenixTestJsdom is significantly more lightweight than PhoneixTestPlaywright, and allows seamless testing against controllers and LiveView pages when using PhoenixTest, handy for dealing with pages that deals with sprinklings of JS components around the page.

Library is still rough around the edges and is subject to API changes as I tidy things up to perfection. Hope someone finds this useful!

HexDocs

5 Likes