import { describe, it, expect, vi, beforeEach } from 'vitest'; // Mock expo-web-browser vi.mock('expo-web-browser', () => ({ openAuthSessionAsync: vi.fn(), })); // Mock expo-auth-session vi.mock('expo-auth-session', () => ({ makeRedirectUri: vi.fn(() => 'plyr-dial://redirect'), })); // Mock react-native Platform vi.mock('react-native', () => ({ Platform: { OS: 'web' }, })); // Mock global fetch const mockFetch = vi.fn(); vi.stubGlobal('fetch', mockFetch); import * as WebBrowser from 'expo-web-browser'; import { getAuthState, isAuthenticated, login, logout, getMe, authedFetch, } from '../lib/auth'; // We need to reset the module-level _authState between tests. // Since it's module-scoped, we'll use logout() to reset it. beforeEach(async () => { vi.clearAllMocks(); mockFetch.mockReset(); // Reset auth state by calling logout try { await logout(); } catch {} }); describe('auth.ts', () => { describe('getAuthState / isAuthenticated', () => { it('should start unauthenticated', () => { expect(isAuthenticated()).toBe(false); expect(getAuthState().sessionId).toBeNull(); }); it('should reflect authenticated state after login', async () => { // Mock the OAuth browser flow vi.mocked(WebBrowser.openAuthSessionAsync).mockResolvedValueOnce({ type: 'success', url: 'plyr-dial://redirect?token=exchange-token-123', }); // Mock the token exchange mockFetch.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({ session_id: 'sess-abc' }), }); // Mock the /auth/me call mockFetch.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({ handle: 'testuser', display_name: 'Test User' }), }); await login('testuser'); expect(isAuthenticated()).toBe(true); expect(getAuthState().sessionId).toBe('sess-abc'); expect(getAuthState().handle).toBe('testuser'); expect(getAuthState().displayName).toBe('Test User'); }); }); describe('login', () => { it('should complete full OAuth flow', async () => { vi.mocked(WebBrowser.openAuthSessionAsync).mockResolvedValueOnce({ type: 'success', url: 'plyr-dial://redirect?token=exch-tok', }); // Token exchange mockFetch.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({ session_id: 'sess-123' }), }); // /auth/me mockFetch.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({ handle: 'myhandle', display_name: 'My Name' }), }); const state = await login('myhandle'); expect(state.sessionId).toBe('sess-123'); expect(state.handle).toBe('myhandle'); expect(state.displayName).toBe('My Name'); // Verify the exchange call expect(mockFetch).toHaveBeenCalledWith( 'https://api.plyr.fm/auth/exchange', expect.objectContaining({ method: 'POST', body: JSON.stringify({ token: 'exch-tok' }), }), ); }); it('should throw when browser auth is cancelled', async () => { vi.mocked(WebBrowser.openAuthSessionAsync).mockResolvedValueOnce({ type: 'cancel', url: undefined as any, }); await expect(login('test')).rejects.toThrow('Authentication cancelled or failed'); }); it('should throw when callback has no token', async () => { vi.mocked(WebBrowser.openAuthSessionAsync).mockResolvedValueOnce({ type: 'success', url: 'plyr-dial://redirect?error=denied', }); await expect(login('test')).rejects.toThrow('No exchange token in callback'); }); it('should throw when token exchange fails', async () => { vi.mocked(WebBrowser.openAuthSessionAsync).mockResolvedValueOnce({ type: 'success', url: 'plyr-dial://redirect?token=bad-token', }); mockFetch.mockResolvedValueOnce({ ok: false, status: 401, }); await expect(login('test')).rejects.toThrow('Token exchange failed: 401'); }); it('should still set session when /auth/me fails', async () => { vi.mocked(WebBrowser.openAuthSessionAsync).mockResolvedValueOnce({ type: 'success', url: 'plyr-dial://redirect?token=exch-tok', }); // Token exchange succeeds mockFetch.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({ session_id: 'sess-456' }), }); // /auth/me fails mockFetch.mockResolvedValueOnce({ ok: false, status: 500, }); const state = await login('fallback'); expect(state.sessionId).toBe('sess-456'); expect(state.handle).toBe('fallback'); expect(state.displayName).toBeNull(); }); }); describe('logout', () => { it('should clear auth state', async () => { // First log in vi.mocked(WebBrowser.openAuthSessionAsync).mockResolvedValueOnce({ type: 'success', url: 'plyr-dial://redirect?token=tok', }); mockFetch.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({ session_id: 'sess-out' }), }); mockFetch.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({ handle: 'x', display_name: 'X' }), }); await login('x'); expect(isAuthenticated()).toBe(true); // Logout mockFetch.mockResolvedValueOnce({ ok: true }); await logout(); expect(isAuthenticated()).toBe(false); expect(getAuthState().sessionId).toBeNull(); }); it('should call the logout API endpoint', async () => { // Set up authenticated state vi.mocked(WebBrowser.openAuthSessionAsync).mockResolvedValueOnce({ type: 'success', url: 'plyr-dial://redirect?token=tok', }); mockFetch.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({ session_id: 'sess-logout' }), }); mockFetch.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({ handle: 'y', display_name: 'Y' }), }); await login('y'); mockFetch.mockResolvedValueOnce({ ok: true }); await logout(); expect(mockFetch).toHaveBeenCalledWith( 'https://api.plyr.fm/auth/logout', expect.objectContaining({ method: 'POST', headers: expect.objectContaining({ Authorization: 'Bearer sess-logout', }), }), ); }); it('should clear state even if API call fails', async () => { // Set up authenticated state vi.mocked(WebBrowser.openAuthSessionAsync).mockResolvedValueOnce({ type: 'success', url: 'plyr-dial://redirect?token=tok', }); mockFetch.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({ session_id: 'sess-fail' }), }); mockFetch.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({ handle: 'z', display_name: 'Z' }), }); await login('z'); // Logout API fails mockFetch.mockRejectedValueOnce(new Error('Network error')); await logout(); expect(isAuthenticated()).toBe(false); }); it('should be a no-op when not authenticated', async () => { await logout(); expect(mockFetch).not.toHaveBeenCalled(); }); }); describe('getMe', () => { it('should throw when not authenticated', async () => { await expect(getMe()).rejects.toThrow('Not authenticated'); }); it('should fetch current user when authenticated', async () => { // Set up authenticated state vi.mocked(WebBrowser.openAuthSessionAsync).mockResolvedValueOnce({ type: 'success', url: 'plyr-dial://redirect?token=tok', }); mockFetch.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({ session_id: 'sess-me' }), }); mockFetch.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({ handle: 'me', display_name: 'Me' }), }); await login('me'); // Now test getMe mockFetch.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({ handle: 'me', display_name: 'Me', email: 'me@test.com' }), }); const user = await getMe(); expect(user.handle).toBe('me'); expect(mockFetch).toHaveBeenCalledWith( 'https://api.plyr.fm/auth/me', expect.objectContaining({ headers: expect.objectContaining({ Authorization: 'Bearer sess-me', }), }), ); }); }); describe('authedFetch', () => { it('should throw when not authenticated', async () => { await expect(authedFetch('/tracks')).rejects.toThrow('Not authenticated'); }); it('should include Authorization header when authenticated', async () => { // Set up authenticated state vi.mocked(WebBrowser.openAuthSessionAsync).mockResolvedValueOnce({ type: 'success', url: 'plyr-dial://redirect?token=tok', }); mockFetch.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({ session_id: 'sess-fetch' }), }); mockFetch.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({ handle: 'f', display_name: 'F' }), }); await login('f'); mockFetch.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({}) }); await authedFetch('/tracks', { method: 'POST' }); expect(mockFetch).toHaveBeenCalledWith( 'https://api.plyr.fm/tracks', expect.objectContaining({ method: 'POST', headers: expect.objectContaining({ Authorization: 'Bearer sess-fetch', 'Content-Type': 'application/json', }), }), ); }); }); });