82 lines
2.8 KiB
TypeScript
82 lines
2.8 KiB
TypeScript
import "reflect-metadata";
|
|
|
|
describe("AuthProxyController", () => {
|
|
const originalFetch = global.fetch;
|
|
let AuthProxyController: typeof import("../src/proxy/auth-proxy.controller").AuthProxyController;
|
|
|
|
beforeAll(async () => {
|
|
// `../src/config.ts` reads this at module-import time, so it must be set
|
|
// before the dynamic import below, not in a plain top-of-file import.
|
|
process.env.AUTH_SERVICE_URL = "http://auth-service.test";
|
|
({ AuthProxyController } = await import("../src/proxy/auth-proxy.controller"));
|
|
});
|
|
|
|
afterAll(() => {
|
|
global.fetch = originalFetch;
|
|
});
|
|
|
|
it("forwards method, body, and Authorization header to auth-service and relays the response verbatim", async () => {
|
|
const mockFetch = jest.fn().mockResolvedValue({
|
|
status: 201,
|
|
headers: new Headers({ "content-type": "application/json" }),
|
|
text: async () => JSON.stringify({ username: "demo", role: "user" }),
|
|
});
|
|
global.fetch = mockFetch as unknown as typeof fetch;
|
|
|
|
const controller = new AuthProxyController();
|
|
const req = {
|
|
method: "POST",
|
|
originalUrl: "/auth/register",
|
|
headers: { authorization: "Bearer abc" },
|
|
body: { username: "demo", password: "1" },
|
|
} as unknown as import("express").Request;
|
|
const res = {
|
|
status: jest.fn().mockReturnThis(),
|
|
setHeader: jest.fn().mockReturnThis(),
|
|
send: jest.fn(),
|
|
} as unknown as import("express").Response;
|
|
|
|
await controller.proxy(req, res);
|
|
|
|
expect(mockFetch).toHaveBeenCalledWith(
|
|
"http://auth-service.test/auth/register",
|
|
expect.objectContaining({
|
|
method: "POST",
|
|
headers: expect.objectContaining({ Authorization: "Bearer abc" }),
|
|
body: JSON.stringify({ username: "demo", password: "1" }),
|
|
})
|
|
);
|
|
expect(res.status).toHaveBeenCalledWith(201);
|
|
expect(res.send).toHaveBeenCalledWith(JSON.stringify({ username: "demo", role: "user" }));
|
|
});
|
|
|
|
it("sends no body for a GET (e.g. /auth/me)", async () => {
|
|
const mockFetch = jest.fn().mockResolvedValue({
|
|
status: 200,
|
|
headers: new Headers({ "content-type": "application/json" }),
|
|
text: async () => JSON.stringify({ username: "demo", role: "user" }),
|
|
});
|
|
global.fetch = mockFetch as unknown as typeof fetch;
|
|
|
|
const controller = new AuthProxyController();
|
|
const req = {
|
|
method: "GET",
|
|
originalUrl: "/auth/me",
|
|
headers: { authorization: "Bearer abc" },
|
|
body: {},
|
|
} as unknown as import("express").Request;
|
|
const res = {
|
|
status: jest.fn().mockReturnThis(),
|
|
setHeader: jest.fn().mockReturnThis(),
|
|
send: jest.fn(),
|
|
} as unknown as import("express").Response;
|
|
|
|
await controller.proxy(req, res);
|
|
|
|
expect(mockFetch).toHaveBeenCalledWith(
|
|
"http://auth-service.test/auth/me",
|
|
expect.objectContaining({ method: "GET", body: undefined })
|
|
);
|
|
});
|
|
});
|