How to test asnyc code with Jest ( or test “image.

2019-05-20 06:34发布

问题:

[Edited] : I have change my code with promise way .

I am writing react with this starter created by facebook, and I'm a newbie about testing.

Now I have a component about image, it has a function to check Image size:

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

And test snippet:

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

After Running the test, I got this error :

TypeError: Cannot read property 'toBe' of undefined

The question is:

  1. How can I test `loadImg in right way ?
  2. what's the general pattern to test checkSize ?

thank you.

回答1:

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


回答2:

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