import { describe, it, expect, vi, afterEach } from 'vitest' import { getUnidades } from './api' import { INVENTARIO_SEED } from '../data/unidades' import type { Unidad } from '../types' const unidadApi: Unidad = { codigo: 'U-101', modelo: '2RA', fechaEntrega: '2027-10-08', supEstacionamiento: 28.62, supConstruccion: 69.485, supExcedente: 21.336, precioSinAcabados: 4415000, precioConAcabados: 4579000, status: 'DISPONIBLE', desarrollo: 'DIAGONAL', } function respuestaOk(body: unknown): Response { return new Response(JSON.stringify(body), { status: 200, headers: { 'Content-Type': 'application/json' }, }) } afterEach(() => { vi.unstubAllGlobals() vi.restoreAllMocks() }) describe('getUnidades', () => { it('devuelve las unidades del API cuando la respuesta es OK', async () => { const fetchMock = vi.fn().mockResolvedValue(respuestaOk([unidadApi])) vi.stubGlobal('fetch', fetchMock) const resultado = await getUnidades() expect(fetchMock).toHaveBeenCalledWith('http://192.168.10.123:3000/api/unidades', {}) expect(resultado.usandoSeed).toBe(false) expect(resultado.unidades).toEqual([unidadApi]) }) it('hace fallback al seed local cuando la respuesta no es OK', async () => { const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) vi.stubGlobal( 'fetch', vi.fn().mockResolvedValue(new Response('error', { status: 500 })), ) const resultado = await getUnidades() expect(resultado.usandoSeed).toBe(true) expect(resultado.unidades).toEqual(INVENTARIO_SEED) expect(warn).toHaveBeenCalledOnce() }) it('hace fallback al seed local cuando falla la red', async () => { vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new TypeError('fetch failed'))) const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) const resultado = await getUnidades() expect(resultado.usandoSeed).toBe(true) expect(resultado.unidades).toEqual(INVENTARIO_SEED) expect(warn).toHaveBeenCalledOnce() }) })