Javascript 使用酶sinon在反应组件内部加载测试图像
我试图测试是否正在为我的组件中的图像调用函数回调 这是一个组件:Javascript 使用酶sinon在反应组件内部加载测试图像,javascript,sinon,chai-enzyme,Javascript,Sinon,Chai Enzyme,我试图测试是否正在为我的组件中的图像调用函数回调 这是一个组件: const ImageById = (props) => { return ( <div> <img src={props.url} onLoad={props.onLoad} onError={props.onError} /> </div> ); }; 测试失败,因为内部Img标记从未调用其onload或onerror方法。在生产环境中,代码运行良
const ImageById = (props) => {
return (
<div>
<img src={props.url} onLoad={props.onLoad} onError={props.onError} />
</div>
);
};
测试失败,因为内部
Img
标记从未调用其onload
或onerror
方法。在生产环境中,代码运行良好,可能与测试环境有关。它类似于Img
标记,不会对设置的url
做出反应。我发现安装组件不会导致加载
和错误
事件发生。我找到了一种使用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);
});
});
var Wrapper=React.createClass({
渲染:函数(){
返回(
{this.props.children}
);
},
道具类型:{
子项:PropTypes.object
}
});
描述('ImageById',()=>{
它('应该调用加载或错误',()=>{
让callbackSpy=sinon.spy();
//需要将`Images`包装在类组件中,因为`renderIntoDocument`
//不会渲染纯功能组件。
// https://github.com/facebook/react/issues/4692#issuecomment-163029873
var component=TestUtils.renderIntoDocument();
var image=TestUtils.findRenderedomComponentWithTag(组件“img”);
TestUtils.Simulate.load(图像);
expect(callbackSpy.called).to.equal(true);
});
});
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);
});
});