| 1 |
// resize-image.test.js |
| 2 |
import { resizeImage } from '@shared/utils/resize-image'; |
| 3 |
|
| 4 |
describe('resizeImage', () => { |
| 5 |
beforeEach(() => { |
| 6 |
Object.defineProperty(global.Image.prototype, 'src', { |
| 7 |
set() { |
| 8 |
setTimeout(() => { |
| 9 |
this.width = 500; |
| 10 |
this.height = 500; |
| 11 |
this.onload(); |
| 12 |
}, 10); |
| 13 |
}, |
| 14 |
}); |
| 15 |
|
| 16 |
HTMLCanvasElement.prototype.getContext = () => ({ |
| 17 |
clearRect: jest.fn(), |
| 18 |
drawImage: jest.fn(), |
| 19 |
}); |
| 20 |
|
| 21 |
HTMLCanvasElement.prototype.toBlob = (callback, type) => { |
| 22 |
callback(new Blob(['mock'], { type })); |
| 23 |
}; |
| 24 |
|
| 25 |
global.URL.createObjectURL = jest.fn( |
| 26 |
() => 'blob:http://example.com/fake-url', |
| 27 |
); |
| 28 |
}); |
| 29 |
|
| 30 |
afterEach(() => { |
| 31 |
delete global.URL.createObjectURL; |
| 32 |
}); |
| 33 |
|
| 34 |
it('should resize image and return a blob URL', async () => { |
| 35 |
const result = await resizeImage('http://example.com/img.png', { |
| 36 |
size: { width: 64, height: 64 }, |
| 37 |
mimeType: 'image/png', |
| 38 |
}); |
| 39 |
|
| 40 |
expect(typeof result).toBe('string'); |
| 41 |
expect(result).toBe('blob:http://example.com/fake-url'); |
| 42 |
expect(global.URL.createObjectURL).toHaveBeenCalledWith(expect.any(Blob)); |
| 43 |
}); |
| 44 |
|
| 45 |
it('should throw if imageUrl is missing', async () => { |
| 46 |
await expect( |
| 47 |
resizeImage(null, { width: 64, height: 64 }, 'image/png'), |
| 48 |
).rejects.toThrow('Invalid imageUrl or size dimensions'); |
| 49 |
}); |
| 50 |
|
| 51 |
it('should throw if size is missing', async () => { |
| 52 |
await expect(resizeImage('http://example.com/img.png', {})).rejects.toThrow( |
| 53 |
'Invalid imageUrl or size dimensions', |
| 54 |
); |
| 55 |
}); |
| 56 |
|
| 57 |
it('should throw if size is not an object', async () => { |
| 58 |
await expect( |
| 59 |
resizeImage('http://example.com/img.png', 64, 'image/png'), |
| 60 |
).rejects.toThrow('Invalid imageUrl or size dimensions'); |
| 61 |
}); |
| 62 |
|
| 63 |
it('should throw if width or height are not valid numbers', async () => { |
| 64 |
await expect( |
| 65 |
resizeImage('http://example.com/img.png', { width: 0, height: 64 }), |
| 66 |
).rejects.toThrow('Invalid imageUrl or size dimensions'); |
| 67 |
|
| 68 |
await expect( |
| 69 |
resizeImage('http://example.com/img.png', { width: 64, height: -1 }), |
| 70 |
).rejects.toThrow('Invalid imageUrl or size dimensions'); |
| 71 |
|
| 72 |
await expect( |
| 73 |
resizeImage('http://example.com/img.png', { width: '64', height: 64 }), |
| 74 |
).rejects.toThrow('Invalid imageUrl or size dimensions'); |
| 75 |
}); |
| 76 |
}); |
| 77 |
|