Reactjs 测试函数是否调用了react和enzyme
我正在尝试测试react组件中的一种方法。它是在点击一个按钮后被调用的,所以我用酶进行了模拟Reactjs 测试函数是否调用了react和enzyme,reactjs,sinon,enzyme,Reactjs,Sinon,Enzyme,我正在尝试测试react组件中的一种方法。它是在点击一个按钮后被调用的,所以我用酶进行了模拟 it('clone should call handleCloneClick when clicked', () => { const cloneButton = wrapper.find('#clone-btn'); cloneButton.simulate('click'); }); 我的组件方法如下: _handleCloneClick(event) {
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,我如何测试它是否被成功调用 有两个选项,在渲染组件之前,您可以监视组件原型的
\u 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>);
}
}
您应该知道,如果您向原型添加间谍,它也会改变后续测试的行为。严格来说,您不应该测试私有方法。您应该监视
handleClone
道具以测试预期行为。我在尝试此操作时出现以下错误:“expect(jest.fn())[.not]。toHaveBeenCalled()jest.fn()值必须是模拟函数或spy。接收到:函数:[function proxy]”@您可以使用sinon.createSandbox
创建一个沙盒,并在每次测试后调用sandbox.restore()
。
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
});
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
});