0

I need to do a unit test of the promise of html2canvas with Jasmine in an Ionic project that uses Angular.

The html2canvas library is imported like this, directly without the brackets:

import html2canvas from 'html2canvas';

The method with the promise is called in this manner:

html2canvas(DATA).then(canvas => {
  // code
}

We have to consider how the method is declared in its definition in the library, in which the method is exported with export default:

declare const html2canvas: (element: HTMLElement, options?: Partial<Options>) => Promise<HTMLCanvasElement>;
export default html2canvas;

How can I spy this function with Jasmine to make the unit test to proceed into the then block? As commented in other solutions, I tried to spy on default like this that but it's not working, it's detecting default as a method and it doesn't exist.

import * as canvas from 'html2canvas';
spyOn(canvas, 'default')
Error: <spyOn> : default() method does not exist
Usage: spyOn(<object>, <methodName>)

I tried other uses of the spyOn function but none of them worked. How I should test this in Jasmine?

gazops
  • 41
  • 3
  • You're most likely facing this issue: https://stackoverflow.com/a/62935131/7365461. The post I linked shows how to solve it by making a class/service that does everything that `html2canvas` does for you. It also links a github thread showing what the issue is and it occurs in later versions of TypeScript. – AliF50 Feb 23 '23 at 13:49
  • @AliF50 Thanks! I guess it's not possible to spy the function directly and Jasmine hasn't made a fix for this case. The solution then would be to create a class that wraps the function and to spy that class. – gazops Feb 23 '23 at 14:40
  • Right, exactly. – AliF50 Feb 23 '23 at 20:14

0 Answers0