apiAuthenticate.test.ts67 lines · main
| 1 | import { beforeEach, describe, expect, it, vi } from 'vitest' |
| 2 | |
| 3 | import { apiAuthenticate } from './apiAuthenticate' |
| 4 | |
| 5 | const mocks = vi.hoisted(() => { |
| 6 | return { |
| 7 | getUserClaims: vi.fn().mockResolvedValue({ |
| 8 | claims: { |
| 9 | sub: 'test-gotrue-id', |
| 10 | email: 'test@example.com', |
| 11 | }, |
| 12 | error: null, |
| 13 | }), |
| 14 | } |
| 15 | }) |
| 16 | |
| 17 | vi.mock('@/lib/gotrue', () => ({ |
| 18 | getUserClaims: mocks.getUserClaims, |
| 19 | })) |
| 20 | |
| 21 | describe('apiAuthenticate', () => { |
| 22 | const mockReq = { |
| 23 | headers: { |
| 24 | authorization: 'Bearer test-token', |
| 25 | }, |
| 26 | query: {}, |
| 27 | } as any |
| 28 | |
| 29 | const mockRes = {} as any |
| 30 | |
| 31 | beforeEach(() => { |
| 32 | vi.clearAllMocks() |
| 33 | mocks.getUserClaims.mockResolvedValue({ |
| 34 | claims: { |
| 35 | sub: 'test-gotrue-id', |
| 36 | email: 'test@example.com', |
| 37 | }, |
| 38 | error: null, |
| 39 | }) |
| 40 | }) |
| 41 | |
| 42 | it('should return error when authorization token is missing', async () => { |
| 43 | const reqWithoutToken = { ...mockReq, headers: {} } |
| 44 | const result = await apiAuthenticate(reqWithoutToken, mockRes) |
| 45 | expect(result).toStrictEqual({ error: new Error('missing access token') }) |
| 46 | }) |
| 47 | |
| 48 | it('should return error when auth user fetch fails', async () => { |
| 49 | mocks.getUserClaims.mockResolvedValue({ |
| 50 | claims: null, |
| 51 | error: new Error('Auth failed'), |
| 52 | }) |
| 53 | |
| 54 | const result = await apiAuthenticate(mockReq, mockRes) |
| 55 | expect(result).toStrictEqual({ error: new Error('Auth failed') }) |
| 56 | }) |
| 57 | |
| 58 | it('should return error when user does not exist', async () => { |
| 59 | mocks.getUserClaims.mockResolvedValue({ |
| 60 | claims: null, |
| 61 | error: null, |
| 62 | }) |
| 63 | |
| 64 | const result = await apiAuthenticate(mockReq, mockRes) |
| 65 | expect(result).toStrictEqual({ error: new Error('The user does not exist') }) |
| 66 | }) |
| 67 | }) |