a73x

internal/server/web/spa_test.go

Ref:   Size: 1.6 KiB   History

package web

import (
	"io"
	"net/http"
	"net/http/httptest"
	"testing"
	"testing/fstest"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)

func get(t *testing.T, h http.Handler, path string) (int, string) {
	t.Helper()
	req := httptest.NewRequest("GET", path, nil)
	rec := httptest.NewRecorder()
	h.ServeHTTP(rec, req)
	body, _ := io.ReadAll(rec.Result().Body)
	return rec.Code, string(body)
}

func TestSPAServesIndexAtRoot(t *testing.T) {
	h := spaHandler(fstest.MapFS{
		"index.html": {Data: []byte("<title>eitri</title>")},
	})
	code, body := get(t, h, "/")
	assert.Equal(t, http.StatusOK, code)
	assert.Contains(t, body, "eitri")
}

func TestSPAServesRealAsset(t *testing.T) {
	h := spaHandler(fstest.MapFS{
		"index.html":  {Data: []byte("index")},
		"_app/app.js": {Data: []byte("console.log(1)")},
	})
	code, body := get(t, h, "/_app/app.js")
	assert.Equal(t, http.StatusOK, code)
	assert.Contains(t, body, "console.log")
}

func TestSPAFallsBackToIndexForClientRoute(t *testing.T) {
	h := spaHandler(fstest.MapFS{
		"index.html": {Data: []byte("APP_SHELL")},
	})
	// An unknown path (client-side route) must serve the app shell, not 404.
	code, body := get(t, h, "/vms/abc123")
	assert.Equal(t, http.StatusOK, code)
	assert.Contains(t, body, "APP_SHELL")
}

func TestSPAReportsNotBuiltWhenEmpty(t *testing.T) {
	h := spaHandler(fstest.MapFS{})
	code, body := get(t, h, "/")
	assert.Equal(t, http.StatusServiceUnavailable, code)
	assert.Contains(t, body, "not built")
}

func TestEmbeddedHandlerConstructs(t *testing.T) {
	// Handler() must not panic even with only .gitkeep embedded.
	require.NotNil(t, Handler())
}