/** * End-to-end connect flow: URL validation → version probe → token validation → * persistence. Uses a mocked fetch and an in-memory SecureStore so the test * exercises the real store wiring without touching native modules. */ import * as SecureStore from 'expo-secure-store'; import { useAccountsStore } from '@/core/accounts/accounts-store'; import { ConnectError, connectToInstance } from './connect'; // jest.mock is hoisted above the imports by babel-jest at runtime. jest.mock('expo-secure-store', () => { const store = new Map(); return { getItemAsync: jest.fn(async (key: string) => store.get(key) ?? null), setItemAsync: jest.fn(async (key: string, value: string) => { store.set(key, value); }), deleteItemAsync: jest.fn(async (key: string) => { store.delete(key); }), }; }); function res(body: string, status = 200): Response { return { ok: status >= 200 && status < 300, status, headers: { get: () => null }, text: async () => body, } as unknown as Response; } function userResponse(status = 200): Response { if (status === 200) { return res(JSON.stringify({ login: 'alice', id: 7, full_name: 'Alice', avatar_url: 'https://x/a.png' })); } return res('', status); } function mockFetch(userStatus = 200) { return jest.fn(async (url: string) => { if (url.endsWith('/api/v1/version')) return res(JSON.stringify({ version: '1.21.0' })); if (url.endsWith('/api/v1/user')) return userResponse(userStatus); return res('{}', 404); }); } async function codeOf(fn: () => Promise): Promise { try { await fn(); return undefined; } catch (error) { return error instanceof ConnectError ? error.code : undefined; } } describe('connectToInstance', () => { beforeEach(() => { useAccountsStore.setState({ instances: [], accounts: [], activeAccountId: null, tokens: {}, hydrated: true, }); jest.clearAllMocks(); }); it('validates the token, persists the account and stores the token securely', async () => { global.fetch = mockFetch() as unknown as typeof fetch; const result = await connectToInstance({ baseUrl: 'codeberg.org', token: 'pat-123' }); expect(result.instance.baseUrl).toBe('https://codeberg.org'); expect(result.instance.version).toBe('1.21.0'); expect(result.account.login).toBe('alice'); const state = useAccountsStore.getState(); expect(state.accounts).toHaveLength(1); expect(state.activeAccountId).toBe(result.account.id); expect(state.tokens[result.account.id]).toBe('pat-123'); expect(state.instances[0].baseUrl).toBe('https://codeberg.org'); // Token written through SecureStore, never to plain storage state. expect(SecureStore.setItemAsync).toHaveBeenCalledWith( `token.${result.account.id}`, 'pat-123', expect.objectContaining({ keychainService: 'gitea-native.credentials' }), ); expect(JSON.stringify(state.accounts)).not.toContain('pat-123'); }); it('rejects the token when the instance returns 401', async () => { global.fetch = mockFetch(401) as unknown as typeof fetch; expect(await codeOf(() => connectToInstance({ baseUrl: 'codeberg.org', token: 'bad' }))).toBe( 'auth', ); }); it('treats a 404 on /user as “not a Gitea instance”', async () => { global.fetch = mockFetch(404) as unknown as typeof fetch; expect(await codeOf(() => connectToInstance({ baseUrl: 'codeberg.org', token: 'x' }))).toBe( 'url', ); }); it('reports a network failure distinctly from a bad token', async () => { global.fetch = jest.fn(async () => { throw new TypeError('Network request failed'); }) as unknown as typeof fetch; expect(await codeOf(() => connectToInstance({ baseUrl: 'codeberg.org', token: 'x' }))).toBe( 'network', ); }); it('rejects insecure remote HTTP before any request', async () => { const fetchImpl = mockFetch(); global.fetch = fetchImpl as unknown as typeof fetch; expect(await codeOf(() => connectToInstance({ baseUrl: 'http://codeberg.org', token: 'x' }))).toBe( 'insecure', ); expect(fetchImpl).not.toHaveBeenCalled(); }); it('requires a non-empty token', async () => { const fetchImpl = mockFetch(); global.fetch = fetchImpl as unknown as typeof fetch; expect(await codeOf(() => connectToInstance({ baseUrl: 'codeberg.org', token: ' ' }))).toBe( 'auth', ); expect(fetchImpl).not.toHaveBeenCalled(); }); it('re-adding the same user refreshes the account instead of duplicating it', async () => { global.fetch = mockFetch() as unknown as typeof fetch; const first = await connectToInstance({ baseUrl: 'codeberg.org', token: 'pat-1' }); const second = await connectToInstance({ baseUrl: 'https://codeberg.org/', token: 'pat-2' }); expect(second.account.id).toBe(first.account.id); expect(useAccountsStore.getState().accounts).toHaveLength(1); expect(useAccountsStore.getState().tokens[first.account.id]).toBe('pat-2'); }); });