Phoenix LiveView 테스트에서 데이터 역할별로 DOM 요소 찾기

오늘은 테스트 작성에 유용하다고 생각되는 한 가지 기술을 모아봤습니다. 테스트에서 DOM 요소를 찾는 데 data attributes을 사용하는 것입니다. 자바스크립트에도 같은 생각을 적용할 수 있지만 여기서는 주로 Phoenix LiveView 테스트에 집중합니다.

TL;DR



글을 쓰는 시점에서 나는 일반적으로 사용되는 data attributes보다 Id selectors을 사용하는 것을 선호합니다. 특히 customdata-role 속성의 유연성과 명시성을 좋아합니다.

이 HTML 문서가 있다고 가정하면

defmodule MnishiguchiWeb.AlchemistsLive do
  use MnishiguchiWeb, :live_view

  alias Mnishiguchi.Alchemists

  @impl Phoenix.LiveView
  def mount(_params, _session, socket) do
    {:ok, assign(socket, alchemists: Alchemists.list_alchemists())}
  end

  @impl Phoenix.LiveView
  def render(assigns) do
    ~L"""
    <div class="row">
      <%= for alchemist <- @alchemists do %>
        <div class="card mb-3" data-role="alchemist-card" data-id="<%= alchemist.id %>">
          <div class="card-body">
            <h5 class="card-title"><%= alchemist.name %></h5>
          </div>
        <div>
      <% end %>
    </div>
    """
  end
end


테스트 코드에서 data-role 를 통해 주어진 DOM 요소를 찾을 수 있습니다.

defmodule MnishiguchiWeb.AlchemistsLiveTest do
  use MnishiguchiWeb.ConnCase, async: true

  import Phoenix.LiveViewTest

  @path "/alchemists"

  test "displays alchemists", %{conn: conn} do
    alchemist1 = create_alchemist(name: "Taro Yamada")

    {:ok, view, _disconnected_html} = live(conn, @path)

    assert has_alchemist_card?(view, "Taro Yamada")
    refute has_alchemist_card?(view, "Jiro Yamada")
  end

  defp has_alchemist_card?(view, name) do
    has_element?(view, "[data-role=alchemist-card]", name)
  end
end


예를 들어 특정 목록 항목을 정확히 지적하려는 경우 data-role 및 data-id 속성을 모두 사용할 수 있습니다.

  defp has_alchemist_card?(view, id, name) do
    has_element?(view, "[data-role=alchemist-card][data-id=#{id}]", name)
  end


Phoenix.LiveViewTest은 헤드리스 브라우저 없이도 동적 페이지를 쉽게 테스트할 수 있도록 해주기 때문에 매우 훌륭합니다.

대안적 접근



물론 other CSS selectors도 사용할 수 있습니다. 다음은 일반적으로 사용되는 선택기입니다.
  • Id selectors
  • Class selectors
  • data-test-id
  • ARIA roles
  • data-test-id는 data-role와 유사하지만 차이점은 data-test-id DOM 요소 자체의 의미론을 정의하는 data-role와 대조적으로 테스트 특정이기 때문에 차이점이 있습니다.
    data-role 는 관례일 뿐이며 data attribute , ARIA roles 은 more formal standard or specifications 이며, 글을 쓰는 현재 details of many roles are to be determined 입니다.

    데이터 속성 사용의 장점



    나에게 데이터 속성을 사용하면 다음과 같은 이점이 있습니다.
  • 페이지를 스타일링할 때 실수로 테스트 코드를 깨뜨릴 위험을 최소화합니다
  • .
  • 요소가 무엇인지 유연하게 설명할 수 있습니다
  • .
  • DOM을 자체 설명으로 만듭니다.

  • 데이터 속성 사용의 단점



    몇 가지 단점을 알고 있지만 큰 문제는 아닙니다.
  • 조금 장황하다
  • 요소를 찾기 위해 DOM Id 또는 클래스를 사용할 수 있는 많은 예가 있습니다.

  • 그게 다야!

    좋은 웹페이지 즐겨찾기