apiWrappers.test.ts62 lines · main
| 1 | import type { JwtPayload } from '@supabase/supabase-js' |
| 2 | import type { NextApiRequest, NextApiResponse } from 'next' |
| 3 | import { beforeEach, describe, expect, it, vi } from 'vitest' |
| 4 | |
| 5 | import { apiAuthenticate } from './apiAuthenticate' |
| 6 | import apiWrapper from './apiWrapper' |
| 7 | import { ResponseError } from '@/types' |
| 8 | |
| 9 | vi.mock('@/lib/constants', () => ({ |
| 10 | IS_PLATFORM: true, |
| 11 | API_URL: 'https://api.example.com', |
| 12 | })) |
| 13 | |
| 14 | vi.mock('./apiAuthenticate', () => ({ |
| 15 | apiAuthenticate: vi.fn(), |
| 16 | })) |
| 17 | |
| 18 | describe('apiWrapper', () => { |
| 19 | const mockReq = {} as NextApiRequest |
| 20 | const mockRes = { |
| 21 | status: vi.fn().mockReturnThis(), |
| 22 | json: vi.fn().mockReturnThis(), |
| 23 | } as unknown as NextApiResponse |
| 24 | const mockHandler = vi.fn() |
| 25 | |
| 26 | beforeEach(() => { |
| 27 | vi.clearAllMocks() |
| 28 | }) |
| 29 | |
| 30 | it('should call handler directly when withAuth is false', async () => { |
| 31 | await apiWrapper(mockReq, mockRes, mockHandler, { withAuth: false }) |
| 32 | expect(mockHandler).toHaveBeenCalledWith(mockReq, mockRes, undefined) |
| 33 | expect(apiAuthenticate).not.toHaveBeenCalled() |
| 34 | }) |
| 35 | |
| 36 | it('should pass JWT claims to handler when withAuth is true', async () => { |
| 37 | const mockClaims: JwtPayload = { |
| 38 | iss: 'briven', |
| 39 | sub: 'user-123', |
| 40 | aud: 'authenticated', |
| 41 | exp: 9999999999, |
| 42 | iat: 1000000000, |
| 43 | role: 'authenticated', |
| 44 | aal: 'aal1', |
| 45 | session_id: 'session-123', |
| 46 | } |
| 47 | vi.mocked(apiAuthenticate).mockResolvedValue(mockClaims) |
| 48 | |
| 49 | await apiWrapper(mockReq, mockRes, mockHandler, { withAuth: true }) |
| 50 | expect(apiAuthenticate).toHaveBeenCalledWith(mockReq, mockRes) |
| 51 | expect(mockHandler).toHaveBeenCalledWith(mockReq, mockRes, mockClaims) |
| 52 | }) |
| 53 | |
| 54 | it('should return 401 when authentication fails', async () => { |
| 55 | const mockError = { error: new ResponseError('Invalid token') } |
| 56 | vi.mocked(apiAuthenticate).mockResolvedValue(mockError) |
| 57 | |
| 58 | await apiWrapper(mockReq, mockRes, mockHandler, { withAuth: true }) |
| 59 | expect(mockRes.status).toHaveBeenCalledWith(401) |
| 60 | expect(mockHandler).not.toHaveBeenCalled() |
| 61 | }) |
| 62 | }) |