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