2017-07-20 102 views
2

我试图测试一个函数回调函数被调用用于我的组件内部的图像。使用酶,sinon测试映像内部反应组件内部

这是组件:

const ImageById = (props) => { 
    return (
    <div> 
     <img src={props.url} onLoad={props.onLoad} onError={props.onError} /> 
    </div> 
); 
}; 

而且我的测试安装的组件,然后间谍回调函数:

describe('ImageById',() => { 
    it('should call load or error',() => { 
    let callbackSpy = sinon.spy(); 
    let comp = mount(ImageById, {url: 'some-url', onLoad: callbackSpy, onError: callbackSpy}); 
    expect(callbackSpy.called).to.equal(true); 
    }); 
}); 

测试失败,因为内部Img标签是永远不会调用其onload也不onerror方法。在生产中,代码工作正常,可能与测试环境有关。它就像Img标记对设置的url没有反应。

回答

1

我发现安装组件并不会导致loaderror事件发生。我发现一种使用TestUtils这样的模拟方法:

var Wrapper = React.createClass({ 
    render: function() { 
    return (
     <div>{this.props.children}</div> 
    ); 
    }, 
    propTypes: { 
    children: PropTypes.object 
    } 
}); 

describe('ImageById',() => { 
    it('should call load or error',() => { 
    let callbackSpy = sinon.spy(); 
    // need to wrap `Images` inside a class component because `renderIntoDocument` 
    // wont render pure functional components. 
    // https://github.com/facebook/react/issues/4692#issuecomment-163029873 
    var component = TestUtils.renderIntoDocument(<Wrapper><ImageById url={'some-url'} onLoad={callbackSpy} onError={callbackSpy} /></Wrapper>); 
    var image = TestUtils.findRenderedDOMComponentWithTag(component, 'img'); 
    TestUtils.Simulate.load(image); 
    expect(callbackSpy.called).to.equal(true); 
    }); 
});