54 lines
1.3 KiB
TypeScript
54 lines
1.3 KiB
TypeScript
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
|
import { getSession } from '@/lib/auth-simple'
|
|
|
|
// Mock next/headers
|
|
vi.mock('next/headers', () => ({
|
|
cookies: vi.fn().mockResolvedValue({
|
|
get: vi.fn().mockReturnValue({ name: 'better-auth.session_token', value: 'test-token' }),
|
|
}),
|
|
}))
|
|
|
|
// Mock fetch
|
|
const mockFetch = vi.fn()
|
|
global.fetch = mockFetch as any
|
|
|
|
describe('getSession', () => {
|
|
beforeEach(() => {
|
|
vi.clearAllMocks()
|
|
})
|
|
|
|
it('returns session data when auth API returns 200', async () => {
|
|
const mockSession = {
|
|
session: { token: 'test-token', expiresAt: new Date().toISOString() },
|
|
user: { id: 'user-123', email: 'test@example.com' },
|
|
}
|
|
|
|
mockFetch.mockResolvedValue(
|
|
new Response(JSON.stringify(mockSession), { status: 200 })
|
|
)
|
|
|
|
const result = await getSession()
|
|
|
|
expect(result).toEqual(mockSession)
|
|
expect(mockFetch).toHaveBeenCalled()
|
|
})
|
|
|
|
it('returns null when auth API returns non-200 status', async () => {
|
|
mockFetch.mockResolvedValue(
|
|
new Response(null, { status: 401 })
|
|
)
|
|
|
|
const result = await getSession()
|
|
|
|
expect(result).toBeNull()
|
|
})
|
|
|
|
it('returns null when an error occurs', async () => {
|
|
mockFetch.mockRejectedValue(new Error('Network error'))
|
|
|
|
const result = await getSession()
|
|
|
|
expect(result).toBeNull()
|
|
})
|
|
})
|