Here is the solution I came up with:
index.ts
:
export default function saveFile(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 saveFile from './';
describe('save File', () => {
test('should save file 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();
saveFile('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 results are in with full coverage achieved:
PASS src/stackoverflow/58445250/index.spec.ts
save File
✓ should save file 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
Check out the source code here: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/58445250