Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

431
Visualizações
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
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda