...
1 package goquery
2
3 import (
4 "testing"
5
6 "golang.org/x/net/html"
7 )
8
9 func TestEach(t *testing.T) {
10 var cnt int
11
12 sel := Doc().Find(".hero-unit .row-fluid").Each(func(i int, n *Selection) {
13 cnt++
14 t.Logf("At index %v, node %v", i, n.Nodes[0].Data)
15 }).Find("a")
16
17 if cnt != 4 {
18 t.Errorf("Expected Each() to call function 4 times, got %v times.", cnt)
19 }
20 assertLength(t, sel.Nodes, 6)
21 }
22
23 func TestEachWithBreak(t *testing.T) {
24 var cnt int
25
26 sel := Doc().Find(".hero-unit .row-fluid").EachWithBreak(func(i int, n *Selection) bool {
27 cnt++
28 t.Logf("At index %v, node %v", i, n.Nodes[0].Data)
29 return false
30 }).Find("a")
31
32 if cnt != 1 {
33 t.Errorf("Expected Each() to call function 1 time, got %v times.", cnt)
34 }
35 assertLength(t, sel.Nodes, 6)
36 }
37
38 func TestEachEmptySelection(t *testing.T) {
39 var cnt int
40
41 sel := Doc().Find("zzzz")
42 sel.Each(func(i int, n *Selection) {
43 cnt++
44 })
45 if cnt > 0 {
46 t.Error("Expected Each() to not be called on empty Selection.")
47 }
48 sel2 := sel.Find("div")
49 assertLength(t, sel2.Nodes, 0)
50 }
51
52 func TestMap(t *testing.T) {
53 sel := Doc().Find(".pvk-content")
54 vals := sel.Map(func(i int, s *Selection) string {
55 n := s.Get(0)
56 if n.Type == html.ElementNode {
57 return n.Data
58 }
59 return ""
60 })
61 for _, v := range vals {
62 if v != "div" {
63 t.Error("Expected Map array result to be all 'div's.")
64 }
65 }
66 if len(vals) != 3 {
67 t.Errorf("Expected Map array result to have a length of 3, found %v.", len(vals))
68 }
69 }
70
71 func TestForRange(t *testing.T) {
72 sel := Doc().Find(".pvk-content")
73 initLen := sel.Length()
74 for i := range sel.Nodes {
75 single := sel.Eq(i)
76
77
78
79
80
81 if single.Length() != 1 {
82 t.Errorf("%d: expected length of 1, got %d", i, single.Length())
83 }
84 }
85 if sel.Length() != initLen {
86 t.Errorf("expected initial selection to still have length %d, got %d", initLen, sel.Length())
87 }
88 }
89
90 func TestGenericMap(t *testing.T) {
91 sel := Doc().Find(".pvk-content")
92 vals := Map(sel, func(i int, s *Selection) *html.NodeType {
93 n := s.Get(0)
94 if n.Type == html.ElementNode {
95 return &n.Type
96 }
97 return nil
98 })
99 for _, v := range vals {
100 if v == nil || *v != html.ElementNode {
101 t.Error("Expected Map array result to be all 'div's.")
102 }
103 }
104 if len(vals) != 3 {
105 t.Errorf("Expected Map array result to have a length of 3, found %v.", len(vals))
106 }
107 }
108
View as plain text