Something went wrong. Try again.
An experimental Wallabag client
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';import { authenticate, fetchEntries, patchEntry, deleteEntryApi, searchEntries, AuthError, ApiError } from './client';
// Mock the db/queries module — the client calls saveSettings/getSettingsvi.mock('../db/queries', () => ({ getSettings: vi.fn(), saveSettings: vi.fn(), clearAuth: vi.fn()}));
import { getSettings, saveSettings, clearAuth } from '../db/queries';
const mockGetSettings = vi.mocked(getSettings);const mockSaveSettings = vi.mocked(saveSettings);const mockClearAuth = vi.mocked(clearAuth);
function mockSettings(overrides = {}) { return { wallabag_url: 'https://wb.example.com', worker_url: 'https://proxy.example.com', client_id: 'cid', client_secret: 'csecret', access_token: 'tok', refresh_token: 'ref', token_expires_at: Date.now() + 3_600_000, last_sync_at: null, last_full_sync_at: null, reader_prefs: {} as never, id: 'singleton' as const, ...overrides };}
function mockFetch(status: number, body: unknown, headers: Record<string, string> = {}) { return vi.fn().mockResolvedValue({ ok: status >= 200 && status < 300, status, statusText: String(status), headers: new Headers({ 'content-type': 'application/json', ...headers }), json: () => Promise.resolve(body), text: () => Promise.resolve(JSON.stringify(body)) });}
beforeEach(() => { // resetAllMocks flushes queued mockResolvedValueOnce state; clearAllMocks does not vi.resetAllMocks();});
afterEach(() => { vi.unstubAllGlobals();});
describe('authenticate', () => { it('POSTs to the proxy with correct grant_type=password payload', async () => { const fetchSpy = mockFetch(200, { access_token: 'newTok', refresh_token: 'newRef', expires_in: 3600 }); vi.stubGlobal('fetch', fetchSpy);
await authenticate( 'https://wb.example.com', 'https://proxy.example.com', 'cid', 'csecret', 'user', 'pass' );
const [url, init] = fetchSpy.mock.calls[0]; expect(url).toContain('proxy.example.com/proxy?target='); expect(url).toContain(encodeURIComponent('https://wb.example.com/oauth/v2/token')); const body = JSON.parse(init.body); expect(body.grant_type).toBe('password'); expect(body.username).toBe('user'); expect(body.password).toBe('pass'); });
it('saves tokens to settings on success', async () => { vi.stubGlobal( 'fetch', mockFetch(200, { access_token: 'newTok', refresh_token: 'newRef', expires_in: 3600 }) ); await authenticate('https://wb.example.com', 'https://proxy.example.com', 'cid', 'csecret', 'u', 'p'); expect(mockSaveSettings).toHaveBeenCalledOnce(); const saved = mockSaveSettings.mock.calls[0][0]; expect(saved.access_token).toBe('newTok'); expect(saved.refresh_token).toBe('newRef'); });
it('throws AuthError on non-200 response', async () => { vi.stubGlobal('fetch', mockFetch(401, { error: 'invalid_client' })); await expect( authenticate('https://wb.example.com', 'https://proxy.example.com', 'cid', 'csecret', 'u', 'badpass') ).rejects.toThrow(AuthError); });});
describe('fetchEntries', () => { it('constructs the correct query string', async () => { mockGetSettings.mockResolvedValue(mockSettings()); const fetchSpy = mockFetch(200, { _embedded: { items: [] }, pages: 1 }); vi.stubGlobal('fetch', fetchSpy);
await fetchEntries(1234, 2, 50);
// The proxy wraps the target URL inside ?target=<encoded>, so decode before asserting const [url] = fetchSpy.mock.calls[0]; const decoded = decodeURIComponent(url as string); expect(decoded).toContain('since=1234'); expect(decoded).toContain('page=2'); expect(decoded).toContain('perPage=50'); });
it('returns entries and total pages', async () => { mockGetSettings.mockResolvedValue(mockSettings()); const entries = [{ id: 1, title: 'A' }, { id: 2, title: 'B' }]; vi.stubGlobal('fetch', mockFetch(200, { _embedded: { items: entries }, pages: 3 }));
const result = await fetchEntries(0); expect(result.entries).toHaveLength(2); expect(result.pages).toBe(3); });
it('returns empty items when _embedded is missing', async () => { mockGetSettings.mockResolvedValue(mockSettings()); vi.stubGlobal('fetch', mockFetch(200, {}));
const result = await fetchEntries(0); expect(result.entries).toEqual([]); expect(result.pages).toBe(1); });
it('throws AuthError when no settings exist', async () => { mockGetSettings.mockResolvedValue(undefined); await expect(fetchEntries(0)).rejects.toThrow(AuthError); });});
describe('patchEntry', () => { it('sends PATCH to the correct entry URL', async () => { mockGetSettings.mockResolvedValue(mockSettings()); const fetchSpy = mockFetch(200, { id: 7, is_archived: 1 }); vi.stubGlobal('fetch', fetchSpy);
await patchEntry(7, { archive: 1 });
const [url, init] = fetchSpy.mock.calls[0]; expect(decodeURIComponent(url as string)).toContain('/api/entries/7'); expect(init.method).toBe('PATCH'); expect(JSON.parse(init.body)).toEqual({ archive: 1 }); });
it('retries with a fresh token after 401', async () => { const expiredSettings = mockSettings({ token_expires_at: Date.now() - 1000 }); // getValidSettings calls getSettings once; refreshToken uses the passed settings, not getSettings mockGetSettings.mockResolvedValueOnce(expiredSettings);
const fetchSpy = vi .fn() // First call: refresh token exchange — succeeds .mockResolvedValueOnce({ ok: true, status: 200, json: () => Promise.resolve({ access_token: 'freshTok', refresh_token: 'freshRef', expires_in: 3600 }) }) // Second call: actual PATCH — succeeds .mockResolvedValueOnce({ ok: true, status: 200, json: () => Promise.resolve({ id: 5 }) }); vi.stubGlobal('fetch', fetchSpy); mockSaveSettings.mockResolvedValue(undefined);
await patchEntry(5, { starred: 1 }); expect(fetchSpy).toHaveBeenCalledTimes(2); });
it('throws ApiError on non-401 error status', async () => { mockGetSettings.mockResolvedValue(mockSettings()); vi.stubGlobal('fetch', mockFetch(500, {})); await expect(patchEntry(1, {})).rejects.toThrow(ApiError); });});
describe('deleteEntryApi', () => { it('sends DELETE to the correct URL', async () => { mockGetSettings.mockResolvedValue(mockSettings()); const fetchSpy = mockFetch(200, {}); vi.stubGlobal('fetch', fetchSpy);
await deleteEntryApi(42);
const [url, init] = fetchSpy.mock.calls[0]; expect(decodeURIComponent(url as string)).toContain('/api/entries/42'); expect(init.method).toBe('DELETE'); });});
describe('searchEntries', () => { it('URL-encodes the term and returns parsed results', async () => { mockGetSettings.mockResolvedValue(mockSettings()); const fetchSpy = mockFetch(200, { _embedded: { items: [{ id: 1 }, { id: 2 }] }, pages: 3 }); vi.stubGlobal('fetch', fetchSpy);
const result = await searchEntries('hello world', 2, 50);
const [url] = fetchSpy.mock.calls[0]; expect(decodeURIComponent(url as string)).toContain('/api/search'); // Term should be URL-encoded; the proxyUrl encodes the whole inner URL once. const decoded = decodeURIComponent(decodeURIComponent(url as string)); expect(decoded).toContain('term=hello world'); expect(decoded).toContain('page=2'); expect(decoded).toContain('perPage=50'); expect(result.entries).toHaveLength(2); expect(result.pages).toBe(3); });
it('returns empty array when _embedded is missing', async () => { mockGetSettings.mockResolvedValue(mockSettings()); vi.stubGlobal('fetch', mockFetch(200, {})); const result = await searchEntries('x'); expect(result.entries).toEqual([]); expect(result.pages).toBe(1); });});