|
| 1 | +import { httpClient } from '../connection/http.js'; |
| 2 | +import { downloadImageFromURLAsBase64 } from './base64.js'; |
| 3 | + |
| 4 | +jest.mock('../connection/http.js'); |
| 5 | + |
| 6 | +describe('downloadImageFromURLAsBase64()', () => { |
| 7 | + const mockHttpClient = { |
| 8 | + externalGet: jest.fn(), |
| 9 | + }; |
| 10 | + |
| 11 | + beforeEach(() => { |
| 12 | + jest.clearAllMocks(); |
| 13 | + (httpClient as jest.Mock).mockReturnValue(mockHttpClient); |
| 14 | + }); |
| 15 | + |
| 16 | + it('should convert a downloaded image to base64', async () => { |
| 17 | + const mockUrl = 'https://example.com/image.jpg'; |
| 18 | + const mockImageData = Buffer.from('image binary data'); |
| 19 | + |
| 20 | + mockHttpClient.externalGet.mockResolvedValue(mockImageData); |
| 21 | + |
| 22 | + const result = await downloadImageFromURLAsBase64(mockUrl); |
| 23 | + |
| 24 | + expect(result).toBe(mockImageData.toString('base64')); |
| 25 | + expect(httpClient).toHaveBeenCalledWith({ headers: { 'Content-Type': 'image/*' }, host: '' }); |
| 26 | + expect(mockHttpClient.externalGet).toHaveBeenCalledWith(mockUrl); |
| 27 | + }); |
| 28 | + |
| 29 | + it('should throw an error if the URL is invalid', async () => { |
| 30 | + const invalidUrl = 'invalid-url'; |
| 31 | + |
| 32 | + await expect(downloadImageFromURLAsBase64(invalidUrl)).rejects.toThrow('Invalid URL'); |
| 33 | + }); |
| 34 | + |
| 35 | + it('should throw an error if the image download fails', async () => { |
| 36 | + const mockUrl = 'https://example.com/image.jpg'; |
| 37 | + |
| 38 | + mockHttpClient.externalGet.mockRejectedValue(new Error('Network error')); |
| 39 | + |
| 40 | + await expect(downloadImageFromURLAsBase64(mockUrl)).rejects.toThrow('Failed to download image from URL'); |
| 41 | + expect(httpClient).toHaveBeenCalledWith({ headers: { 'Content-Type': 'image/*' }, host: '' }); |
| 42 | + expect(mockHttpClient.externalGet).toHaveBeenCalledWith(mockUrl); |
| 43 | + }); |
| 44 | + |
| 45 | + it('should handle empty response data gracefully', async () => { |
| 46 | + const mockUrl = 'https://example.com/image.jpg'; |
| 47 | + |
| 48 | + mockHttpClient.externalGet.mockResolvedValue(Buffer.alloc(0)); |
| 49 | + |
| 50 | + const result = await downloadImageFromURLAsBase64(mockUrl); |
| 51 | + |
| 52 | + expect(result).toBe(''); |
| 53 | + expect(httpClient).toHaveBeenCalledWith({ headers: { 'Content-Type': 'image/*' }, host: '' }); |
| 54 | + expect(mockHttpClient.externalGet).toHaveBeenCalledWith(mockUrl); |
| 55 | + }); |
| 56 | + |
| 57 | + it('should throw an error if the response is not a buffer', async () => { |
| 58 | + const mockUrl = 'wrong-url.com'; |
| 59 | + |
| 60 | + mockHttpClient.externalGet.mockResolvedValue('not a buffer'); |
| 61 | + |
| 62 | + await expect(downloadImageFromURLAsBase64(mockUrl)).rejects.toThrow('Invalid URL'); |
| 63 | + }); |
| 64 | +}); |
0 commit comments