Spaces:
Paused
Paused
File size: 5,625 Bytes
4e7644b | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 | import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { authApi } from "./auth";
// auth.ts uses fetch directly (not the request wrapper), so mock global fetch
vi.mock("../config", () => ({
getApiUrl: (path: string) => `/api${path}`,
}));
function mockFetch(status: number, body: unknown) {
global.fetch = vi.fn().mockResolvedValue({
ok: status >= 200 && status < 300,
status,
statusText: status === 200 ? "OK" : "Bad Request",
json: () => Promise.resolve(body),
text: () =>
Promise.resolve(typeof body === "string" ? body : JSON.stringify(body)),
} as unknown as Response);
}
describe("authApi.login", () => {
afterEach(() => vi.clearAllMocks());
it("returns token and username on successful login", async () => {
mockFetch(200, { token: "tok-123", username: "alice" });
const result = await authApi.login("alice", "pass");
expect(result).toEqual({ token: "tok-123", username: "alice" });
});
it("sends POST to /api/auth/login", async () => {
mockFetch(200, { token: "tok", username: "alice" });
await authApi.login("alice", "pass");
expect(fetch).toHaveBeenCalledWith(
"/api/auth/login",
expect.objectContaining({ method: "POST" }),
);
});
it("request body contains username and password", async () => {
mockFetch(200, { token: "tok", username: "alice" });
await authApi.login("alice", "secret");
const [, init] = vi.mocked(fetch).mock.calls[0];
const body = JSON.parse(String(init?.body));
expect(body).toEqual({ username: "alice", password: "secret" });
});
it("throws error with detail on login failure", async () => {
mockFetch(401, { detail: "Invalid username or password" });
await expect(authApi.login("alice", "wrong")).rejects.toThrow(
"Invalid username or password",
);
});
it("throws default error when response has no detail", async () => {
mockFetch(401, {});
await expect(authApi.login("alice", "wrong")).rejects.toThrow(
"Login failed",
);
});
});
describe("authApi.register", () => {
afterEach(() => vi.clearAllMocks());
it("returns token and username on successful registration", async () => {
mockFetch(200, { token: "tok-new", username: "bob" });
const result = await authApi.register("bob", "pass123");
expect(result.token).toBe("tok-new");
});
it("sends POST to /api/auth/register", async () => {
mockFetch(200, { token: "t", username: "bob" });
await authApi.register("bob", "pass");
expect(fetch).toHaveBeenCalledWith("/api/auth/register", expect.anything());
});
it("throws detail error on registration failure", async () => {
mockFetch(409, { detail: "Username already exists" });
await expect(authApi.register("bob", "pass")).rejects.toThrow(
"Username already exists",
);
});
it("formats FastAPI validation details for a short password", async () => {
mockFetch(422, {
detail: [
{
type: "string_too_short",
loc: ["body", "password"],
msg: "String should have at least 8 characters",
},
],
});
await expect(authApi.register("bob", "short")).rejects.toThrow(
"password: String should have at least 8 characters",
);
});
it('throws "Registration failed" when response has no detail', async () => {
mockFetch(500, {});
await expect(authApi.register("bob", "pass")).rejects.toThrow(
"Registration failed",
);
});
});
describe("authApi.getStatus", () => {
afterEach(() => vi.clearAllMocks());
it("returns enabled and has_users fields", async () => {
mockFetch(200, { enabled: true, has_users: false });
const result = await authApi.getStatus();
expect(result).toEqual({ enabled: true, has_users: false });
});
it("throws error when request fails", async () => {
global.fetch = vi.fn().mockResolvedValue({
ok: false,
status: 500,
json: () => Promise.resolve({}),
} as unknown as Response);
await expect(authApi.getStatus()).rejects.toThrow(
"Failed to check auth status",
);
});
});
describe("authApi.updateProfile", () => {
beforeEach(() => {
localStorage.clear();
});
afterEach(() => vi.clearAllMocks());
it("sends POST to /api/auth/update-profile", async () => {
mockFetch(200, { token: "t", username: "alice" });
await authApi.updateProfile("oldpass", "newname");
expect(fetch).toHaveBeenCalledWith(
"/api/auth/update-profile",
expect.anything(),
);
});
it("request body contains current password and new username", async () => {
mockFetch(200, { token: "t", username: "newname" });
await authApi.updateProfile("oldpass", "newname");
const [, init] = vi.mocked(fetch).mock.calls[0];
const body = JSON.parse(String(init?.body));
expect(body.current_password).toBe("oldpass");
expect(body.new_username).toBe("newname");
expect(body.new_password).toBeNull();
});
it("reads token from localStorage and injects Authorization header", async () => {
localStorage.setItem("qwenpaw_auth_token", "my-token");
mockFetch(200, { token: "t", username: "alice" });
await authApi.updateProfile("oldpass");
const [, init] = vi.mocked(fetch).mock.calls[0];
const headers = new Headers(init?.headers);
expect(headers.get("Authorization")).toBe("Bearer my-token");
});
it("throws detail error on update failure", async () => {
mockFetch(400, { detail: "Incorrect password" });
await expect(authApi.updateProfile("wrong")).rejects.toThrow(
"Incorrect password",
);
});
});
|