package gomponents_test import ( "errors" "fmt" "io" "strings" "testing" g "github.com/maragudk/gomponents" "github.com/maragudk/gomponents/assert" ) func TestNodeFunc(t *testing.T) { t.Run("implements fmt.Stringer", func(t *testing.T) { fn := g.NodeFunc(func(w io.Writer) error { _, _ = w.Write([]byte("hat")) return nil }) if fn.String() != "hat" { t.FailNow() } }) } func TestAttr(t *testing.T) { t.Run("renders just the local name with one argument", func(t *testing.T) { a := g.Attr("required") assert.Equal(t, " required", a) }) t.Run("renders the name and value when given two arguments", func(t *testing.T) { a := g.Attr("id", "hat") assert.Equal(t, ` id="hat"`, a) }) t.Run("panics with more than two arguments", func(t *testing.T) { called := false defer func() { if err := recover(); err != nil { called = true } }() g.Attr("name", "value", "what is this?") if !called { t.FailNow() } }) t.Run("implements fmt.Stringer", func(t *testing.T) { a := g.Attr("required") s := fmt.Sprintf("%v", a) if s != " required" { t.FailNow() } }) } func BenchmarkAttr(b *testing.B) { b.Run("boolean attributes", func(b *testing.B) { for i := 0; i < b.N; i++ { a := g.Attr("hat") _ = a.Render(&strings.Builder{}) } }) b.Run("name-value attributes", func(b *testing.B) { for i := 0; i < b.N; i++ { a := g.Attr("hat", "party") _ = a.Render(&strings.Builder{}) } }) } type outsider struct{} func (o outsider) String() string { return "outsider" } func (o outsider) Render(w io.Writer) error { _, _ = w.Write([]byte("outsider")) return nil } func TestEl(t *testing.T) { t.Run("renders an empty element if no children given", func(t *testing.T) { e := g.El("div") assert.Equal(t, "
", e) }) t.Run("renders an empty element if only attributes given as children", func(t *testing.T) { e := g.El("div", g.Attr("class", "hat")) assert.Equal(t, ``, e) }) t.Run("renders an element, attributes, and element children", func(t *testing.T) { e := g.El("div", g.Attr("class", "hat"), g.El("span")) assert.Equal(t, `