Something went wrong. Try again.
Synapse is a study workspace. Organize courses read and annotate the material, train with generated exercises and watch your progress forked from denishovart.com/synapse
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { api, apiFetch, hasServerBase, setApiBase, setAuthToken, setUnauthorizedHandler,} from './api';
// isNativeShell()/hasServerBase() key off window.__TAURI_INTERNALS__.function setShell(on: boolean): void { if (on) (window as unknown as Record<string, unknown>).__TAURI_INTERNALS__ = {}; else delete (window as unknown as Record<string, unknown>).__TAURI_INTERNALS__;}
function jsonResponse(body: unknown, init?: { ok?: boolean; status?: number }) { return { ok: init?.ok ?? true, status: init?.status ?? 200, json: vi.fn().mockResolvedValue(body), } as unknown as Response;}
describe('api', () => { beforeEach(() => { globalThis.fetch = vi.fn(); });
afterEach(() => { vi.restoreAllMocks(); });
describe('get', () => { it('returns Ok(parsed JSON) on a 200 response', async () => { const payload = { id: '1', name: 'Denis' }; vi.mocked(fetch).mockResolvedValue(jsonResponse(payload));
const result = await api.get<typeof payload>('/api/thing');
expect(result.isOk()).toBe(true); expect(result._unsafeUnwrap()).toEqual(payload); const [url, init] = vi.mocked(fetch).mock.calls[0]; expect(url).toBe('/api/thing'); expect(init?.credentials).toBe('include'); }); });
describe('base url and token', () => { afterEach(() => { setApiBase(''); setAuthToken(null); });
it('prefixes paths with the configured base and sends the bearer token', async () => { setApiBase('https://synapse.example/'); setAuthToken('tok-123'); vi.mocked(fetch).mockResolvedValue(jsonResponse({}));
await api.get('/api/thing');
const [url, init] = vi.mocked(fetch).mock.calls[0]; expect(url).toBe('https://synapse.example/api/thing'); expect((init?.headers as Record<string, string>).Authorization).toBe('Bearer tok-123'); });
it('keeps relative paths and sends no Authorization header by default', async () => { vi.mocked(fetch).mockResolvedValue(jsonResponse({}));
await api.post('/api/thing', {});
const [url, init] = vi.mocked(fetch).mock.calls[0]; expect(url).toBe('/api/thing'); expect((init?.headers as Record<string, string>).Authorization).toBeUndefined(); }); });
describe('post', () => { it('sends the body as JSON with method POST and the right Content-Type header', async () => { const body = { title: 'hello' }; const responseBody = { ok: true }; vi.mocked(fetch).mockResolvedValue(jsonResponse(responseBody));
const result = await api.post<typeof responseBody>('/api/create', body);
expect(result._unsafeUnwrap()).toEqual(responseBody); const [url, init] = vi.mocked(fetch).mock.calls[0]; expect(url).toBe('/api/create'); expect(init?.method).toBe('POST'); expect((init?.headers as Record<string, string>)['Content-Type']).toBe('application/json'); expect(init?.body).toBe(JSON.stringify(body)); });
it('sends an empty object body when none is provided', async () => { vi.mocked(fetch).mockResolvedValue(jsonResponse({}));
await api.post('/api/create');
const [, init] = vi.mocked(fetch).mock.calls[0]; expect(init?.body).toBe(JSON.stringify({})); }); });
describe('put', () => { it('uses the PUT method and JSON body', async () => { const body = { name: 'updated' }; vi.mocked(fetch).mockResolvedValue(jsonResponse({ done: true }));
await api.put('/api/item/1', body);
const [url, init] = vi.mocked(fetch).mock.calls[0]; expect(url).toBe('/api/item/1'); expect(init?.method).toBe('PUT'); expect((init?.headers as Record<string, string>)['Content-Type']).toBe('application/json'); expect(init?.body).toBe(JSON.stringify(body)); }); });
describe('del', () => { it('uses the DELETE method', async () => { // A 204 response has no JSON body; parse() short-circuits to null. vi.mocked(fetch).mockResolvedValue({ ok: true, status: 204, json: vi.fn(), } as unknown as Response);
const result = await api.del('/api/item/1');
expect(result._unsafeUnwrap()).toBeNull(); const [url, init] = vi.mocked(fetch).mock.calls[0]; expect(url).toBe('/api/item/1'); expect(init?.method).toBe('DELETE'); }); });
describe('upload', () => { it('POSTs FormData without a JSON Content-Type header', async () => { const form = new FormData(); form.append('file', 'x'); const responseBody = { uploaded: true }; vi.mocked(fetch).mockResolvedValue(jsonResponse(responseBody));
const result = await api.upload<typeof responseBody>('/api/upload', form);
expect(result._unsafeUnwrap()).toEqual(responseBody); const [url, init] = vi.mocked(fetch).mock.calls[0]; expect(url).toBe('/api/upload'); expect(init?.method).toBe('POST'); expect(init?.body).toBe(form); expect((init?.headers as Record<string, string>)['Content-Type']).toBeUndefined(); }); });
describe('error handling', () => { it('returns Err with the message from the JSON body on a non-ok response', async () => { vi.mocked(fetch).mockResolvedValue( jsonResponse({ error: 'Not found' }, { ok: false, status: 404 }), );
const result = await api.get('/api/missing'); expect(result.isErr()).toBe(true); expect(result._unsafeUnwrapErr()).toMatchObject({ message: 'Not found', status: 404 }); });
it('falls back to a status-based message when the body is not JSON', async () => { vi.mocked(fetch).mockResolvedValue({ ok: false, status: 400, json: vi.fn().mockRejectedValue(new Error('not json')), } as unknown as Response);
const result = await api.post('/api/bad', {}); expect(result._unsafeUnwrapErr()).toMatchObject({ message: 'Error 400', status: 400 }); });
it('carries the status on the Err for put and del as well', async () => { vi.mocked(fetch).mockResolvedValue( jsonResponse({ error: 'Forbidden' }, { ok: false, status: 403 }), );
expect((await api.put('/api/x', {}))._unsafeUnwrapErr()).toMatchObject({ status: 403 }); expect((await api.del('/api/x'))._unsafeUnwrapErr()).toMatchObject({ status: 403 }); }); });
describe('401 handling', () => { afterEach(() => setUnauthorizedHandler(() => {})); // reset the shared handler
it('fires the unauthorized handler on a 401 from the fetch path', async () => { const onUnauthorized = vi.fn(); setUnauthorizedHandler(onUnauthorized); vi.mocked(fetch).mockResolvedValue( jsonResponse({ error: 'Authentication required' }, { ok: false, status: 401 }), );
const result = await api.get('/api/courses'); expect(result._unsafeUnwrapErr().status).toBe(401); expect(onUnauthorized).toHaveBeenCalledTimes(1); });
it('does NOT fire the handler on other error statuses', async () => { const onUnauthorized = vi.fn(); setUnauthorizedHandler(onUnauthorized); vi.mocked(fetch).mockResolvedValue( jsonResponse({ error: 'nope' }, { ok: false, status: 403 }), );
const result = await api.get('/api/courses'); expect(result._unsafeUnwrapErr().status).toBe(403); expect(onUnauthorized).not.toHaveBeenCalled(); });
it('does NOT fire the handler when a post opts out (401 as a domain answer)', async () => { const onUnauthorized = vi.fn(); setUnauthorizedHandler(onUnauthorized); vi.mocked(fetch).mockResolvedValue( jsonResponse({ error: 'The current password is incorrect' }, { ok: false, status: 401 }), );
const result = await api.post( '/api/auth/password', { currentPassword: 'x', newPassword: 'y' }, { handleUnauthorized: false }, ); expect(result._unsafeUnwrapErr().status).toBe(401); expect(onUnauthorized).not.toHaveBeenCalled(); });
it('fires the unauthorized handler on a 401 from the XHR upload path', async () => { const onUnauthorized = vi.fn(); setUnauthorizedHandler(onUnauthorized);
// Minimal XMLHttpRequest stand-in: send() invokes onload with a 401. class FakeXhr { status = 401; response: unknown = { error: 'Authentication required' }; upload = { onprogress: null as ((e: ProgressEvent) => void) | null }; onload: (() => void) | null = null; onerror: (() => void) | null = null; open() {} set responseType(_v: string) {} send() { this.onload?.(); } } const original = globalThis.XMLHttpRequest; globalThis.XMLHttpRequest = FakeXhr as unknown as typeof XMLHttpRequest; try { const result = await api.uploadWithProgress('/api/documents', new FormData(), () => {}); expect(result._unsafeUnwrapErr().status).toBe(401); expect(onUnauthorized).toHaveBeenCalledTimes(1); } finally { globalThis.XMLHttpRequest = original; } }); });
describe('hasServerBase', () => { afterEach(() => { setShell(false); setApiBase(''); });
it('is true in the browser (same-origin relative paths work)', () => { setShell(false); expect(hasServerBase()).toBe(true); });
it('is false in a native shell with no configured base', () => { setShell(true); setApiBase(''); expect(hasServerBase()).toBe(false); });
it('is true in a native shell once a base is configured', () => { setShell(true); setApiBase('https://synapse.example'); expect(hasServerBase()).toBe(true); }); });
describe('apiFetch', () => { afterEach(() => setAuthToken(null));
it('fetches with credentials and no JSON content-type, merging caller headers', async () => { vi.mocked(fetch).mockResolvedValue(jsonResponse({})); await apiFetch('/api/blob', { headers: { 'X-Test': '1' } });
const [url, init] = vi.mocked(fetch).mock.calls[0]; expect(url).toBe('/api/blob'); expect(init?.credentials).toBe('include'); const headers = init?.headers as Record<string, string>; expect(headers['Content-Type']).toBeUndefined(); expect(headers['X-Test']).toBe('1'); });
it('adds the bearer token when one is set', async () => { setAuthToken('tok-xyz'); vi.mocked(fetch).mockResolvedValue(jsonResponse({})); await apiFetch('/api/blob');
const [, init] = vi.mocked(fetch).mock.calls[0]; expect((init?.headers as Record<string, string>).Authorization).toBe('Bearer tok-xyz'); }); });
describe('uploadWithProgress', () => { it('reports computable progress and resolves on a 2xx', async () => { const seen: number[] = []; // send() drives one progress event then a 201 onload. class FakeXhr { status = 201; response: unknown = { id: 'doc-1' }; upload = { onprogress: null as ((e: ProgressEvent) => void) | null }; onload: (() => void) | null = null; onerror: (() => void) | null = null; open() {} setRequestHeader() {} set responseType(_v: string) {} set withCredentials(_v: boolean) {} send() { this.upload.onprogress?.({ lengthComputable: true, loaded: 50, total: 200, } as ProgressEvent); // A non-computable event is ignored (no NaN percent). this.upload.onprogress?.({ lengthComputable: false, loaded: 0, total: 0, } as ProgressEvent); this.onload?.(); } } const original = globalThis.XMLHttpRequest; globalThis.XMLHttpRequest = FakeXhr as unknown as typeof XMLHttpRequest; try { const result = await api.uploadWithProgress<{ id: string }>( '/api/documents', new FormData(), (p) => seen.push(p), ); expect(result._unsafeUnwrap()).toEqual({ id: 'doc-1' }); expect(seen).toEqual([25]); } finally { globalThis.XMLHttpRequest = original; } });
it('rejects with a network error when the transfer errors', async () => { class FakeXhr { status = 0; response: unknown = null; upload = { onprogress: null }; onload: (() => void) | null = null; onerror: (() => void) | null = null; open() {} setRequestHeader() {} set responseType(_v: string) {} set withCredentials(_v: boolean) {} send() { this.onerror?.(); } } const original = globalThis.XMLHttpRequest; globalThis.XMLHttpRequest = FakeXhr as unknown as typeof XMLHttpRequest; try { const result = await api.uploadWithProgress('/api/documents', new FormData(), () => {}); expect(result._unsafeUnwrapErr()).toMatchObject({ message: 'Network error', status: 0 }); } finally { globalThis.XMLHttpRequest = original; } }); });});