import { afterEach, describe, expect, it, vi } from 'vitest'; function installBrowser() { Object.defineProperty(globalThis, 'window', { configurable: true, value: { location: { origin: 'https://rentaldrivego.ma', hostname: 'rentaldrivego.ma', }, }, }); } afterEach(() => { Reflect.deleteProperty(globalThis, 'window'); delete process.env.API_INTERNAL_URL; delete process.env.NEXT_PUBLIC_API_URL; delete process.env.NEXT_PUBLIC_HOMEPAGE_DIRECT_API; vi.resetModules(); }); describe('homepage API base URL', () => { it('keeps API URLs that already include the version prefix', async () => { const { normalizeApiBase } = await import('@/lib/api'); expect(normalizeApiBase('https://api.rentaldrivego.ma/api/v1')).toBe('https://api.rentaldrivego.ma/api/v1'); }); it('adds the version prefix when production env only contains the API host', async () => { const { normalizeApiBase } = await import('@/lib/api'); expect(normalizeApiBase('https://api.rentaldrivego.ma')).toBe('https://api.rentaldrivego.ma/api/v1'); }); it('normalizes trailing slashes before appending the version prefix', async () => { const { normalizeApiBase } = await import('@/lib/api'); expect(normalizeApiBase('https://api.rentaldrivego.ma/')).toBe('https://api.rentaldrivego.ma/api/v1'); }); it('uses the same-origin API proxy in browsers by default', async () => { installBrowser(); process.env.NEXT_PUBLIC_API_URL = 'https://api.rentaldrivego.ma/api/v1'; const { API_BASE } = await import('@/lib/api'); expect(API_BASE).toBe('/api/v1'); }); it('allows direct browser API calls only when explicitly enabled', async () => { installBrowser(); process.env.NEXT_PUBLIC_API_URL = 'https://api.rentaldrivego.ma'; process.env.NEXT_PUBLIC_HOMEPAGE_DIRECT_API = 'true'; const { API_BASE } = await import('@/lib/api'); expect(API_BASE).toBe('https://api.rentaldrivego.ma/api/v1'); }); it('uses the internal API URL on the server', async () => { process.env.API_INTERNAL_URL = 'http://api:4000/api/v1'; const { API_BASE } = await import('@/lib/api'); expect(API_BASE).toBe('http://api:4000/api/v1'); }); });