From 77f45fc7ec3d23ee0aeda18faa746d7cf4e78bbc Mon Sep 17 00:00:00 2001 From: arsam Date: Fri, 18 Sep 2026 23:15:14 +0330 Subject: [PATCH] Import tests: cshare-app/src/test/api Import the existing local project snapshot. This commit organizes existing files; it does not represent newly developed functionality. --- cshare-app/src/test/api.test.js | 82 +++++++++++++++++++++++++++++++++ 1 file changed, 82 insertions(+) create mode 100644 cshare-app/src/test/api.test.js diff --git a/cshare-app/src/test/api.test.js b/cshare-app/src/test/api.test.js new file mode 100644 index 0000000..2d5854d --- /dev/null +++ b/cshare-app/src/test/api.test.js @@ -0,0 +1,82 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest'; + +// Mock fetch globally +const mockFetch = vi.fn(); +global.fetch = mockFetch; + +// We import after setting up mocks +const mockXhr = { + open: vi.fn(), + send: vi.fn(), + setRequestHeader: vi.fn(), + withCredentials: false, + upload: { onprogress: null }, + onload: null, + onerror: null, +}; + +vi.stubGlobal('XMLHttpRequest', vi.fn(() => mockXhr)); + +// Helper to reset module cache between tests +beforeEach(() => { + vi.clearAllMocks(); + mockXhr.status = 200; + mockXhr.responseText = '{}'; +}); + +describe('api helpers', () => { + it('downloadUrl returns the correct path', async () => { + const { downloadUrl } = await import('../lib/api.js'); + const url = downloadUrl('abc123'); + expect(url).toContain('/api/v1/links/abc123/download'); + }); + + it('previewUrl returns the correct path', async () => { + const { previewUrl } = await import('../lib/api.js'); + const url = previewUrl('xyz'); + expect(url).toContain('/api/v1/links/xyz/preview'); + }); + + it('listFiles parses response data array', async () => { + const files = [{ id: '1', originalName: 'test.txt' }]; + mockFetch.mockResolvedValueOnce({ + ok: true, + status: 200, + json: async () => ({ data: files }), + }); + + const { listFiles } = await import('../lib/api.js'); + const result = await listFiles(); + expect(result).toEqual(files); + expect(mockFetch).toHaveBeenCalledWith( + expect.stringContaining('/api/v1/files'), + expect.objectContaining({ credentials: 'include' }), + ); + }); + + it('deleteFile calls DELETE and handles 204', async () => { + mockFetch.mockResolvedValueOnce({ + ok: true, + status: 204, + json: async () => { throw new Error('no body'); }, + }); + + const { deleteFile } = await import('../lib/api.js'); + await expect(deleteFile('file-id')).resolves.toBeUndefined(); + expect(mockFetch).toHaveBeenCalledWith( + expect.stringContaining('/api/v1/files/file-id'), + expect.objectContaining({ method: 'DELETE' }), + ); + }); + + it('listFiles throws on non-ok response', async () => { + mockFetch.mockResolvedValueOnce({ + ok: false, + status: 401, + json: async () => ({ error: 'Unauthorized' }), + }); + + const { listFiles } = await import('../lib/api.js'); + await expect(listFiles()).rejects.toThrow('Unauthorized'); + }); +});