How do you use Jest to test img.onerror

前端 未结 2 2014
迷失自我
迷失自我 2020-12-11 09:36

I\'ve created a React component that loads an image and determines if the image loaded successfully or not.

import React from \'react\';
import PropTypes fro         


        
2条回答
  •  甜味超标
    2020-12-11 09:58

    You could mock document.createElement:

     it('should call any passed in onError after an image load error', () => {
        const img = {}
        global.document.createElement = (type) => type === 'img' ? img : null
        const onError = jest.fn();
        mount();
        img.onload()
        expect(onError).toHaveBeenCalled();
      });
    

提交回复
热议问题