fix: little fixes
This commit is contained in:
@@ -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();
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user