mercredi 13 février 2019

Mocking SyntheticEvent handler for onClick

I need to write a test to simulate the click on a chevron for changing pages. The function called when onClick occurs has a synthetic event handler as a parameter and I need some way to mock this event handler (or rewrite the code with the same functionality) . I currently get the error

TypeError: Cannot read property 'preventDefault' of undefined

Edit: Everything is contained in setTimeout because the buttons won't render until several promises have been resolved

Here is the function code

handleClick(e) {
  e.preventDefault();
  if (this.state.currentPage > 0) {
    this.setState({
      currentPage: this.state.currentPage - 1
    });
  }
};

here is the code inside the render function

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

And finally my test code thus far

 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)
});

Aucun commentaire:

Enregistrer un commentaire