How to test asnyc code with Jest ( or test “image.onload” with jsdom )

╄→尐↘猪︶ㄣ 提交于 2019-12-01 09:06:08

The current implementation of checkSize is asynchronous and always returns undefined.

You should either use a callback or return a 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);
  });
});

You should be able to use the done call back when testing async code. https://facebook.github.io/jest/docs/asynchronous.html

In your case i would do

it('checking image size without error', (done) => {
    const image = new ImagePart();
    const img300_300 = 'https://someImage.png';
    expect(image.checkSize(img300_300,200,200)).toEqual(true);
    expect(image.checkSize(img300_300,300,300)).toEqual(true);
    expect(image.checkSize(img300_300,300,200)).toEqual(false);
    expect(image.checkSize(img300_300,200,300)).toEqual(false);
    expect(image.checkSize(img300_300,400,400)).toEqual(false);
    done();
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!