import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { TEAM_PREFIX, deleteTeamProfile, invalidateTeamProfiles, loadTeamProfiles, saveTeamProfile, teamProfileToEntry, type TeamLensProfile, } from './lensProfiles'; const profile: TeamLensProfile = { id: 'abc-123', maker: 'Tamron', model: 'SP 24-70mm f/2.8 Di VC USD', mount: 'Canon EF', crop: 1, aspect: 0, centerX: 0, centerY: 0, notes: '', d: [[24, 2, 0.01, -0.02, 0.03, 0]], t: [], v: [], createdBy: 'user-1', createdAt: 1, updatedAt: 1, }; let calls: { url: string; method: string }[] = []; function stubFetch(handler: (url: string, init?: RequestInit) => unknown) { vi.stubGlobal('fetch', async (input: RequestInfo | URL, init?: RequestInit) => { const url = String(input); calls.push({ url, method: init?.method ?? 'GET' }); return new Response(JSON.stringify(handler(url, init)), { status: 200 }); }); } beforeEach(() => { calls = []; invalidateTeamProfiles(); }); afterEach(() => { vi.unstubAllGlobals(); }); describe('team lens profiles', () => { it('loads the list once and caches it', async () => { stubFetch(() => ({ profiles: [profile] })); const first = await loadTeamProfiles(); const second = await loadTeamProfiles(); expect(first).toHaveLength(1); expect(second).toBe(first); expect(calls.filter((call) => call.url === '/api/lens-profiles')).toHaveLength(1); }); it('turns a saved profile into an entry the engine can use', () => { const entry = teamProfileToEntry(profile); expect(entry).toMatchObject({ id: `${TEAM_PREFIX}abc-123`, maker: 'Tamron', mounts: ['Canon EF'], crop: 1, team: true, }); expect(entry.d).toHaveLength(1); }); it('posts a new profile and drops the cached list', async () => { stubFetch((url, init) => { if (url === '/api/lens-profiles' && init?.method === 'POST') return { profile }; return { profiles: [profile] }; }); await loadTeamProfiles(); const { id: _id, createdBy: _by, createdAt: _at, updatedAt: _up, ...draft } = profile; const saved = await saveTeamProfile(draft); expect(saved.id).toBe('abc-123'); const post = calls.find((call) => call.method === 'POST'); expect(post?.url).toBe('/api/lens-profiles'); // The next read must go back to the server rather than the pre-save cache. await loadTeamProfiles(); expect(calls.filter((call) => call.method === 'GET').length).toBe(2); }); it('updates an existing profile with PUT to its id', async () => { stubFetch(() => ({ profile })); await saveTeamProfile({ ...profile, notes: 're-measured' }); expect(calls[0]).toEqual({ url: '/api/lens-profiles/abc-123', method: 'PUT' }); }); it('deletes by id', async () => { stubFetch(() => ({ ok: true })); await deleteTeamProfile('abc-123'); expect(calls[0]).toEqual({ url: '/api/lens-profiles/abc-123', method: 'DELETE' }); }); });