File size: 1,843 Bytes
6778ee0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
defmodule Plausible.Test.Support.HTML do
  @moduledoc """
  LazyHTML wrappers to help make assertions about HTML/DOM structures
  """

  def element_exists?(html, selector) do
    html
    |> find(selector)
    |> Enum.empty?()
    |> Kernel.not()
  end

  def find(%LazyHTML{} = html, selector) do
    html
    |> LazyHTML.query(selector)
  end

  def find(html, selector) do
    html
    |> lazy_parse()
    |> find(selector)
  end

  def submit_button(html, form) do
    find(html, "#{form} button[type=\"submit\"]")
  end

  def form_exists?(html, action_path) do
    element_exists?(html, "form[action=\"" <> action_path <> "\"]")
  end

  def text_of_element(html, selector) do
    html
    |> find(selector)
    |> text()
  end

  def elem_count(html, selector) do
    find(html, selector) |> Enum.count()
  end

  def text(element) do
    element
    |> lazy_parse()
    |> LazyHTML.text()
    |> String.trim()
    |> String.replace(~r/\s+/, " ")
  end

  def attr_defined?(html, element, attr) do
    empty? =
      html
      |> find(element)
      |> LazyHTML.attribute(attr)
      |> Enum.empty?()

    not empty?
  end

  def class_of_element(html, element) do
    html
    |> find(element)
    |> text_of_attr("class")
  end

  def text_of_attr(html, selector, attr) do
    html
    |> find(selector)
    |> text_of_attr(attr)
  end

  def text_of_attr(element, attr) do
    case LazyHTML.attribute(lazy_parse(element), attr) do
      [] ->
        nil

      [value] ->
        value

      [_ | _] ->
        raise "Multiple attributes found. Narrow down the element you are looking for"
    end
  end

  def name_of(element) do
    text_of_attr(element, "name")
  end

  defp lazy_parse(%LazyHTML{} = lazy) do
    lazy
  end

  defp lazy_parse(element) when is_binary(element) do
    LazyHTML.from_fragment(element)
  end
end