Skip to content
quarry Artifact [b1ac0c45ca]
Login

Artifact [b1ac0c45ca]

Artifact b1ac0c45cac911a1b2dfa6a0e91b451b8365ea7d820e662cdc68ea41f0937acd:


package api

import (
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"

	"craftdesign.group/quarry/internal/ops"
)

// A browser refuses to register a worker served as anything but
// JavaScript, and a worker without Service-Worker-Allowed may only
// control the path it was served from — which would make a
// notification click unable to focus any page (RFC 0011 §6).
func TestServiceWorkerHeaders(t *testing.T) {
	rec := httptest.NewRecorder()
	ServiceWorker().ServeHTTP(rec, httptest.NewRequest("GET", "/sw.js", nil))
	if rec.Code != http.StatusOK {
		t.Fatalf("status = %d", rec.Code)
	}
	if ct := rec.Header().Get("Content-Type"); !strings.HasPrefix(ct, "application/javascript") {
		t.Errorf("Content-Type = %q", ct)
	}
	if got := rec.Header().Get("Service-Worker-Allowed"); got != "/" {
		t.Errorf("Service-Worker-Allowed = %q", got)
	}
	body := rec.Body.String()
	// The three jobs the worker exists to do. Asserted as the event
	// names it registers, not as copy.
	for _, want := range []string{"'push'", "'notificationclick'", "'pushsubscriptionchange'",
		"/api/v1/me/push/key", "/api/v1/me/push"} {
		if !strings.Contains(body, want) {
			t.Errorf("sw.js does not handle %s", want)
		}
	}
}

// Mounted by the API router too, so a node that serves this router at
// the root needs no extra wiring.
func TestRouterServesTheServiceWorker(t *testing.T) {
	h, err := Router(ops.NewRegistry(), "0.0.0-test")
	if err != nil {
		t.Fatal(err)
	}
	rec := httptest.NewRecorder()
	h.ServeHTTP(rec, httptest.NewRequest("GET", "/sw.js", nil))
	if rec.Code != http.StatusOK || rec.Header().Get("Service-Worker-Allowed") != "/" {
		t.Fatalf("status = %d, headers = %+v", rec.Code, rec.Header())
	}
}