forked from fahrPool/fahrPool
50 lines
1.8 KiB
TypeScript
50 lines
1.8 KiB
TypeScript
import { beforeEach, describe, expect, it, vi } from "vitest";
|
|
import { NextResponse, NextRequest } from "next/server";
|
|
|
|
// updateSession telefoniert normalerweise ueber das Netz zu Supabase
|
|
// (supabase.auth.getUser()). Fuer einen schnellen, deterministischen Test
|
|
// stubben wir es und pruefen nur, ob die Middleware es aufruft oder umgeht.
|
|
vi.mock("@/lib/supabase/middleware", () => ({
|
|
updateSession: vi.fn(),
|
|
}));
|
|
|
|
import { updateSession } from "@/lib/supabase/middleware";
|
|
import { middleware } from "@/middleware";
|
|
|
|
beforeEach(() => {
|
|
vi.mocked(updateSession).mockReset();
|
|
vi.mocked(updateSession).mockImplementation(async (request) => {
|
|
const url = request.nextUrl.clone();
|
|
url.pathname = "/login";
|
|
return NextResponse.redirect(url);
|
|
});
|
|
});
|
|
|
|
describe("middleware", () => {
|
|
it("laesst POST /api/notifications/dispatch ohne Session-Cookie ohne Redirect passieren", async () => {
|
|
const request = new NextRequest("http://localhost/api/notifications/dispatch", {
|
|
method: "POST",
|
|
});
|
|
|
|
const res = await middleware(request);
|
|
|
|
// Session-Gate (updateSession) darf fuer diese Route gar nicht laufen
|
|
expect(updateSession).not.toHaveBeenCalled();
|
|
// Kein 3xx-Redirect nach /login
|
|
expect(res.status).toBe(200);
|
|
const location = res.headers.get("location");
|
|
expect(location === null || !location.endsWith("/login")).toBe(true);
|
|
});
|
|
|
|
it("leitet GET /dashboard ohne Session-Cookie weiterhin auf /login um", async () => {
|
|
const request = new NextRequest("http://localhost/dashboard", { method: "GET" });
|
|
|
|
const res = await middleware(request);
|
|
|
|
expect(updateSession).toHaveBeenCalledTimes(1);
|
|
expect(res.status).toBeGreaterThanOrEqual(300);
|
|
expect(res.status).toBeLessThan(400);
|
|
expect(res.headers.get("location")).toMatch(/\/login$/);
|
|
});
|
|
});
|