import { createApiClient } from '@pipu/api-client'; import { describe, expect, it } from 'vitest'; import { checkServer, normalizeServerUrl } from './server'; describe('normalizeServerUrl', () => { it.each([ ['music.home.lan', 'https://music.home.lan'], [' https://music.home.lan/ ', 'https://music.home.lan'], ['http://192.168.1.10:8080', 'http://192.168.1.10:8080'], ['https://home.lan/pipu//', 'https://home.lan/pipu'], ])('%s → %s', (input, expected) => { expect(normalizeServerUrl(input)).toBe(expected); }); it.each(['', ' ', 'ftp://music.home.lan', 'https://'])('rejects %j', (input) => { expect(normalizeServerUrl(input)).toBeNull(); }); }); const info = { name: 'pipu-music', version: '0.1.0', api_version: 'v1', supported_locales: ['ru', 'en'], min_android_version_code: 100, }; function clientReturning(response: () => Response | Promise) { return createApiClient({ baseUrl: 'https://music.test', fetch: async () => response() }); } const json = (body: unknown, status = 200) => new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } }); describe('checkServer', () => { it('reports ok for a compatible server', async () => { await expect(checkServer(clientReturning(() => json(info)), 100)).resolves.toEqual({ status: 'ok', info }); }); it('reports unsupported_app when the app is too old', async () => { const res = await checkServer(clientReturning(() => json(info)), 99); expect(res.status).toBe('unsupported_app'); }); it('reports offline on network errors', async () => { const res = await checkServer( clientReturning(() => { throw new TypeError('Failed to fetch'); }), ); expect(res).toEqual({ status: 'offline', error: 'Failed to fetch' }); }); it('reports offline when the server does not answer in time', async () => { const client = createApiClient({ baseUrl: 'https://music.test', fetch: () => new Promise(() => {}) }); await expect(checkServer(client, undefined, 20)).resolves.toEqual({ status: 'offline', error: 'timeout' }); }); it('reports offline with the problem code on API errors', async () => { const res = await checkServer(clientReturning(() => json({ status: 500, code: 'common.internal' }, 500))); expect(res).toEqual({ status: 'offline', error: 'common.internal' }); }); });