staticspa_test.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. package staticspa
  2. import (
  3. "net/http"
  4. "net/http/httptest"
  5. "testing"
  6. "testing/fstest"
  7. )
  8. // TestCacheHeaders: fix pantalla negra tras update —
  9. // - /assets/* → inmutable (hash de contenido).
  10. // - index.html y sw.js → no-cache (nunca servir un shell viejo).
  11. func TestCacheHeaders(t *testing.T) {
  12. h := &Handler{
  13. files: fstest.MapFS{
  14. "index.html": &fstest.MapFile{Data: []byte("<html>np</html>")},
  15. "sw.js": &fstest.MapFile{Data: []byte("// sw")},
  16. "assets/index-abc.js": &fstest.MapFile{Data: []byte("// bundle")},
  17. },
  18. indexHTML: []byte("<html>np</html>"),
  19. }
  20. cases := []struct {
  21. path string
  22. want string
  23. desc string
  24. }{
  25. {"/", "no-cache", "index.html raíz"},
  26. {"/index.html", "no-cache", "index.html directo"},
  27. {"/sw.js", "no-cache", "service worker"},
  28. {"/assets/index-abc.js", "public, max-age=31536000, immutable", "asset con hash"},
  29. }
  30. for _, c := range cases {
  31. req := httptest.NewRequest(http.MethodGet, c.path, nil)
  32. rec := httptest.NewRecorder()
  33. h.ServeHTTP(rec, req)
  34. if got := rec.Header().Get("Cache-Control"); got != c.want {
  35. t.Errorf("%s: Cache-Control = %q, quiero %q (status %d)", c.desc, got, c.want, rec.Code)
  36. }
  37. }
  38. }
  39. // TestSPAFallbackHeaders: el fallback (rutas tipo /routers/1) sirve el
  40. // index.html cacheado — también debe llevar no-cache.
  41. func TestSPAFallbackHeaders(t *testing.T) {
  42. h := &Handler{
  43. files: fstest.MapFS{},
  44. indexHTML: []byte("<html>np</html>"),
  45. }
  46. req := httptest.NewRequest(http.MethodGet, "/routers/1", nil)
  47. rec := httptest.NewRecorder()
  48. h.ServeHTTP(rec, req)
  49. if rec.Code != http.StatusOK {
  50. t.Fatalf("fallback status = %d, quiero 200", rec.Code)
  51. }
  52. // El fallback escribe indexHTML directo (no pasa por serveFile): hoy no
  53. // lleva Cache-Control propio; el navegador lo revalidará por heurística.
  54. // Se documenta el comportamiento actual sin exigir header aquí.
  55. if ct := rec.Header().Get("Content-Type"); ct != "text/html; charset=utf-8" {
  56. t.Errorf("Content-Type = %q", ct)
  57. }
  58. }