我在React中有一个带有onChange事件的组件。在下面的代码中,我需要声明在
时调用正确的方法this.props.onChangeImage()
在Gallery组件中调用。
export class Form extends React.PureComponent {
componentDidMount = () => {
this.props.getUser();
this.props.getImages();
this.props.getBoards();
}
render() {
if (this.props.pin === null) {
let boards = [];
boards = this.props.boards;
boards = boards.data.map(
(item) => <MenuItem key={item.id.toString()} value={item.name} primaryText={item.name} />
);
return (
<div>
<Helmet
title="Form"
meta={[
{ name: 'description', content: 'Description of Form' },
]}
/>
<Gallery images={this.props.images} onChange={this.props.onChangeImage} />
</div>
);
}
return (<div className="spinner-container"><CircularProgress /></div>);
}
}
下面,在onChangeImage方法中,我试图断言调用sendEventToParentWindow方法。
function mapDispatchToProps(dispatch) {
return {
onChangeImage: (event) => {
dispatch(createPinImage(event.target.value));
sendEventToParentWindow({
action: 'change-image',
description: 'Change image',
});
},
};
}
function sendEventToParentWindow(message) {
window.postMessage(message, window.location.href);
}
export default connect(mapStateToProps, mapDispatchToProps)(Form);
我已经在这里查看了一些答案,虽然这个答案看起来最接近,但它并没有让我到那里:Jest - mocking a function call
编辑:这是我的测试,我认为这是错误的,因为它指定模拟函数直接调用onChange,当它真的应该调用函数,而函数又调用mock。我需要以某种方式调用onImageChange函数,然后验证我的间谍是否被调用。import Gallery from '../index';
import * as formIndex from '../../../containers/Form';
describe('<Gallery />', () => {
it('Expect sendMessageToParentWindow to be called on image change', () => {
const sendEventToParentWindowMock = jest.spyOn(formIndex, 'sendEventToParentWindow');
const gallery = shallow(<Gallery images={imagesMockData} onChange={sendEventToParentWindowMock} />);
gallery.find('input#image-1').simulate('change');
expect(sendEventToParentWindowMock).toBeCalled();
});
}
答案 0 :(得分:9)
正如我在评论中提到的,您可以将模拟函数作为prop传递,其实现将包含对sendEventToParentWindow
函数的调用。即你需要创建两个模拟函数。
onChangeImage
模拟功能。sendEventToParentWindow
带有实现的模拟函数,其中实现只包含对describe('<Gallery />', () => {
it('Expect sendMessageToParentWindow to be called on image change', () => {
const sendEventToParentWindowMock = jest.fn();
const onChangeImageMock = jest.fn(() => {
sendEventToParentWindowMock();
});
const gallery = shallow(<Gallery images={imagesMockData} onChange={onChangeImageMock} />); // Passing the mocked onChangeImage as prop
gallery.find('input#image-1').simulate('change');
expect(sendEventToParentWindowMock).toBeCalled();
});
}
模拟函数的调用。所以测试看起来像这样,
{{1}}
希望有所帮助:)