package templ_test import ( "bytes" "context" "testing" "github.com/a-h/templ" "github.com/google/go-cmp/cmp" ) func TestJSONScriptElement(t *testing.T) { data := map[string]any{"foo": "bar"} tests := []struct { name string ctx context.Context e templ.JSONScriptElement expected string }{ { name: "renders data as JSON inside a script element", e: templ.JSONScript("id", data), expected: "", }, { name: "if a nonce is available in the context, it is used", ctx: templ.WithNonce(context.Background(), "nonce-from-context"), e: templ.JSONScript("idc", data), expected: "", }, { name: "if a nonce is provided, it is used", e: templ.JSONScript("ids", data).WithNonceFromString("nonce-from-string"), expected: "", }, { name: "if a nonce function is provided, it is used", e: templ.JSONScript("idf", data).WithNonceFrom(func(context.Context) string { return "nonce-from-function" }), expected: "", }, { name: "if a type is provided, it is used", e: templ.JSONScript("idt", data).WithType("application/ld+json"), expected: "", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { w := new(bytes.Buffer) if err := tt.e.Render(tt.ctx, w); err != nil { t.Fatalf("unexpected error: %v", err) } if diff := cmp.Diff(tt.expected, w.String()); diff != "" { t.Fatalf("unexpected output (-want +got):\n%s", diff) } }) } }