downloader.test.ts 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. import type { AxiosRequestConfig } from 'axios';
  2. import { beforeEach, describe, expect, it, vi } from 'vitest';
  3. import { FileDownloader } from './downloader';
  4. describe('fileDownloader', () => {
  5. let fileDownloader: FileDownloader;
  6. const mockAxiosInstance = {
  7. get: vi.fn(),
  8. } as any;
  9. beforeEach(() => {
  10. fileDownloader = new FileDownloader(mockAxiosInstance);
  11. });
  12. it('should create an instance of FileDownloader', () => {
  13. expect(fileDownloader).toBeInstanceOf(FileDownloader);
  14. });
  15. it('should download a file and return a Blob', async () => {
  16. const url = 'https://example.com/file';
  17. const mockBlob = new Blob(['file content'], { type: 'text/plain' });
  18. const mockResponse: Blob = mockBlob;
  19. mockAxiosInstance.get.mockResolvedValueOnce(mockResponse);
  20. const result = await fileDownloader.download(url);
  21. expect(result).toBeInstanceOf(Blob);
  22. expect(result).toEqual(mockBlob);
  23. expect(mockAxiosInstance.get).toHaveBeenCalledWith(url, {
  24. responseType: 'blob',
  25. });
  26. });
  27. it('should merge provided config with default config', async () => {
  28. const url = 'https://example.com/file';
  29. const mockBlob = new Blob(['file content'], { type: 'text/plain' });
  30. const mockResponse: Blob = mockBlob;
  31. mockAxiosInstance.get.mockResolvedValueOnce(mockResponse);
  32. const customConfig: AxiosRequestConfig = {
  33. headers: { 'Custom-Header': 'value' },
  34. };
  35. const result = await fileDownloader.download(url, customConfig);
  36. expect(result).toBeInstanceOf(Blob);
  37. expect(result).toEqual(mockBlob);
  38. expect(mockAxiosInstance.get).toHaveBeenCalledWith(url, {
  39. ...customConfig,
  40. responseType: 'blob',
  41. });
  42. });
  43. it('should handle errors gracefully', async () => {
  44. const url = 'https://example.com/file';
  45. mockAxiosInstance.get.mockRejectedValueOnce(new Error('Network Error'));
  46. await expect(fileDownloader.download(url)).rejects.toThrow('Network Error');
  47. });
  48. it('should handle empty URL gracefully', async () => {
  49. const url = '';
  50. mockAxiosInstance.get.mockRejectedValueOnce(
  51. new Error('Request failed with status code 404'),
  52. );
  53. await expect(fileDownloader.download(url)).rejects.toThrow(
  54. 'Request failed with status code 404',
  55. );
  56. });
  57. it('should handle null URL gracefully', async () => {
  58. const url = null as unknown as string;
  59. mockAxiosInstance.get.mockRejectedValueOnce(
  60. new Error('Request failed with status code 404'),
  61. );
  62. await expect(fileDownloader.download(url)).rejects.toThrow(
  63. 'Request failed with status code 404',
  64. );
  65. });
  66. });