我创建了一个 React 组件来加载图像并确定图像是否成功加载。
import React from 'react';
import PropTypes from 'prop-types';
import { LOADING, SUCCESS, ERROR } from '../helpers';
class Image extends React.Component {
static propTypes = {
onError: PropTypes.func,
onLoad: PropTypes.func,
src: PropTypes.string.isRequired,
}
static defaultProps = {
onError: null,
onLoad: null,
}
constructor(props) {
super(props);
this.state = { imageStatus: LOADING };
this.initImage();
}
componentDidMount() {
this.image.onload = this.handleImageLoad;
this.image.onerror = this.handleImageError;
this.image.src = this.props.src;
}
initImage() {
this.image = document.createElement('img');
this.handleImageLoad = this.handleImageLoad.bind(this);
this.handleImageError = this.handleImageError.bind(this);
}
handleImageLoad(ev) {
this.setState({ imageStatus: SUCCESS });
if (this.props.onLoad) this.props.onLoad(ev);
}
handleImageError(ev) {
this.setState({ imageStatus: ERROR });
if (this.props.onError) this.props.onError(ev);
}
render() {
switch (this.state.imageStatus) {
case LOADING:
return this.renderLoading();
case SUCCESS:
return this.renderSuccess();
case ERROR:
return this.renderError();
default:
throw new Error('unknown value for this.state.imageStatus');
}
}
}
export default Image;
我正在尝试使用 Jest + Enzyme 创建一个测试来测试图像何时无法加载。
it('should call any passed in onError after an image load error', () => {
const onError = jest.fn();
mount(<Image {...props} src="crap.junk"} onError={onError} />);
expect(onError).toHaveBeenCalled();
});
无论我做什么,Jest 总能找到一种方法来成功渲染图像。即使将 src 设置为 false 仍然以某种方式呈现图像。有谁知道你到底是如何强迫 jest 使图像加载失败的?