Javascript 模拟onClick的事件处理程序

Javascript 模拟onClick的事件处理程序,javascript,reactjs,testing,jestjs,Javascript,Reactjs,Testing,Jestjs,我需要写一个测试来模拟点击一个V形来改变页面。onClick发生时调用的函数有一个合成事件处理程序作为参数,我需要一些方法来模拟这个事件处理程序(或者用相同的功能重写代码)。我目前得到的错误 TypeError:无法读取未定义的属性“preventDefault” 编辑:所有内容都包含在setTimeout中,因为在解决多个承诺之前,按钮不会呈现 这是函数代码 handleClick(e) { e.preventDefault(); if (this.state.currentPage

我需要写一个测试来模拟点击一个V形来改变页面。onClick发生时调用的函数有一个合成事件处理程序作为参数,我需要一些方法来模拟这个事件处理程序(或者用相同的功能重写代码)。我目前得到的错误

TypeError:无法读取未定义的属性“preventDefault”

编辑:所有内容都包含在setTimeout中,因为在解决多个承诺之前,按钮不会呈现

这是函数代码

handleClick(e) {
  e.preventDefault();
  if (this.state.currentPage > 0) {
    this.setState({
      currentPage: this.state.currentPage - 1
    });
  }
};
下面是render函数内部的代码

<Icon
  link
  href="#"
  onClick={this.handleClick}
 >
   chevron_left
 </Icon>

雪佛龙左
最后是到目前为止我的测试代码

 test("Chevron left", done=>{
  Enzyme.configure({ adapter: new Adapter() });
  const wrapper = shallow(
      <App/>
  );
  expect(wrapper.exists()).toBe(true);

  setTimeout(()=>{
      wrapper.instance().state.currentPage = 1;
      wrapper.find("Icon").at(0).simulate("click");
      expect(wrapper.instance().state.currentPage).toEqual(0);
      done();
  },0)
});
测试(“V形左”,完成=>{
configure({adapter:newadapter()});
常数包装=浅(
);
expect(wrapper.exists()).toBe(true);
设置超时(()=>{
wrapper.instance().state.currentPage=1;
包装器。在(0)处查找(“图标”)。模拟(“单击”);
expect(wrapper.instance().state.currentPage).toEqual(0);
完成();
},0)
});

我很确定在
handleClick
方法(在本例中)中不需要
e.preventDefault()
。你可以把它取下来,就没事了

但是,如果您遇到此问题(如
表单
提交,或者您发现页面自动刷新,或者您希望阻止默认操作事件),则只需在模拟的
单击
事件中添加模拟的
预防默认

wrapper.find("Icon").at(0).simulate("click", { preventDefault: () => null });
为确保正确的状态更改,请将handleClick方法更改为以下方法之一(因为
setState
是异步的,使用其值可确保在比较时准确):

选项1——handleClick方法:

handleClick() {
  this.setState(prevState => {
     const nextPage =  prevState.currentPage - 1; // subtract 1 from current page

     return nextPage > 0 // if next page is greater than 0
       ? { currentPage: nextPage } // subtract 1
       : { null } // else do nothing

  })
}
handleClick() {
  this.setState(prevState => ({
     currentPage: prevState.currentPage > 0 ? prevState.currentPage - 1 : 0 // if current page is greater than 0, subtract 1, else set it 0
  }))
}
选项2——handleClick方法:

handleClick() {
  this.setState(prevState => {
     const nextPage =  prevState.currentPage - 1; // subtract 1 from current page

     return nextPage > 0 // if next page is greater than 0
       ? { currentPage: nextPage } // subtract 1
       : { null } // else do nothing

  })
}
handleClick() {
  this.setState(prevState => ({
     currentPage: prevState.currentPage > 0 ? prevState.currentPage - 1 : 0 // if current page is greater than 0, subtract 1, else set it 0
  }))
}

令人惊叹的!我正在测试别人的代码,并质疑是否有必要拥有它。不管你的解决方案如何奏效!当然。有关更好的
handleClick
回调,请参见更新的答案。