|
| 1 | +import { describe, expect, it, vi } from "vitest"; |
| 2 | + |
| 3 | +vi.mock("cloudflare:workers", () => { |
| 4 | + class DurableObject { |
| 5 | + constructor(_state?: unknown, _env?: unknown) {} |
| 6 | + } |
| 7 | + |
| 8 | + class WorkerEntrypoint {} |
| 9 | + |
| 10 | + return { |
| 11 | + DurableObject, |
| 12 | + WorkerEntrypoint, |
| 13 | + env: {}, |
| 14 | + }; |
| 15 | +}); |
| 16 | + |
| 17 | +import { Actor, type ActorConfiguration } from "./index"; |
| 18 | + |
| 19 | +describe("Actor configuration overrides", () => { |
| 20 | + it("respects custom upgrade paths defined by subclasses", async () => { |
| 21 | + let upgradeCalls = 0; |
| 22 | + |
| 23 | + class CustomPathActor extends Actor<Record<string, never>> { |
| 24 | + static override configuration(): ActorConfiguration { |
| 25 | + return { |
| 26 | + sockets: { |
| 27 | + upgradePath: "/custom", |
| 28 | + }, |
| 29 | + }; |
| 30 | + } |
| 31 | + |
| 32 | + protected override async shouldUpgradeWebSocket( |
| 33 | + request: Request, |
| 34 | + ): Promise<boolean> { |
| 35 | + return request.headers.get("Upgrade")?.toLowerCase() === "websocket"; |
| 36 | + } |
| 37 | + |
| 38 | + protected override onWebSocketUpgrade(_request: Request): Response { |
| 39 | + upgradeCalls += 1; |
| 40 | + return new Response("upgraded", { status: 200 }); |
| 41 | + } |
| 42 | + |
| 43 | + protected override onRequest(): Promise<Response> { |
| 44 | + return Promise.resolve(new Response("fallback", { status: 418 })); |
| 45 | + } |
| 46 | + } |
| 47 | + |
| 48 | + const actor = new CustomPathActor(undefined, undefined); |
| 49 | + (actor as Record<string, unknown>)["_setNameCalled"] = true; |
| 50 | + |
| 51 | + const upgradeResponse = await actor.fetch( |
| 52 | + new Request("https://example.com/custom/game", { |
| 53 | + headers: { Upgrade: "websocket" }, |
| 54 | + }), |
| 55 | + ); |
| 56 | + // Node/undici Response objects cannot emit 101, so we just ensure the response we returned flows through. |
| 57 | + expect(upgradeResponse.status).toBe(200); |
| 58 | + expect(upgradeCalls).toBe(1); |
| 59 | + |
| 60 | + const fallbackResponse = await actor.fetch( |
| 61 | + new Request("https://example.com/ws/game"), |
| 62 | + ); |
| 63 | + expect(fallbackResponse.status).toBe(418); |
| 64 | + expect(upgradeCalls).toBe(1); |
| 65 | + }); |
| 66 | +}); |
0 commit comments