You can use jest.spyOn() to mock every DOM manipulation.
E.g.
index.ts:
export const downloadPdfDataContent = (title: string, url: string): void => {
const link = document.createElement('a');
link.target = title;
link.href = url;
link.download = title;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(url);
};
index.test.ts:
import { downloadPdfDataContent } from '.';
describe('67634069', () => {
afterEach(() => {
jest.restoreAllMocks();
});
it('should pass', () => {
const mAnchor = ({
target: '',
href: '',
download: '',
click: jest.fn(),
} as unknown) as HTMLAnchorElement;
const createElementSpy = jest.spyOn(document, 'createElement').mockReturnValueOnce(mAnchor);
const appendChildSpy = jest.spyOn(document.body, 'appendChild').mockImplementation();
const removeChildSpy = jest.spyOn(document.body, 'removeChild').mockImplementation();
URL.revokeObjectURL = jest.fn();
downloadPdfDataContent('teresa teng', 'example.com');
expect(createElementSpy).toBeCalledWith('a');
expect(appendChildSpy).toBeCalledWith(
expect.objectContaining({
target: 'teresa teng',
href: 'example.com',
download: 'teresa teng',
})
);
expect(mAnchor.click).toBeCalledTimes(1);
expect(removeChildSpy).toBeCalledWith(
expect.objectContaining({
target: 'teresa teng',
href: 'example.com',
download: 'teresa teng',
})
);
expect(URL.revokeObjectURL).toBeCalledWith('example.com');
});
});
test result:
PASS examples/67634069/index.test.ts (8.691 s)
67634069
✓ should pass (4 ms)
----------|---------|----------|---------|---------|-------------------
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: 9.612 s
fileURLcome from? And why you try toappendChildaurlstring?removeChild(link)?