fix: little fixes

This commit is contained in:
2026-08-13 23:02:25 +03:00
parent 9156f29707
commit 2e32d226d3
5 changed files with 496 additions and 2 deletions
+56
View File
@@ -0,0 +1,56 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { apiClient, configureAuthClient } from "./client";
describe("apiClient authentication", () => {
afterEach(() => {
configureAuthClient(null);
vi.unstubAllGlobals();
});
it("refreshes once and retries an unauthorized protected request", async () => {
let token = "expired";
const refresh = vi.fn(async () => {
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);
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",
);
});
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);
configureAuthClient({
accessToken: () => "expired",
refresh: async () => false,
clear,
});
await apiClient.GET("/api/v1/brokerage-accounts");
expect(clear).toHaveBeenCalledOnce();
expect(fetch).toHaveBeenCalledOnce();
});
});