Here is my solution:
index.ts:
export default function download(blobUrl, fileName) { const link = document.createElement('a'); link.setAttribute('href', blobUrl); link.setAttribute('download', `${fileName}.pdf`); link.style.display = 'none'; document.body.appendChild(link); link.click(); document.body.removeChild(link); }
index.spec.ts:
import download from './'; describe('download', () => { test('should download correctly', () => { const mLink = { href: '', click: jest.fn(), download: '', style: { display: '' }, setAttribute: jest.fn() } as any; const createElementSpy = jest.spyOn(document, 'createElement').mockReturnValueOnce(mLink); document.body.appendChild = jest.fn(); document.body.removeChild = jest.fn(); download('blobUrl', 'go'); expect(createElementSpy).toBeCalledWith('a'); expect(mLink.setAttribute.mock.calls.length).toBe(2); expect(mLink.setAttribute.mock.calls[0]).toEqual(['href', 'blobUrl']); expect(mLink.setAttribute.mock.calls[1]).toEqual(['download', 'go.pdf']); expect(mLink.style.display).toBe('none'); expect(document.body.appendChild).toBeCalledWith(mLink); expect(mLink.click).toBeCalled(); expect(document.body.removeChild).toBeCalledWith(mLink); }); });
Unit test result with 100% coverage:
PASS src/stackoverflow/58445250/index.spec.ts download ✓ should download correctly (8ms) ----------|----------|----------|----------|----------|-------------------| File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s | ----------|----------|----------|----------|----------|-------------------| All files | 100 | 100 | 100 | 100 | | index.ts | 100 | 100 | 100 | 100 | | ----------|----------|----------|----------|----------|-------------------| Test Suites: 1 passed, 1 total Tests: 1 passed, 1 total Snapshots: 0 total Time: 4.571s, estimated 8s
Source code: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/58445250
documentobject, then you can check if a link is added pointing to the given file and even if the link was clicked.documentyou should be able to either disable removing (just check if it's called) or otherwise keep the node added even if it's removed. Remember that a mockeddocumentwill also be able to return a mocked<a>node.