小编典典

如何使用Jest测试asnyc代码(或使用jsdom测试“ image.onload”)

reactjs

[编辑]:我已经用诺言方式更改了代码。

我正在写与Facebook创建的这个入门工具的反应,我是有关测试的新手。

现在我有一个有关图像的组件,它具有检查图像大小的功能:

import React, { Component } from 'react';


class ImagePart extends Component {
    .....
    //  check size.
    checkSize(src, width, height){
        this.loadImg(src)
        .then((obj) => {
            return (obj.width >= width && obj.height >= height)
            ? true : false;
        })
        .catch((msg)=> {
            dosomething
        });
    }
    // load image and return a promise.
    loadImg(src){
        return new Promise((resolve, reject) => {
            let imageObj = new Image();
            imageObj.onload = (evt) => {
                resolve(evt.target);
            }
            imageObj.error = (err) =>{
                reject(err);
            }
            imageObj.src = src; 
        })
    }
    .....
}

和测试代码段:

import React from 'react';
import ReactDOM from 'react-dom';
import ImagePart from './ImagePart';



it('checking image size without error', () => {
    const image = new ImagePart();
    const img300_300 = 'https://someImage.png';
    expect(image.loadImg(img300_300).width).resolves.toBe(300);
    // ??? test checkSize
});

运行测试后,出现此错误:

TypeError:无法读取未定义的属性“ toBe”

问题是:

  1. 我如何以正确的方式测试`loadImg?
  2. 测试checkSize的一般模式是什么?

谢谢。


阅读 367

收藏
2020-07-22

共1个答案

小编典典

当前的实现checkSize是异步的,并且始终返回undefined

您应该使用回调或返回Promise

function checkSizeWithCallback(src, width, height, callback) {
  const image = new Image();
  image.onload = evt => {
    const result = evt.target.width >= width && evt.target.height >= height;
    callback(null, result);
  };
  image.onerror = // TODO: handle onerror
  image.src = src; 
}


it('...', done => {
  checkSizeWithCallback(/* args */, (err, result) => {
    expect(result).toEqual(true);
    done(err);
  });
});

function checkSizeWithPromise(src, width, height) {
  return new Promise((resolve, reject) => {
    const image = new Image();
    image.onload = evt => {
      const result = evt.target.width >= width && evt.target.height >= height;
      resolve(result);
    };
    image.onerror = // TODO: handle onerror
    imageObj.src = src; 
  });
}


it('...', () => {
  return checkSizeWithPromise(/* args */)
    .then(result => {
      expect(result).toEqual(true);
  });
});
2020-07-22