我有一个组件,可以显示上传的图像的缩略图,如下所示:
class Thumb extends Component {
state = {
loading: false,
thumb: undefined,
};
componentWillReceiveProps(nextProps) {
if (!nextProps.file) {
return;
}
this.setState({ loading: true }, () => {
const reader = new FileReader();
reader.onloadend = () => {
this.setState({ loading: false, thumb: reader.result });
};
reader.readAsDataURL(nextProps.file);
});
}
render() {
const { file } = this.props;
const { loading, thumb } = this.state;
const imageStyle = {
maxWidth: '100%',
height: 'auto',
marginTop: 10,
};
if (!file) {
return null;
}
if (loading) {
return <p>loading...</p>;
}
return (
<img
alt={file.name}
height={200}
src={thumb}
style={imageStyle}
width={200}
/>
);
}
}
export default Thumb;
它几乎是从https://hackernoon.com/formik-handling-files-and-recaptcha-209cbeae10bc开始。 我希望能够使用快照测试来测试此组件,但不确定如何将prop(图像文件)模拟到它。
我当前的测试文件如下:
import React from 'react';
import { shallow } from 'enzyme';
import { Thumb } from 'admin/components/FormControls/Thumbnail';
import errorImage from 'admin/assets/error.png';
describe('<Thumb />', () => {
it('should render the correct snapshot', () => {
const wrapper = shallow(<Thumb file={errorImage} />);
expect(wrapper).toMatchSnapshot();
});
});
目前,这使我抛出TypeError: Cannot read property 'prototype' of undefined
。