137 lines
5.2 KiB
TypeScript
137 lines
5.2 KiB
TypeScript
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
|
import { api, setAccessToken, getAccessToken, ApiError } from '../src/api/client';
|
|
import { API_BASE } from '../src/config';
|
|
|
|
function jsonResponse(status: number, body: unknown) {
|
|
return new Response(JSON.stringify(body), {
|
|
status,
|
|
headers: { 'Content-Type': 'application/json' },
|
|
});
|
|
}
|
|
|
|
function mockFetchSequence(...responses: Response[]) {
|
|
const calls: { url: string; init?: RequestInit }[] = [];
|
|
const fetchMock = vi.fn(async (url: string, init?: RequestInit) => {
|
|
calls.push({ url, init });
|
|
const next = responses.shift();
|
|
if (!next) throw new Error(`No more mocked responses for url: ${url}`);
|
|
return next;
|
|
});
|
|
vi.stubGlobal('fetch', fetchMock);
|
|
return calls;
|
|
}
|
|
|
|
beforeEach(async () => {
|
|
// wait for any pending internal refresh-state cleanup from previous tests
|
|
await new Promise((r) => setTimeout(r, 25));
|
|
setAccessToken(null);
|
|
localStorage.clear();
|
|
});
|
|
|
|
afterEach(() => {
|
|
vi.unstubAllGlobals();
|
|
});
|
|
|
|
describe('admin api client', () => {
|
|
it('performs a GET request with the Authorization header when a token is set', async () => {
|
|
setAccessToken('admin-tok');
|
|
const calls = mockFetchSequence(jsonResponse(200, { ok: true }));
|
|
const data = await api<{ ok: boolean }>('/admin/users');
|
|
expect(data).toEqual({ ok: true });
|
|
expect(calls).toHaveLength(1);
|
|
expect(calls[0].url).toBe(`${API_BASE}/admin/users`);
|
|
expect(calls[0].init?.headers).toMatchObject({ Authorization: 'Bearer admin-tok' });
|
|
expect(calls[0].init?.credentials).toBe('include');
|
|
});
|
|
|
|
it('omits the Authorization header when no token is set', async () => {
|
|
setAccessToken(null);
|
|
const calls = mockFetchSequence(jsonResponse(200, { ok: true }));
|
|
await api('/me');
|
|
expect(calls[0].init?.headers).not.toHaveProperty('Authorization');
|
|
});
|
|
|
|
it('sends a JSON body for POST requests', async () => {
|
|
const calls = mockFetchSequence(jsonResponse(200, { ok: true }));
|
|
await api('/auth/login', { method: 'POST', body: { email: 'a@b.c', password: 'x' } });
|
|
expect(calls[0].init?.method).toBe('POST');
|
|
expect(calls[0].init?.body).toBe(JSON.stringify({ email: 'a@b.c', password: 'x' }));
|
|
});
|
|
|
|
it('throws an ApiError with status and server message on failure', async () => {
|
|
mockFetchSequence(
|
|
jsonResponse(403, { error: { code: 'FORBIDDEN', message: 'Admin only' } }),
|
|
);
|
|
let caught: unknown;
|
|
try {
|
|
await api('/admin/users');
|
|
} catch (e) {
|
|
caught = e;
|
|
}
|
|
expect(caught).toBeInstanceOf(ApiError);
|
|
expect((caught as ApiError).status).toBe(403);
|
|
expect((caught as ApiError).message).toBe('Admin only');
|
|
});
|
|
|
|
it('wraps a non-JSON error body (e.g. rate limiter) in an ApiError with the raw text message', async () => {
|
|
mockFetchSequence(new Response('Too many requests, please try again later.', { status: 429 }));
|
|
let caught: unknown;
|
|
try {
|
|
await api('/admin/users');
|
|
} catch (e) {
|
|
caught = e;
|
|
}
|
|
expect(caught).toBeInstanceOf(ApiError);
|
|
expect((caught as ApiError).status).toBe(429);
|
|
expect((caught as ApiError).message).toBe('Too many requests, please try again later.');
|
|
});
|
|
|
|
it('on 401 refreshes the token and retries the request', async () => {
|
|
setAccessToken('old-token');
|
|
const calls = mockFetchSequence(
|
|
jsonResponse(401, { error: { code: 'UNAUTHORIZED', message: 'Unauthorized' } }),
|
|
jsonResponse(200, { accessToken: 'new-token' }),
|
|
jsonResponse(200, { users: [] }),
|
|
);
|
|
const data = await api<{ users: unknown[] }>('/admin/users');
|
|
expect(data).toEqual({ users: [] });
|
|
expect(calls).toHaveLength(3);
|
|
expect(calls[1].url).toBe(`${API_BASE}/auth/refresh`);
|
|
expect(getAccessToken()).toBe('new-token');
|
|
expect(calls[2].init?.headers).toMatchObject({ Authorization: 'Bearer new-token' });
|
|
});
|
|
|
|
it('on 401 with a failed refresh clears the token and dispatches fitos:logout', async () => {
|
|
setAccessToken('old-token');
|
|
const listener = vi.fn();
|
|
window.addEventListener('fitos:logout', listener);
|
|
const calls = mockFetchSequence(
|
|
jsonResponse(401, { error: { code: 'UNAUTHORIZED', message: 'Unauthorized' } }),
|
|
jsonResponse(401, { error: { code: 'UNAUTHORIZED', message: 'Invalid refresh token' } }),
|
|
);
|
|
await expect(api('/admin/users')).rejects.toBeInstanceOf(ApiError);
|
|
expect(calls).toHaveLength(2);
|
|
expect(getAccessToken()).toBeNull();
|
|
expect(localStorage.getItem('fitos_admin_access')).toBeNull();
|
|
expect(listener).toHaveBeenCalledTimes(1);
|
|
window.removeEventListener('fitos:logout', listener);
|
|
});
|
|
|
|
it('does not attempt a refresh for the auth login endpoint', async () => {
|
|
const calls = mockFetchSequence(
|
|
jsonResponse(401, { error: { code: 'UNAUTHORIZED', message: 'Invalid credentials' } }),
|
|
);
|
|
await expect(
|
|
api('/auth/login', { method: 'POST', body: { email: 'a@b.c', password: 'x' } }),
|
|
).rejects.toBeInstanceOf(ApiError);
|
|
expect(calls).toHaveLength(1);
|
|
});
|
|
|
|
it('persists the access token under the admin localStorage key', () => {
|
|
setAccessToken('abc');
|
|
expect(localStorage.getItem('fitos_admin_access')).toBe('abc');
|
|
setAccessToken(null);
|
|
expect(localStorage.getItem('fitos_admin_access')).toBeNull();
|
|
});
|
|
});
|