I have a third-party function, return from a parent function, I am able to test the parent function call, toHaveBeenCalled but the nested return statement is not being tested. Definitely it needs to be mocked as it's a third-party function. The function looks like below:
import * as _html2canvas from 'html2canvas';
// tslint:disable-next-line: no-any
const html2canvas: any = _html2canvas;
export const downloadElement = (props: string, imageName: string): HTMLElement => {
const captureElement = document.querySelector(props);
const canvasBg = window.getComputedStyle(document.body, null).getPropertyValue('background-color');
const options = {
scale: 0.8,
backgroundColor: canvasBg,
removeContainer: true,
allowTaint: true
};
return html2canvas(captureElement, options)
.then((canvas: HTMLCanvasElement) => {
canvas.style.display = 'none';
document.body.appendChild(canvas);
return canvas;
})
.then((canvas: HTMLCanvasElement) => {
const image = canvas
.toDataURL('image/png')
.replace('image/png', 'image/octet-stream');
const a = document.createElement('a');
a.setAttribute('download', `${imageName}.png`);
a.setAttribute('href', image);
a.click();
canvas.remove();
});
};
I am trying to cover: return html2canvas... till the end.
I tried-
jest.mock('html2canvas', () => {
html2canvas: jest.fn();
})
and
jest.mock('html2canvas', () => () => ({
then : jest.fn(() => ({
then : jest.fn(() => ({
toHaveBeenCalled : jest.fn().mockResolvedValue({})
}))
}))
}));
const element = document.createElement('div');
element.id = "test";
document.body.appendChild(element);
let de = downloadElement('test', 'testImage') as any;
expect(de).toBeCalled();
I tried mockResolvedValue as well.
de = jest.fn().mockResolvedValue({});
Looks like I can't find the way to cover it. Any help appreciated.