apiAuthenticate.test.ts 1.7 KB

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