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

时间:2020-01-02 23:03:13

标签: reactjs promise nested jestjs

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

有问题的功能是这个:

    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函数,但我不知道从何处着手...

1 个答案:

答案 0 :(得分:0)

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

const spy = jest.spyOn(yourMockedModule, 'createImage').mockImplementation(() => Promise.resolve(....));