package services import ( "net/http" "net/http/httptest" "testing" "github.com/labstack/echo/v4" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "git.grosinger.net/tgrosinger/saasitone/config" "git.grosinger.net/tgrosinger/saasitone/pkg/htmx" "git.grosinger.net/tgrosinger/saasitone/pkg/models" "git.grosinger.net/tgrosinger/saasitone/pkg/page" "git.grosinger.net/tgrosinger/saasitone/pkg/tests" "git.grosinger.net/tgrosinger/saasitone/templ/layouts" "git.grosinger.net/tgrosinger/saasitone/templ/pages" ) func TestTemplateRenderer(t *testing.T) { group := "test" id := "parse" // Should not exist yet _, err := c.TemplateRenderer.Load(group, id) assert.Error(t, err) // Parse in to the cache tpl, err := c.TemplateRenderer. Parse(). Group(group). Key(id). Base("test"). Files("emails/test"). Store() require.NoError(t, err) // Should exist now parsed, err := c.TemplateRenderer.Load(group, id) require.NoError(t, err) // Check that all expected templates are included expectedTemplates := make(map[string]bool) expectedTemplates["test"+config.TemplateExt] = true for _, v := range parsed.Template.Templates() { delete(expectedTemplates, v.Name()) } assert.Empty(t, expectedTemplates) data := struct { StatusCode int }{ StatusCode: 500, } buf, err := tpl.Execute(data) require.NoError(t, err) require.NotNil(t, buf) assert.Contains(t, buf.String(), "Test email template") buf, err = c.TemplateRenderer. Parse(). Group(group). Key(id). Base("test"). Files("email/test"). Execute(data) require.NoError(t, err) require.NotNil(t, buf) assert.Contains(t, buf.String(), "Test email template") } func TestTemplateRenderer_RenderPage(t *testing.T) { setup := func() (echo.Context, *httptest.ResponseRecorder, page.Page) { ctx, rec := tests.NewContext(c.Web, "/test/TestTemplateRenderer_RenderPage") tests.InitSession(ctx) p := page.New(ctx) p.Cache.Enabled = false p.Headers["A"] = "b" p.Headers["C"] = "d" p.StatusCode = http.StatusCreated return ctx, rec, p } t.Run("htmx rendering", func(t *testing.T) { ctx, _, p := setup() p.LayoutComponent = layouts.Main p.HTMX.Request.Enabled = true p.HTMX.Response = &htmx.Response{ Trigger: "trigger", } component := pages.Home(p, []models.Post{}) err := c.TemplateRenderer.RenderPageTempl(ctx, p, component) require.NoError(t, err) // Check HTMX header assert.Equal(t, "trigger", ctx.Response().Header().Get(htmx.HeaderTrigger)) }) }