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.
This commit is contained in:
arsam
2026-09-18 23:15:14 +03:30
parent 5d20e7d099
commit 77f45fc7ec
+82
View File
@@ -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');
});
});