Files
agentic-coding-workflow/internal/transport/http/spa_test.go
T
2026-06-10 14:18:40 +08:00

47 lines
1.5 KiB
Go

package httpx
import (
"net/http/httptest"
"strings"
"testing"
"testing/fstest"
)
func TestSPAHandler(t *testing.T) {
distFS := fstest.MapFS{
"index.html": {Data: []byte("<html>app</html>")},
"assets/app.js": {Data: []byte("console.log(1)")},
}
h := NewSPAHandler(distFS)
tests := []struct {
name string
path string
wantStatus int
wantBody string
}{
{"根路径返回 index", "/", 200, "<html>app</html>"},
{"静态文件直接命中", "/assets/app.js", 200, "console.log(1)"},
{"前端路由回退 index", "/p/TestProject/w/main", 200, "<html>app</html>"},
{"带尾斜杠的前端路由也回退 index", "/p/TestProject/w/", 200, "<html>app</html>"},
{"不存在的带扩展名文件返回 404", "/assets/missing.js", 404, ""},
{"api 前缀不回退", "/api/v1/unknown", 404, ""},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
rec := httptest.NewRecorder()
h.ServeHTTP(rec, httptest.NewRequest("GET", tt.path, nil))
if rec.Code != tt.wantStatus {
t.Fatalf("status = %d, want %d", rec.Code, tt.wantStatus)
}
if tt.wantBody != "" && strings.TrimSpace(rec.Body.String()) != tt.wantBody {
t.Fatalf("body = %q, want %q", rec.Body.String(), tt.wantBody)
}
// 回退必须直接 200 返回内容,禁止 301 ./ 重定向(会把深层路由改写成尾斜杠 URL)
if rec.Code == 301 || rec.Code == 302 {
t.Fatalf("unexpected redirect to %q", rec.Header().Get("Location"))
}
})
}
}