star-chart-search-enhancer/tests/protected-api-client.test.ts

74 lines
2.0 KiB
TypeScript

import { describe, expect, test, vi } from "vitest";
import { createProtectedApiClient } from "../src/shared/protected-api-client";
describe("protected-api-client", () => {
test("requests a token before calling the protected endpoint", async () => {
const sendMessage = vi.fn(async () => ({
ok: true,
type: "auth:token",
value: { accessToken: "abc123" }
}));
const fetchImpl = vi.fn(async () => ({
ok: true,
status: 200,
json: async () => ({ ok: true })
}));
const client = createProtectedApiClient({
baseUrl: "http://127.0.0.1:4319",
fetchImpl,
sendMessage
});
await client.loadProtectedMockData();
expect(sendMessage).toHaveBeenCalledWith({ type: "auth:get-access-token" });
expect(fetchImpl).toHaveBeenCalledWith(
"http://127.0.0.1:4319/api/mock/protected",
expect.objectContaining({
headers: expect.objectContaining({
Authorization: "Bearer abc123"
}),
method: "GET"
})
);
});
test("throws before fetch when the token is unavailable", async () => {
const sendMessage = vi.fn(async () => ({
ok: false,
type: "auth:error",
error: "token missing"
}));
const fetchImpl = vi.fn();
const client = createProtectedApiClient({
baseUrl: "http://127.0.0.1:4319",
fetchImpl,
sendMessage
});
await expect(client.loadProtectedMockData()).rejects.toThrow(/token/i);
expect(fetchImpl).not.toHaveBeenCalled();
});
test("throws an authorization error on 401", async () => {
const client = createProtectedApiClient({
baseUrl: "http://127.0.0.1:4319",
fetchImpl: vi.fn(async () => ({
ok: false,
status: 401,
json: async () => ({ ok: false, error: "unauthorized" })
})),
sendMessage: vi.fn(async () => ({
ok: true,
type: "auth:token",
value: { accessToken: "abc123" }
}))
});
await expect(client.loadProtectedMockData()).rejects.toThrow(/unauthorized/i);
});
});