refactor: refactor foundation

This commit is contained in:
2026-08-14 09:43:19 +03:00
parent 2e32d226d3
commit da585b157a
54 changed files with 4822 additions and 535 deletions
+37 -24
View File
@@ -1,11 +1,10 @@
import { HttpResponse, http } from "msw";
import { afterEach, describe, expect, it, vi } from "vitest";
import { server } from "@/test/server";
import { apiClient, configureAuthClient } from "./client";
describe("apiClient authentication", () => {
afterEach(() => {
configureAuthClient(null);
vi.unstubAllGlobals();
});
afterEach(() => configureAuthClient(null));
it("refreshes once and retries an unauthorized protected request", async () => {
let token = "expired";
@@ -13,35 +12,31 @@ describe("apiClient authentication", () => {
token = "fresh";
return true;
});
const fetch = vi
.fn()
.mockResolvedValueOnce(
new Response(JSON.stringify({ code: "UNAUTHORIZED" }), { status: 401 }),
)
.mockResolvedValueOnce(new Response(JSON.stringify([]), { status: 200 }));
vi.stubGlobal("fetch", fetch);
const authorization: string[] = [];
server.use(
http.get("*/api/v1/brokerage-accounts", ({ request }) => {
authorization.push(request.headers.get("Authorization") ?? "");
return authorization.length === 1
? HttpResponse.json({ code: "UNAUTHORIZED" }, { status: 401 })
: HttpResponse.json([]);
}),
);
configureAuthClient({ accessToken: () => token, refresh, clear: vi.fn() });
const { data } = await apiClient.GET("/api/v1/brokerage-accounts");
expect(data).toEqual([]);
expect(refresh).toHaveBeenCalledOnce();
expect(fetch.mock.calls[0][0].headers.get("Authorization")).toBe(
"Bearer expired",
);
expect(fetch.mock.calls[1][0].headers.get("Authorization")).toBe(
"Bearer fresh",
);
expect(authorization).toEqual(["Bearer expired", "Bearer fresh"]);
});
it("clears the session when refresh cannot restore it", async () => {
const clear = vi.fn();
const fetch = vi
.fn()
.mockResolvedValue(
new Response(JSON.stringify({ code: "UNAUTHORIZED" }), { status: 401 }),
);
vi.stubGlobal("fetch", fetch);
server.use(
http.get("*/api/v1/brokerage-accounts", () =>
HttpResponse.json({ code: "UNAUTHORIZED" }, { status: 401 }),
),
);
configureAuthClient({
accessToken: () => "expired",
refresh: async () => false,
@@ -51,6 +46,24 @@ describe("apiClient authentication", () => {
await apiClient.GET("/api/v1/brokerage-accounts");
expect(clear).toHaveBeenCalledOnce();
expect(fetch).toHaveBeenCalledOnce();
});
it("does not attach Bearer auth to authentication endpoints", async () => {
let authorization: string | null = null;
server.use(
http.post("*/api/v1/auth/refresh", ({ request }) => {
authorization = request.headers.get("Authorization");
return HttpResponse.json({ code: "UNAUTHORIZED" }, { status: 401 });
}),
);
configureAuthClient({
accessToken: () => "token",
refresh: vi.fn(),
clear: vi.fn(),
});
await apiClient.POST("/api/v1/auth/refresh");
expect(authorization).toBeNull();
});
});