import { describe, it, expect, vi, beforeEach } from 'vitest'; import { GET, POST } from '@/app/api/suppliers/route'; const mockToArray = vi.fn(); const mockSort = vi.fn(() => ({ toArray: mockToArray })); const mockFind = vi.fn(() => ({ sort: mockSort })); const mockInsertOne = vi.fn(); const mockCollection = vi.fn(() => ({ find: mockFind, insertOne: mockInsertOne, })); const mockDb = { collection: mockCollection }; vi.mock('@/lib/mongodb', () => ({ getDb: vi.fn(() => Promise.resolve(mockDb)), })); describe('GET /api/suppliers', () => { beforeEach(() => { vi.clearAllMocks(); }); it('returns sorted suppliers', async () => { const suppliers = [ { _id: 'sup1', name: 'Acme Foods' }, { _id: 'sup2', name: 'Best Produce' }, ]; mockToArray.mockResolvedValue(suppliers); const response = await GET(); const data = await response.json(); expect(mockCollection).toHaveBeenCalledWith('suppliers'); expect(mockSort).toHaveBeenCalledWith({ name: 1 }); expect(data).toEqual(suppliers); }); }); describe('POST /api/suppliers', () => { beforeEach(() => { vi.clearAllMocks(); }); it('creates supplier and returns 201', async () => { mockInsertOne.mockResolvedValue({ insertedId: 'new-sup' }); const request = new Request('http://localhost/api/suppliers', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name: 'Fresh Farms' }), }); const response = await POST(request); const data = await response.json(); expect(response.status).toBe(201); expect(data.name).toBe('Fresh Farms'); expect(data._id).toBe('new-sup'); expect(data.createdAt).toBeDefined(); }); it('returns 400 when name is missing', async () => { const request = new Request('http://localhost/api/suppliers', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({}), }); const response = await POST(request); const data = await response.json(); expect(response.status).toBe(400); expect(data.error).toBe('Name is required'); }); it('returns 400 when name is empty string', async () => { const request = new Request('http://localhost/api/suppliers', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name: '' }), }); const response = await POST(request); expect(response.status).toBe(400); }); });