@@ -8,8 +8,10 @@ import (
88 "path"
99 "regexp"
1010 "testing"
11+ "time"
1112
1213 "github.com/a-h/templ/cmd/templ/testproject"
14+ "golang.org/x/sync/errgroup"
1315)
1416
1517func TestGenerate (t * testing.T ) {
@@ -42,6 +44,58 @@ func TestGenerate(t *testing.T) {
4244 t .Fatalf ("templates_templ.go was not created: %v" , err )
4345 }
4446 })
47+ t .Run ("can generate a file in watch mode" , func (t * testing.T ) {
48+ // templ generate -f templates.templ
49+ dir , err := testproject .Create ("github.com/a-h/templ/cmd/templ/testproject" )
50+ if err != nil {
51+ t .Fatalf ("failed to create test project: %v" , err )
52+ }
53+ defer os .RemoveAll (dir )
54+
55+ // Delete the templates_templ.go file to ensure it is generated.
56+ err = os .Remove (path .Join (dir , "templates_templ.go" ))
57+ if err != nil {
58+ t .Fatalf ("failed to remove templates_templ.go: %v" , err )
59+ }
60+ ctx , cancel := context .WithCancel (context .Background ())
61+
62+ var eg errgroup.Group
63+ eg .Go (func () error {
64+ // Run the generate command.
65+ return Run (ctx , log , Arguments {
66+ Path : dir ,
67+ Watch : true ,
68+ })
69+ })
70+
71+ // Check the templates_templ.go file was created, with backoff.
72+ for i := 0 ; i < 5 ; i ++ {
73+ time .Sleep (time .Second * time .Duration (i ))
74+ _ , err = os .Stat (path .Join (dir , "templates_templ.go" ))
75+ if err != nil {
76+ continue
77+ }
78+ _ , err = os .Stat (path .Join (dir , "templates_templ.txt" ))
79+ if err != nil {
80+ continue
81+ }
82+ break
83+ }
84+ if err != nil {
85+ t .Fatalf ("template files were not created: %v" , err )
86+ }
87+
88+ cancel ()
89+ if err := eg .Wait (); err != nil {
90+ t .Fatalf ("generate command failed: %v" , err )
91+ }
92+
93+ // Check the templates_templ.txt file was removed.
94+ _ , err = os .Stat (path .Join (dir , "templates_templ.txt" ))
95+ if err == nil {
96+ t .Fatalf ("templates_templ.txt was not removed" )
97+ }
98+ })
4599}
46100
47101func TestDefaultWatchPattern (t * testing.T ) {
0 commit comments