测试函数是否被称为 react 和 enzyme
Test if function is called react and enzyme
我正在尝试测试我的 React 组件中的一种方法。单击按钮后会调用它,因此我可以使用酶
进行模拟
it('clone should call handleCloneClick when clicked', () => {
const cloneButton = wrapper.find('#clone-btn');
cloneButton.simulate('click');
});
我的组件方法在这里:
_handleCloneClick(event) {
event.preventDefault();
event.stopPropagation();
this.props.handleClone(this.props.user.id);
}
当用户点击模拟中的按钮时,_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>);
}
}
在你的测试中:
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
});
或者,您可以尝试在渲染组件后设置一个 spy 并在之后调用 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
});
我正在尝试测试我的 React 组件中的一种方法。单击按钮后会调用它,因此我可以使用酶
进行模拟 it('clone should call handleCloneClick when clicked', () => {
const cloneButton = wrapper.find('#clone-btn');
cloneButton.simulate('click');
});
我的组件方法在这里:
_handleCloneClick(event) {
event.preventDefault();
event.stopPropagation();
this.props.handleClone(this.props.user.id);
}
当用户点击模拟中的按钮时,_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>);
}
}
在你的测试中:
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
});
或者,您可以尝试在渲染组件后设置一个 spy 并在之后调用 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
});