mirror of
https://github.com/ThisTine/Snip.git
synced 2026-08-18 23:18:47 +07:00
58 lines
1.6 KiB
Go
58 lines
1.6 KiB
Go
package frontend_test
|
|
|
|
import (
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
"testing"
|
|
|
|
"github.com/snip/backend/internal/httpx/frontend"
|
|
)
|
|
|
|
func tempDist(t *testing.T) string {
|
|
t.Helper()
|
|
dir := t.TempDir()
|
|
if err := os.WriteFile(filepath.Join(dir, "index.html"), []byte("<!doctype html><div id=root>SPA</div>"), 0o644); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := os.MkdirAll(filepath.Join(dir, "assets"), 0o755); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := os.WriteFile(filepath.Join(dir, "assets", "app.js"), []byte("console.log('hi')"), 0o644); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
return dir
|
|
}
|
|
|
|
func TestServesSPARoutes(t *testing.T) {
|
|
h := frontend.New(tempDist(t)).Handler()
|
|
|
|
for _, route := range []string{"/", "/login", "/dashboard"} {
|
|
w := httptest.NewRecorder()
|
|
h.ServeHTTP(w, httptest.NewRequest(http.MethodGet, route, nil))
|
|
if w.Code != http.StatusOK || !strings.Contains(w.Body.String(), "SPA") {
|
|
t.Fatalf("%s should render index, got %d", route, w.Code)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestServesAssets(t *testing.T) {
|
|
h := frontend.New(tempDist(t)).Handler()
|
|
w := httptest.NewRecorder()
|
|
h.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/assets/app.js", nil))
|
|
if w.Code != http.StatusOK || !strings.Contains(w.Body.String(), "console.log") {
|
|
t.Fatalf("asset should be served, got %d", w.Code)
|
|
}
|
|
}
|
|
|
|
func TestUnknownPathIs404(t *testing.T) {
|
|
h := frontend.New(tempDist(t)).Handler()
|
|
w := httptest.NewRecorder()
|
|
h.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/some/short-code", nil))
|
|
if w.Code != http.StatusNotFound {
|
|
t.Fatalf("unknown path: want 404 (redirect cmd owns it), got %d", w.Code)
|
|
}
|
|
}
|