|
| 1 | +import { beforeEach, describe, expect, it, vi } from 'vitest'; |
| 2 | + |
| 3 | +const mocks = vi.hoisted(() => { |
| 4 | + const getUser = vi.fn(); |
| 5 | + const eq = vi.fn(() => ({ single: async () => ({ data: { id: 'row-1', username: 'cha0spunk', display_name: 'cha0spunk' }, error: null }) })); |
| 6 | + const client = { auth: { getUser }, from: vi.fn(() => ({ select: () => ({ eq }) })) }; |
| 7 | + return { getUser, eq, client, createSupabaseServerClientWithToken: vi.fn(async () => client) }; |
| 8 | +}); |
| 9 | + |
| 10 | +vi.mock('@/lib/supabase.js', () => ({ |
| 11 | + createSupabaseServerClientWithToken: mocks.createSupabaseServerClientWithToken |
| 12 | +})); |
| 13 | + |
| 14 | +const get = (authorization) => new Request('https://example.com/api/profile', { headers: authorization ? { authorization } : {} }); |
| 15 | + |
| 16 | +describe('own profile', () => { |
| 17 | + beforeEach(() => { |
| 18 | + vi.clearAllMocks(); |
| 19 | + mocks.getUser.mockResolvedValue({ data: { user: { id: 'auth-1' } }, error: null }); |
| 20 | + }); |
| 21 | + |
| 22 | + it('finds the caller by token, not by username', async () => { |
| 23 | + const { GET } = await import('./route.js'); |
| 24 | + const response = await GET(get('Bearer t')); |
| 25 | + expect(response.status).toBe(200); |
| 26 | + expect(mocks.eq).toHaveBeenCalledWith('auth_user_id', 'auth-1'); |
| 27 | + expect((await response.json()).user.username).toBe('cha0spunk'); |
| 28 | + }); |
| 29 | + |
| 30 | + it('401s without a token', async () => { |
| 31 | + const { GET } = await import('./route.js'); |
| 32 | + expect((await GET(get())).status).toBe(401); |
| 33 | + expect(mocks.createSupabaseServerClientWithToken).not.toHaveBeenCalled(); |
| 34 | + }); |
| 35 | + |
| 36 | + it('401s with a token auth rejects', async () => { |
| 37 | + mocks.getUser.mockResolvedValue({ data: { user: null }, error: new Error('bad jwt') }); |
| 38 | + const { GET } = await import('./route.js'); |
| 39 | + expect((await GET(get('Bearer nope'))).status).toBe(401); |
| 40 | + }); |
| 41 | +}); |
0 commit comments