测试在Jest中调用Promises的嵌套函数

问题描述 投票:0回答:1

我的任务是测试一些非常强大的功能,但不幸的是,我不知道从哪里开始。

有问题的功能是这个:

    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]);
    }

此函数中调用的另一个函数是如下所示的createImage函数:

    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;
      });

[已经对它进行了100%的覆盖率测试,所以我知道我必须对其进行模拟以测试getCroppedImage函数,但我不知道从何处开始这一线索...

我的任务是测试一些非常强大的功能,但不幸的是,我不知道从哪里开始。有问题的功能是这样的:export async function ...

reactjs promise nested jest
1个回答
0
投票

您可以考虑监视createImage,并将响应模拟为已解决的承诺。

© www.soinside.com 2019 - 2024. All rights reserved.