Jak*_*ake 14 sinon reactjs enzyme
我正在尝试测试我的react组件中的一个方法.按下按钮后调用它,所以我用酶进行了模拟
it('clone should call handleCloneClick when clicked', () => {
const cloneButton = wrapper.find('#clone-btn');
cloneButton.simulate('click');
});
Run Code Online (Sandbox Code Playgroud)
我的组件方法在这里:
_handleCloneClick(event) {
event.preventDefault();
event.stopPropagation();
this.props.handleClone(this.props.user.id);
}
Run Code Online (Sandbox Code Playgroud)
当用户点击模拟中的按钮时,会调用_handleCloneClick,如何测试成功调用它?
有两种选择,要么_handleCloneClick在呈现组件之前就监视组件的原型,要么:
export default class cloneButton extends Component {
constructor(...args) {
super(...args);
this. _handleCloneClick = this. _handleCloneClick.bind(this);
}
_handleCloneClick() {
event.preventDefault();
event.stopPropagation();
this.props.handleClone(this.props.user.id);
}
render() {
return (<button onClick={this. _handleCloneClick}>Clone</button>);
}
}
Run Code Online (Sandbox Code Playgroud)
并在您的测试中:
it('clone should call handleCloneClick when clicked', () => {
sinon.spy(cloneButton.prototype, '_handleCloneClick');
const wrapper = mount(<cloneButton/>);
wrapper.find('#clone-btn').simulate('click');
expect(spy).toHaveBeenCalled() //adept assertion to the tool you use
});
Run Code Online (Sandbox Code Playgroud)
或者,您可以尝试在渲染组件后设置间谍并wrapper.update()随后调用:
it('clone should call handleCloneClick when clicked', () => {
const wrapper = mount(<cloneButton/>);
sinon.spy(wrapper.instance(), "_handleCloneClick");
wrapper.update();
wrapper.find('#clone-btn').simulate('click');
expect(spy).toHaveBeenCalled() //adept assertion to the tool you use
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
23674 次 |
| 最近记录: |