-
-
Notifications
You must be signed in to change notification settings - Fork 277
/
scripttemplate_test.go
98 lines (90 loc) · 2.59 KB
/
scripttemplate_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package templ_test
import (
"bytes"
"context"
"testing"
"github.com/a-h/templ"
"github.com/google/go-cmp/cmp"
)
func TestRenderScriptItems(t *testing.T) {
s1 := templ.ComponentScript{
Name: "s1",
Function: "function s1() { return 'hello1'; }",
}
s2 := templ.ComponentScript{
Name: "s2",
Function: "function s2() { return 'hello2'; }",
}
tests := []struct {
name string
toIgnore []templ.ComponentScript
toRender []templ.ComponentScript
expected string
}{
{
name: "if none are ignored, everything is rendered",
toIgnore: nil,
toRender: []templ.ComponentScript{s1, s2},
expected: `<script type="text/javascript">` + s1.Function + s2.Function + `</script>`,
},
{
name: "if something outside the expected is ignored, if has no effect",
toIgnore: []templ.ComponentScript{
{
Name: "s3",
Function: "function s3() { return 'hello3'; }",
},
},
toRender: []templ.ComponentScript{s1, s2},
expected: `<script type="text/javascript">` + s1.Function + s2.Function + `</script>`,
},
{
name: "if one is ignored, it's not rendered",
toIgnore: []templ.ComponentScript{s1},
toRender: []templ.ComponentScript{s1, s2},
expected: `<script type="text/javascript">` + s2.Function + `</script>`,
},
{
name: "if all are ignored, not even style tags are rendered",
toIgnore: []templ.ComponentScript{
s1,
s2,
{
Name: "s3",
Function: "function s3() { return 'hello3'; }",
},
},
toRender: []templ.ComponentScript{s1, s2},
expected: ``,
},
}
for _, tt := range tests {
tt := tt
t.Run(tt.name, func(t *testing.T) {
ctx := context.Background()
b := new(bytes.Buffer)
// Render twice, reusing the same context so that there's a memory of which classes have been rendered.
ctx = templ.InitializeContext(ctx)
err := templ.RenderScriptItems(ctx, b, tt.toIgnore...)
if err != nil {
t.Fatalf("failed to render initial scripts: %v", err)
}
// Now render again to check that only the expected classes were rendered.
b.Reset()
err = templ.RenderScriptItems(ctx, b, tt.toRender...)
if err != nil {
t.Fatalf("failed to render scripts: %v", err)
}
if diff := cmp.Diff(tt.expected, b.String()); diff != "" {
t.Error(diff)
}
})
}
}
func TestJSExpression(t *testing.T) {
expected := "myJSFunction(\"StringValue\",123,event,1 + 2)"
actual := templ.SafeScriptInline("myJSFunction", "StringValue", 123, templ.JSExpression("event"), templ.JSExpression("1 + 2"))
if actual != expected {
t.Fatalf("TestJSExpression: expected %q, got %q", expected, actual)
}
}