Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

422
Views
Unit testing nested function, third-party function mocking. Jest

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.

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!