|
| 1 | +import { Elysia } from "elysia"; |
| 2 | +import { strict as assert } from "node:assert"; |
| 3 | +import { describe, test } from "node:test"; |
| 4 | +import { fedify } from "./index.ts"; |
| 5 | + |
| 6 | +interface MockFederation { |
| 7 | + fetch(request: Request, options: unknown): Promise<Response>; |
| 8 | +} |
| 9 | + |
| 10 | +describe("[elysia] fedify() plugin", () => { |
| 11 | + test("fedify() calls the context data factory when handling a request", async () => { |
| 12 | + const elysia = new Elysia(); |
| 13 | + const mockFederation: MockFederation = { |
| 14 | + fetch: () => Promise.resolve(new Response("OK")), |
| 15 | + }; |
| 16 | + let count = 0; |
| 17 | + const mockContextDataFactory = () => { |
| 18 | + // increases count if this method called |
| 19 | + count++; |
| 20 | + }; |
| 21 | + |
| 22 | + elysia.use(fedify(mockFederation as never, mockContextDataFactory)); |
| 23 | + await elysia.handle(new Request("http://localhost/")); |
| 24 | + |
| 25 | + assert.strictEqual(count, 1, "the context data factory must be called"); |
| 26 | + }); |
| 27 | + |
| 28 | + test("fedify() calls federation.fetch() with the context data", async () => { |
| 29 | + const elysia = new Elysia(); |
| 30 | + const mockFederation: MockFederation = { |
| 31 | + fetch: (_req, opts) => { |
| 32 | + // return context data |
| 33 | + const contextData = (opts as { contextData: string }).contextData; |
| 34 | + return Promise.resolve(new Response(contextData)); |
| 35 | + }, |
| 36 | + }; |
| 37 | + const mockContextDataFactory = () => "Hello World"; |
| 38 | + |
| 39 | + elysia.use(fedify(mockFederation as never, mockContextDataFactory)); |
| 40 | + const actual = await elysia.handle(new Request("http://localhost/")) |
| 41 | + .then((res) => res.text()); |
| 42 | + |
| 43 | + assert.strictEqual( |
| 44 | + actual, |
| 45 | + "Hello World", |
| 46 | + "federation.fetch() must receive the context data returned by the factory", |
| 47 | + ); |
| 48 | + }); |
| 49 | +}); |
0 commit comments