|
| 1 | +/** |
| 2 | + * Copyright since 2025 Mifos Initiative |
| 3 | + * |
| 4 | + * This Source Code Form is subject to the terms of the Mozilla Public |
| 5 | + * License, v. 2.0. If a copy of the MPL was not distributed with this |
| 6 | + * file, You can obtain one at http://mozilla.org/MPL/2.0/. |
| 7 | + */ |
| 8 | + |
| 9 | +import { downloadBlob } from './file-download.utils'; |
| 10 | + |
| 11 | +describe('downloadBlob', () => { |
| 12 | + const objectUrl = 'blob:report-download'; |
| 13 | + let createObjectURLSpy: jest.SpyInstance; |
| 14 | + let revokeObjectURLSpy: jest.SpyInstance; |
| 15 | + |
| 16 | + beforeEach(() => { |
| 17 | + jest.useFakeTimers(); |
| 18 | + Object.defineProperty(URL, 'createObjectURL', { |
| 19 | + configurable: true, |
| 20 | + value: jest.fn() |
| 21 | + }); |
| 22 | + Object.defineProperty(URL, 'revokeObjectURL', { |
| 23 | + configurable: true, |
| 24 | + value: jest.fn() |
| 25 | + }); |
| 26 | + createObjectURLSpy = jest.spyOn(URL, 'createObjectURL').mockReturnValue(objectUrl); |
| 27 | + revokeObjectURLSpy = jest.spyOn(URL, 'revokeObjectURL').mockImplementation(); |
| 28 | + }); |
| 29 | + |
| 30 | + afterEach(() => { |
| 31 | + jest.runOnlyPendingTimers(); |
| 32 | + jest.useRealTimers(); |
| 33 | + createObjectURLSpy.mockRestore(); |
| 34 | + revokeObjectURLSpy.mockRestore(); |
| 35 | + }); |
| 36 | + |
| 37 | + it('creates and clicks a temporary download link', () => { |
| 38 | + const clickSpy = jest.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(); |
| 39 | + const blob = new Blob(['report'], { type: 'text/plain' }); |
| 40 | + |
| 41 | + downloadBlob(blob, 'client-report.xlsx'); |
| 42 | + |
| 43 | + const link = document.body.querySelector('a[download="client-report.xlsx"]') as HTMLAnchorElement; |
| 44 | + expect(createObjectURLSpy).toHaveBeenCalledWith(blob); |
| 45 | + expect(link).toBeTruthy(); |
| 46 | + expect(link.href).toBe(objectUrl); |
| 47 | + expect(link.style.display).toBe('none'); |
| 48 | + expect(clickSpy).toHaveBeenCalledTimes(1); |
| 49 | + |
| 50 | + clickSpy.mockRestore(); |
| 51 | + }); |
| 52 | + |
| 53 | + it('removes the temporary link and revokes the object URL', () => { |
| 54 | + const clickSpy = jest.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(); |
| 55 | + |
| 56 | + downloadBlob(new Blob(['report']), 'client-report.xlsx'); |
| 57 | + |
| 58 | + expect(document.body.querySelector('a[download="client-report.xlsx"]')).toBeTruthy(); |
| 59 | + |
| 60 | + jest.runOnlyPendingTimers(); |
| 61 | + |
| 62 | + expect(document.body.querySelector('a[download="client-report.xlsx"]')).toBeNull(); |
| 63 | + expect(revokeObjectURLSpy).toHaveBeenCalledWith(objectUrl); |
| 64 | + |
| 65 | + clickSpy.mockRestore(); |
| 66 | + }); |
| 67 | +}); |
0 commit comments