Jest Error: Uncaught [TypeError: XXX is not a function]

Viewed 639

I've a onClick on component1 that calls a hook in component2 passing props to him:

component1:

function test(){
    return(
       <div
          onClick=(() => this.props.changeExample(this.props.example)}
       />
}

component2:

changeExample(example){
    ...do some things
}

But when I try to test the onClick event of component1 with the following code:

it("test onClick", () =>{
    let wrapper
     wrapper = shallow <component1 />
     const eventWrapper = wrapper.find("div")
     eventWrapper.simulate("click")
}

I got the following error:

Error: Uncaught [TypeError: _this.props.changeExample is not a function]

1 Answers

You would need to mock that prop, then you can check if it have been called, something like:

it("test onClick", () => {
  const mockOnClick = jest.fn();
  const wrapper = shallow <component1 changeExample={mockOnClick} />

  const eventWrapper = wrapper.find("div");
  eventWrapper.simulate("click");

  expect(mockOnClick).toHaveBeenCalledTimes(1);
}
Related