我正在开发一个包装器组件,用于在 React 中顺利加载图像。我将酶与 mocha、chai 和 sinon 一起使用来对我的组件进行单元测试。在这里的测试中,我试图测试:
加载图像时更新组件的状态
组件上的
onLoad
实例方法被调用
const wrapper = shallow( ); 常量 onLoad = wrapper.find('img').props().onLoad; 常量 onLoadSpy = sinon.spy(onLoad); 包装器.更新(); 常量状态 = wrapper.state().status; 期望(onLoadSpy).to.have.been.call; 期望(状态).to.equal('已加载');
我发现无论是对状态的更新都没有反映在酶上,也没有更新onLoad
间谍的调用计数。这是测试的相应代码:
export default class Image extends Component {
constructor(props) {
super(props);
if (props.src != null && typeof props.src === 'string') {
this.state = {
status: LOADING,
};
} else {
this.state = {
status: PENDING,
};
}
this.onLoad = this.onLoad.bind(this);
}
onLoad() {
this.setState({
status: LOADED,
});
}
render() {
//lots of code above the part we care about
const defaultImageStyle = style({
opacity: 0,
transisition: 'opacity 150ms ease',
});
const loadedImageStyle = style({
opacity: 1,
});
let imageStyle = defaultImageStyle;
if (this.state.status === LOADED) {
imageStyle = merge(defaultImageStyle, loadedImageStyle);
} else {
imageStyle = defaultImageStyle;
}
let image;
if (alt != null) {
image = (<img
className={imageStyle}
src={src}
width={width}
height={height}
alt={alt}
onLoad={this.onLoad}
/>);
} else {
image = (<img
className={imageStyle}
src={src}
width={width}
height={height}
role="presentation"
onLoad={this.onLoad}
/>);
}
let statusIndicator = null;
if (this.state.status === LOADING) {
statusIndicator = (<div className={loadingStyle}></div>);
}
return (<div className={wrapperStyle}>
{statusIndicator}
{image}
</div>);
}}
查看完整代码以获得更好的上下文: