github.com/insionng/yougam@v0.0.0-20170714101924-2bc18d833463/libraries/goquery/iteration_test.go (about) 1 package goquery 2 3 import ( 4 "code.google.com/p/go.net/html" 5 "testing" 6 ) 7 8 func TestEach(t *testing.T) { 9 var cnt int 10 11 sel := Doc().Find(".hero-unit .row-fluid").Each(func(i int, n *Selection) { 12 cnt++ 13 t.Logf("At index %v, node %v", i, n.Nodes[0].Data) 14 }).Find("a") 15 16 if cnt != 4 { 17 t.Errorf("Expected Each() to call function 4 times, got %v times.", cnt) 18 } 19 AssertLength(t, sel.Nodes, 6) 20 } 21 22 func TestEachWithBreak(t *testing.T) { 23 var cnt int 24 25 sel := Doc().Find(".hero-unit .row-fluid").EachWithBreak(func(i int, n *Selection) bool { 26 cnt++ 27 t.Logf("At index %v, node %v", i, n.Nodes[0].Data) 28 return false 29 }).Find("a") 30 31 if cnt != 1 { 32 t.Errorf("Expected Each() to call function 1 time, got %v times.", cnt) 33 } 34 AssertLength(t, sel.Nodes, 6) 35 } 36 37 func TestEachEmptySelection(t *testing.T) { 38 var cnt int 39 40 sel := Doc().Find("zzzz") 41 sel.Each(func(i int, n *Selection) { 42 cnt++ 43 }) 44 if cnt > 0 { 45 t.Error("Expected Each() to not be called on empty Selection.") 46 } 47 sel2 := sel.Find("div") 48 AssertLength(t, sel2.Nodes, 0) 49 } 50 51 func TestMap(t *testing.T) { 52 sel := Doc().Find(".pvk-content") 53 vals := sel.Map(func(i int, s *Selection) string { 54 n := s.Get(0) 55 if n.Type == html.ElementNode { 56 return n.Data 57 } 58 return "" 59 }) 60 for _, v := range vals { 61 if v != "div" { 62 t.Error("Expected Map array result to be all 'div's.") 63 } 64 } 65 if len(vals) != 3 { 66 t.Errorf("Expected Map array result to have a length of 3, found %v.", len(vals)) 67 } 68 }