|
| 1 | +import { beforeEach, describe, expect, it, vi } from 'vitest'; |
| 2 | + |
| 3 | +import { getUserAuth } from '../auth'; |
| 4 | + |
| 5 | +// Mock auth constants |
| 6 | +let mockEnableClerk = false; |
| 7 | +let mockEnableNextAuth = false; |
| 8 | + |
| 9 | +vi.mock('@/const/auth', () => ({ |
| 10 | + get enableClerk() { |
| 11 | + return mockEnableClerk; |
| 12 | + }, |
| 13 | + get enableNextAuth() { |
| 14 | + return mockEnableNextAuth; |
| 15 | + }, |
| 16 | +})); |
| 17 | + |
| 18 | +vi.mock('@/libs/clerk-auth', () => ({ |
| 19 | + ClerkAuth: class { |
| 20 | + async getAuth() { |
| 21 | + return { |
| 22 | + clerkAuth: { |
| 23 | + redirectToSignIn: vi.fn(), |
| 24 | + }, |
| 25 | + userId: 'clerk-user-id', |
| 26 | + }; |
| 27 | + } |
| 28 | + }, |
| 29 | +})); |
| 30 | + |
| 31 | +vi.mock('@/libs/next-auth/edge', () => ({ |
| 32 | + default: { |
| 33 | + auth: vi.fn().mockResolvedValue({ |
| 34 | + user: { |
| 35 | + id: 'next-auth-user-id', |
| 36 | + }, |
| 37 | + }), |
| 38 | + }, |
| 39 | +})); |
| 40 | + |
| 41 | +describe('getUserAuth', () => { |
| 42 | + beforeEach(() => { |
| 43 | + vi.clearAllMocks(); |
| 44 | + mockEnableClerk = false; |
| 45 | + mockEnableNextAuth = false; |
| 46 | + }); |
| 47 | + |
| 48 | + it('should throw error when no auth method is enabled', async () => { |
| 49 | + await expect(getUserAuth()).rejects.toThrow('Auth method is not enabled'); |
| 50 | + }); |
| 51 | + |
| 52 | + it('should return clerk auth when clerk is enabled', async () => { |
| 53 | + mockEnableClerk = true; |
| 54 | + mockEnableNextAuth = false; |
| 55 | + |
| 56 | + const auth = await getUserAuth(); |
| 57 | + |
| 58 | + expect(auth).toEqual({ |
| 59 | + clerkAuth: { |
| 60 | + redirectToSignIn: expect.any(Function), |
| 61 | + }, |
| 62 | + userId: 'clerk-user-id', |
| 63 | + }); |
| 64 | + }); |
| 65 | + |
| 66 | + it('should return next auth when next auth is enabled', async () => { |
| 67 | + mockEnableClerk = false; |
| 68 | + mockEnableNextAuth = true; |
| 69 | + |
| 70 | + const auth = await getUserAuth(); |
| 71 | + |
| 72 | + expect(auth).toEqual({ |
| 73 | + nextAuth: { |
| 74 | + user: { |
| 75 | + id: 'next-auth-user-id', |
| 76 | + }, |
| 77 | + }, |
| 78 | + userId: 'next-auth-user-id', |
| 79 | + }); |
| 80 | + }); |
| 81 | + |
| 82 | + it('should prioritize clerk auth over next auth when both are enabled', async () => { |
| 83 | + mockEnableClerk = true; |
| 84 | + mockEnableNextAuth = true; |
| 85 | + |
| 86 | + const auth = await getUserAuth(); |
| 87 | + |
| 88 | + expect(auth).toEqual({ |
| 89 | + clerkAuth: { |
| 90 | + redirectToSignIn: expect.any(Function), |
| 91 | + }, |
| 92 | + userId: 'clerk-user-id', |
| 93 | + }); |
| 94 | + }); |
| 95 | +}); |
0 commit comments