iteration_test.go 1.9 KB

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