Testing

Rendering Tests

Verify layout composition, escaping, formats, and missing templates.

By Guillermo Alvarez - Published - Updated

Test rendered responses

Application rendering tests can use httptest:

request := httptest.NewRequest(http.MethodGet, "/posts", nil)
response := httptest.NewRecorder()

appinit.App().ServeHTTP(response, request)

if got := response.Header().Get("Content-Type"); !strings.Contains(got, "text/html") {
    t.Fatalf("Content-Type = %q", got)
}
if !strings.Contains(response.Body.String(), "<main") {
    t.Fatal("layout did not render")
}

This catches route, controller, view, and layout wiring together.

Test escaping

If a controller sets ordinary strings, templates should escape them:

if strings.Contains(response.Body.String(), `<script>`) {
    t.Fatal("response contains unescaped script tag")
}

Only trusted framework-generated or adapter-generated HTML should be passed as template.HTML.

Keep framework tests focused

Framework renderer tests can use an in-memory file system:

views, err := lazyview.New(fstest.MapFS{
    "layouts/app.html.tpl": {Data: []byte(`{{.content}}`)},
    "posts/index.html.tpl": {Data: []byte(`<h1>{{.title}}</h1>`)},
})
if err != nil {
    t.Fatal(err)
}

Application tests should assert application behavior rather than duplicating framework renderer coverage.