import { afterEach, describe, expect, it, vi } from 'vitest'; import { NextRequest } from 'next/server'; import { GET as screen } from '@/app/api/screen/route'; import { GET as vehicles } from '@/app/api/vehicles/route'; const originalEngine = process.env.ENGINE_URL; afterEach(() => { if (originalEngine === undefined) delete process.env.ENGINE_URL; else process.env.ENGINE_URL = originalEngine; vi.unstubAllGlobals(); }); const screening = () => screen(new NextRequest('http://localhost/api/screen?q=example')); const vehicle = () => vehicles(new NextRequest('http://localhost/api/vehicles?plate=AB123')); describe('source failure cannot mean absence', () => { it.each([screening, vehicle])('returns 503 for source failures and malformed responses', async (call) => { delete process.env.ENGINE_URL; for (const response of [new Response('down', { status: 503 }), Response.json({}), new Response('{')]) { vi.stubGlobal('fetch', vi.fn(async () => response)); const result = await call(); expect(result.status).toBe(503); expect(await result.json()).toEqual({ error: expect.objectContaining({ code: 'source_unavailable' }) }); } }); it('preserves an actual empty screening result', async () => { delete process.env.ENGINE_URL; vi.stubGlobal('fetch', vi.fn(async () => Response.json({ results: [] }))); expect(await (await screening()).json()).toEqual({ source: 'opensanctions', matches: [] }); }); it('preserves an actual missing vehicle', async () => { delete process.env.ENGINE_URL; vi.stubGlobal('fetch', vi.fn(async () => Response.json([]))); expect(await (await vehicle()).json()).toEqual({ vehicle: null }); }); it.each([screening, vehicle])('does not trust an old engine which can fabricate empty results', async (call) => { process.env.ENGINE_URL = 'https://engine.test'; vi.stubGlobal('fetch', vi.fn(async () => Response.json({ matches: [], vehicle: null }))); expect((await call()).status).toBe(503); expect(fetch).toHaveBeenCalledOnce(); }); it('accepts verified engine screening results', async () => { process.env.ENGINE_URL = 'https://engine.test'; vi.stubGlobal('fetch', vi.fn(async () => Response.json({ source: 'opensanctions', source_status: 'ok', matches: [] }))); expect((await screening()).status).toBe(200); }); });