javascript - How to test asnyc code with Jest ( or test "image.onload" with jsdom ) -


[edited] : have change code promise way .

i writing react this starter created facebook, , i'm newbie testing.

now have component image, has function check image size:

import react, { component } '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 , return 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 'react'; import reactdom 'react-dom'; import imagepart './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 test, got error :

typeerror: cannot read property 'tobe' of undefined

the question is:

  1. how can test `loadimg in right way ?
  2. what's general pattern test checksize ?

thank you.

you should able use done call when testing async code. https://facebook.github.io/jest/docs/asynchronous.html

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

Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

thorough guide for profiling racket code -