[英]Test image onload inside react component using enzyme, sinon
I'm trying to test that a function callback is being called for an image inside my component. 我正在尝试测试组件内部的图像正在调用函数回调。
This is the component: 这是组件:
const ImageById = (props) => {
return (
<div>
<img src={props.url} onLoad={props.onLoad} onError={props.onError} />
</div>
);
};
And my test mounts the component and then spy the callback function: 然后我的测试会挂载该组件,然后监视回调函数:
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);
});
});
The test fails because the inner Img
tag is never calling its onload
nor onerror
methods. 测试失败,因为内部
Img
标记从不调用其onload
或onerror
方法。 In production the code is working fine, it might be something related to the test environment. 在生产中,代码运行良好,可能与测试环境有关。 Its like
Img
tag doesn't react to the url
being set. 就像
Img
标签一样,它对设置的url
没有反应。
I discovered that mounting the component doesn't causes load
and error
events to occur. 我发现安装该组件不会导致发生
load
和error
事件。 I found a way of simulate them using TestUtils
like this: 我找到了一种使用
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);
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.