upload.test.ts 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import { createClient } from '@supabase/supabase-js'
  2. import { beforeEach, describe, expect, it, vi } from 'vitest'
  3. import { uploadAttachment } from './upload'
  4. vi.mock('@supabase/supabase-js', () => ({
  5. createClient: vi.fn(),
  6. }))
  7. describe('uploadAttachment', () => {
  8. const mockUpload = vi.fn()
  9. const mockGetPublicUrl = vi.fn()
  10. const mockStorage = {
  11. from: vi.fn(() => ({
  12. upload: mockUpload,
  13. getPublicUrl: mockGetPublicUrl,
  14. })),
  15. }
  16. const mockBrivenClient = {
  17. storage: mockStorage,
  18. }
  19. const mockFile = new File(['test'], 'test.png', { type: 'image/png' })
  20. beforeEach(() => {
  21. vi.clearAllMocks()
  22. ;(createClient as any).mockReturnValue(mockBrivenClient)
  23. })
  24. it('uploads file and returns public URL when getUrl is true', async () => {
  25. mockUpload.mockResolvedValue({ data: { path: 'folder/test.png' }, error: null })
  26. mockGetPublicUrl.mockReturnValue({
  27. data: { publicUrl: 'https://cdn.supabase.io/folder/test.png' },
  28. })
  29. const url = await uploadAttachment('bucket', 'test.png', mockFile, true)
  30. expect(createClient).toHaveBeenCalled()
  31. expect(mockUpload).toHaveBeenCalledWith('test.png', mockFile, { cacheControl: '3600' })
  32. expect(mockGetPublicUrl).toHaveBeenCalledWith('folder/test.png')
  33. expect(url).toBe('https://cdn.supabase.io/folder/test.png')
  34. })
  35. it('returns undefined if upload succeeds but getUrl is false', async () => {
  36. mockUpload.mockResolvedValue({ data: { path: 'folder/test.png' }, error: null })
  37. const result = await uploadAttachment('bucket', 'test.png', mockFile, false)
  38. expect(result).toBeUndefined()
  39. })
  40. it('returns undefined and logs if upload fails', async () => {
  41. const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
  42. mockUpload.mockResolvedValue({ data: null, error: { message: 'Upload failed' } })
  43. const result = await uploadAttachment('bucket', 'test.png', mockFile)
  44. expect(result).toBeUndefined()
  45. expect(errorSpy).toHaveBeenCalledWith('Failed to upload:', { message: 'Upload failed' })
  46. errorSpy.mockRestore()
  47. })
  48. it('returns undefined if getPublicUrl returns no data', async () => {
  49. mockUpload.mockResolvedValue({ data: { path: 'folder/test.png' }, error: null })
  50. mockGetPublicUrl.mockReturnValue({ data: null })
  51. const result = await uploadAttachment('bucket', 'test.png', mockFile, true)
  52. expect(result).toBeUndefined()
  53. })
  54. })