0

I've been tasked with testing some pretty heavy duty functions and unfortunately I have no idea where to start with this one.

The function in question is this one:

    export async function getCroppedImg(imageSrc, pixelCrop) {
      const image = await createImage(imageSrc);
      const canvas = document.createElement("canvas");
      const ctx = canvas.getContext("2d");

      // set width to double image size to allow for a safe area for the
      // image to rotate in without being clipped by canvas context
      canvas.width = image.width * 2;
      canvas.height = image.height * 2;

      // translate canvas context to a central location to allow rotating around the center.
      ctx.translate(image.width, image.height);
      ctx.translate(-image.width, -image.height);

      // draw rotated image and store data.
      ctx.drawImage(image, image.width / 2, image.height / 2);
      const data = ctx.getImageData(0, 0, image.width * 2, image.height * 2);

      // set canvas width to final desired crop size - this will clear existing context
      canvas.width = pixelCrop.width;
      canvas.height = pixelCrop.height;

      // paste generated rotate image with correct offsets for x,y crop values.
      ctx.putImageData(data, 0 - image.width / 2 - pixelCrop.x, 0 - image.height / 2 - pixelCrop.y);

      // As Base64 string
      // return canvas.toDataURL('image/jpeg');

      // As a blob

      const preview = new Promise(resolve => {
        canvas.toBlob(file => {
          resolve(URL.createObjectURL(file));
        }, "image/jpeg");
      });

      const base64String = canvas.toDataURL();

      return Promise.all([preview, base64String]);
    }

The other function called in this one is the createImage function that looks like this:

    export const createImage = url =>
      new Promise((resolve, reject) => {
        const image = new Image();
        image.addEventListener("load", () => resolve(image));
        image.addEventListener("error", error => reject(error));
        image.setAttribute("crossOrigin", "anonymous"); // needed to avoid cross-origin issues on CodeSandbox
        image.src = url;
      });

This has already been tested to 100% coverage so I know I've got to mock it to test the getCroppedImage function but I haven't got a clue where to start with this one...

skyboyer
  • 22,209
  • 7
  • 57
  • 64
Daniel Cross
  • 51
  • 13
  • you definitely [need to install](https://stackoverflow.com/questions/33269093/how-to-add-canvas-support-to-my-tests-in-jest) `canvas` package otherwise `getContext("2d")` will return `undefined` in jest – skyboyer Jan 03 '20 at 08:25

1 Answers1

0

You can consider spying on createImage and mock the response as a resolved promise.

const spy = jest.spyOn(yourMockedModule, 'createImage').mockImplementation(() => Promise.resolve(....));
wentjun
  • 40,384
  • 10
  • 95
  • 107