无法找出以下错误:使用Jest酶-React JS
**方法“模拟”旨在在1个节点上运行。找到0个。 **
我正在尝试测试onClick =的props / properties。此文件多次调用onClick。我尝试应用与用于其他文件相同的方法,但目前无法正常工作 范例: onClick调用(this.props):
<div className="continue_button_div">
<button className='cancel_button' id='cancel-add-new-view'
title='Cancel' type='button' onClick={() =>
{this.props.hideAddViewModal()}}>Cancel</button>
</div>
<div className="continue_button_div">
<button className='cancel_button' id='cancel-add-new-view' title='Cancel'
type='button' onClick={() =>
{this.props.hideAddViewModal()}}>Cancel</button>
我对测试文件进行了以下操作。
// jest mock functions (mocks this.props.func)
const hideAddViewModal = jest.fn();
// defining this.props
const baseProps = {
hideAddViewModal,
describe('AddViewModal Test', () => {
let wrapper;
let tree;
beforeEach(() => wrapper = shallow(<AddViewModal {...baseProps} />));
it("should call hideAddViewModal functions on button click", () => {
// Reset info from possible previous calls of these mock functions:
baseProps.hideAddViewModal.mockClear();
wrapper.setProps({
});
// Find the button and call the onClick handler
wrapper.find('.sidemodal_addnew_x').at(0).simulate("click"); //pass
wrapper.find('.cancel_button').at(0).simulate("click"); //fails
wrapper.find('.cancel_button').at(1).simulate("click");//fails
但是我一直得到上面描述的错误。
另一个onClick示例。我是否也可以将上述方法也应用于该方法,或者如何确保onClick调用clearviewName =()= {
clearViewName = () => {
this.setState({ViewName: ''});
this.setState({Requests: ''});
this.setState({allowNext: false})
Render(){
<div className="fullmodal_title_select"><span
className="fullmodal_title_add_done" onClick={() => {this.clearViewName()}}
>Add View </span><FontAwesome name='right' className='fa-angle-right' />
Select a request</div>
谢谢
答案 0 :(得分:0)
基本上就是这样:
it('For first cancel button', () => {
// Reset info from possible previous calls of these mock functions:
baseProps.hideAddViewModal.mockClear();
wrapper.setProps({});
// Find the button and call the onClick handler
wrapper.setState({
ViewName: 'something',
allowNext: true,
})
wrapper.find('.cancel_button').at(0).simulate('click');
})
然后
it('For second cancel button', () => {
// Reset info from possible previous calls of these mock functions:
baseProps.hideAddViewModal.mockClear();
wrapper.setProps({});
// Find the button and call the onClick handler
wrapper.setState({
ViewName: 'something',
RequestID: 'something',
Requests: ['random, I dont know the type inside here so']
})
wrapper.find('.cancel_button').at(0).simulate('click');
})
还有什么理由要编写这样的点击处理程序
onClick={() => {
this.onContinueClick();
}}
代替此
onClick={this.onContinueClick}
关于另一个问题,
您可以编辑baseProps
如下所示:
const baseProps = {
hideAddViewModal,
location: {
pathname: 'home'
},
}