const Fastify = require("fastify"); const eventsRoutes = require("../../../src/routes/events"); const { createAppEventBus } = require("../../../src/services/events"); const { AppError } = require("../../../src/utils/AppError"); async function buildApp() { const app = Fastify(); app.decorate("appEvents", createAppEventBus()); app.decorate("authenticate", async (request) => { const auth = request.headers.authorization ?? ""; if (!auth.startsWith("Bearer ")) { throw new AppError({ code: "AUTH_001", message: "未登录", statusCode: 401 }); } request.employee = { id: "employee-1", permissionCodes: [] }; }); app.decorate("hasPermission", (employee, permissionCode) => (employee?.permissionCodes ?? []).includes(permissionCode), ); app.setErrorHandler((error, request, reply) => { if (error instanceof AppError) { return reply.status(error.statusCode).send({ error: { code: error.code, message: error.message, details: error.details ?? {}, }, }); } return reply.status(500).send({ error: { code: "SYS_001", message: "服务异常" } }); }); await app.register(eventsRoutes, { prefix: "/api" }); return app; } describe("GET /api/events", () => { it("requires bearer authentication before opening the event stream", async () => { const app = await buildApp(); try { const response = await app.inject({ method: "GET", url: "/api/events", }); expect(response.statusCode).toBe(401); expect(response.json().error.code).toBe("AUTH_001"); } finally { await app.close(); } }); });