apiWrappers.test.ts 2.0 KB

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