49 lines
1.3 KiB
Go
49 lines
1.3 KiB
Go
package httpserver
|
|
|
|
import (
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"testing"
|
|
"testing/fstest"
|
|
)
|
|
|
|
func testDistFS() fstest.MapFS {
|
|
return fstest.MapFS{
|
|
"index.html": {Data: []byte("<!doctype html><div id=app></div>")},
|
|
"assets/app.js": {Data: []byte("console.log('app')")},
|
|
"favicon.svg": {Data: []byte("<svg></svg>")},
|
|
}
|
|
}
|
|
|
|
func TestSPAHandler(t *testing.T) {
|
|
cases := []struct {
|
|
name string
|
|
path string
|
|
wantBody string
|
|
}{
|
|
{"root serves index", "/", "<!doctype html><div id=app></div>"},
|
|
{"real file served as-is", "/assets/app.js", "console.log('app')"},
|
|
{"real top-level file served as-is", "/favicon.svg", "<svg></svg>"},
|
|
{"deep link falls back to index", "/projects/42/board", "<!doctype html><div id=app></div>"},
|
|
{"unknown asset path falls back to index", "/assets/missing.js", "<!doctype html><div id=app></div>"},
|
|
}
|
|
|
|
handler := spaHandler(testDistFS())
|
|
|
|
for _, tc := range cases {
|
|
t.Run(tc.name, func(t *testing.T) {
|
|
req := httptest.NewRequest(http.MethodGet, tc.path, nil)
|
|
rec := httptest.NewRecorder()
|
|
|
|
handler(rec, req)
|
|
|
|
if rec.Code != http.StatusOK {
|
|
t.Fatalf("status = %d, want 200", rec.Code)
|
|
}
|
|
if got := rec.Body.String(); got != tc.wantBody {
|
|
t.Fatalf("body = %q, want %q", got, tc.wantBody)
|
|
}
|
|
})
|
|
}
|
|
}
|