Add a Write function (#11)
Markus Wüstenberg markus@maragu.dk
Mon, 21 Sep 2020 11:27:37 +0200
2 files changed, 37 insertions(+), 0 deletions(-)
M gomponents.go → gomponents.go
@@ -10,6 +10,7 @@ import ( "fmt" "html/template" + "io" "strings" ) @@ -114,3 +115,9 @@ return func() string { return t } } + +// Write to the given io.Writer, returning any error. +func Write(w io.Writer, n Node) error { + _, err := w.Write([]byte(n.Render())) + return err +}
M gomponents_test.go → gomponents_test.go
@@ -1,6 +1,8 @@ package gomponents_test import ( + "errors" + "strings" "testing" g "github.com/maragudk/gomponents" @@ -76,3 +78,31 @@ e := g.Raw("<div/>") assert.Equal(t, "<div/>", e) }) } + +type erroringWriter struct{} + +func (w *erroringWriter) Write(p []byte) (n int, err error) { + return 0, errors.New("don't want to write") +} + +func TestWrite(t *testing.T) { + t.Run("writes to the writer", func(t *testing.T) { + e := g.El("div") + var b strings.Builder + err := g.Write(&b, e) + if err != nil { + t.FailNow() + } + if b.String() != e.Render() { + t.FailNow() + } + }) + + t.Run("errors on write error", func(t *testing.T) { + e := g.El("div") + err := g.Write(&erroringWriter{}, e) + if err == nil { + t.FailNow() + } + }) +}